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 |
|---|---|---|---|---|---|---|---|---|
WoLpH/celery | celery/app/task/__init__.py | Python | bsd-3-clause | 27,392 | 0.000548 | # -*- coding: utf-8 -*-"
import sys
import threading
from celery.datastructures import ExceptionInfo
from celery.exceptions import MaxRetriesExceededError, RetryTaskError
from celery.execute.trace import TaskTrace
from celery.registry import tasks, _unpickle_task
from celery.result import EagerResult
from celery.utils... |
#: The application instance associated with this task class.
app = None
#: Name of the task.
name = None
#: If :const:`True` the task is an abstract base class.
abstract = True
#: If disabled the worker will not forward magic keyword arguments.
| #: Deprecated and scheduled for removal in v3.0.
accept_magic_kwargs = False
#: Request context (set when task is applied).
request = Context()
#: Destination queue. The queue needs to exist
#: in :setting:`CELERY_QUEUES`. The `routing_key`, `exchange` and
#: `exchange_type` attributes wil... |
cellml/libcellml | tests/resources/generator/hodgkin_huxley_squid_axon_model_1952/model.external.py | Python | apache-2.0 | 5,138 | 0.00506 | # The content of this file was generated using the Python profile of libCellML 0.2.0.
from enum import Enum
from math import *
__version__ = "0.3.0"
LIBCELLML_VERSION = "0.2.0"
STATE_COUNT = 3
VARIABLE_COUNT = 19
class VariableType(Enum):
VARIABLE_OF_INTEGRATION = 1
STATE = 2
CONSTANT = 3
COMPUTED... | ]+25.0)/10.0)-1.0)
variables[12] = 4.0*exp(variables[0]/18.0)
rates[0] = variables[11]*(1.0-states[0])-variables[12]*states[0]
variables[13] = 0.07*exp(variables[0]/20.0)
variables[14] = 1.0/(exp((variables[0]+30.0)/10.0)+1.0)
rates[1] = variables[13]*(1.0-states[1])-variables[14]*states[1]
vari... | riables[0]/80.0)
rates[2] = variables[17]*(1.0-states[2])-variables[18]*states[2]
def compute_variables(voi, states, rates, variables, external_variable):
variables[0] = external_variable(voi, states, variables, 0)
variables[6] = -20.0 if and_func(geq_func(voi, 10.0), leq_func(voi, 10.5)) else 0.0
var... |
riveridea/gnuradio | gr-digital/python/digital/psk_constellations.py | Python | gpl-3.0 | 6,937 | 0.006631 | #!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
... | x3_0_1
def sd_psk_4_0x0_1_0(x, Es=1):
'''
01 | 11
-------
00 | 10
'''
x_re = x.real
x_im = x.imag
dist = Es*numpy.sqrt(2)
return [dist*x_re, dist*x_im]
sd_psk_4_4 = sd_psk_4_0x0_1_0
def sd_psk_4_0x1_1_0(x, Es=1):
'''
00 | 10
-------
01 | | 11
'''
x_re = x.real
x_im = x.imag
dist = Es*numpy.sqrt(2)
return [dist*x_re, -dist*x_im]
sd_psk_4_5 = sd_psk_4_0x1_1_0
def sd_psk_4_0x2_1_0(x, Es=1):
'''
11 | 01
-------
10 | 00
'''
x_re = x.real
x_im = x.imag
dist = Es*numpy.sqrt(2)
return [-dist*x_re, dist*x_... |
h2oai/h2o-3 | h2o-py/tests/testdir_algos/infogram/pyunit_PUBDEV_8075_safe_infogram_personal_loan_x_att.py | Python | apache-2.0 | 1,365 | 0.01685 | from __future__ import print_function
import os
import sys
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from h2o.estimators.infogram import H2OInfogram
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
from tests import pyunit_utils
def test_infogram_personal_loan():
"""
Test to ... | ath=pyunit_utils.locate("smalldata/admissibleml_test/Bank_Personal_Loan_Modelling.csv"))
target = "Personal Loan"
fr[target] = fr[target].asfactor()
x = ["Experience","Income","Family","CCAvg","Education","Mortgage",
"Securities Account","CD Account","Online","CreditCard"]
infogram_model = H2OI... | eralizedLinearEstimator()
glm_model1.train(x=infogram_model._extract_x_from_model(), y=target, training_frame=fr)
coef1 = glm_model1.coef()
glm_model2 = H2OGeneralizedLinearEstimator()
glm_model2.train(x=infogram_model, y=target, training_frame=fr)
coef2 = glm_model2.coef()
pyunit_utils.assertC... |
meren/anvio | anvio/data/misc/MODELLER/scripts/pir_to_fasta.py | Python | gpl-3.0 | 298 | 0.030201 | """
Positional arguments:
1. INPUT - file path to FASTA file
2. OUTPUT - file path of output PIR file
"""
import sys
PIR = sys.argv[1]
FASTA = sys.argv[2]
from modeller import *
e = environ()
a = | alignment(e, file | = PIR, alignment_format = 'PIR')
a.write(file = FASTA, alignment_format = 'FASTA')
|
plotly/python-api | packages/python/plotly/plotly/validators/histogram/unselected/marker/__init__.py | Python | mit | 325 | 0 | import sys
if sys.version_info < (3, 7):
from ._opacity import OpacityValidator
from ._color import ColorValidator
else:
from _plotly_utils.importers import relative_import
__all__ | , __getattr__, __dir__ = relative_import(
__name__, [], ["._opacit | y.OpacityValidator", "._color.ColorValidator"]
)
|
centic9/subversion-ppa | subversion/tests/cmdline/svntest/actions.py | Python | apache-2.0 | 86,069 | 0.011468 | #
# actions.py: routines that actually run the svn client.
#
# Subversion is a tool for revision control.
# See http://subversion.tigris.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more con... | it recursively copies
# the `pristine repos' to a new location.
# Note: make sure setup_pristine_greek_repository was called once before
# using this function.
def guarantee_greek_repository(path, minor_version):
"""Guarantee that a local svn repository exists at PATH, containing
nothing but the gre | ek-tree at revision 1."""
if path == main.pristine_greek_repos_dir:
logger.error("attempt to overwrite the pristine repos! Aborting.")
sys.exit(1)
# copy the pristine repository to PATH.
main.safe_rmtree(path)
if main.copy_repos(main.pristine_greek_repos_dir, path, 1, 1, minor_version):
logger.er... |
samuelarm/A-Level_2016-18 | general/cash register.py | Python | gpl-3.0 | 45 | 0.088889 | #cash registe | r
#Samuel Armstrong
| |
docusign/docusign-python-client | docusign_esign/models/notary_journal_list.py | Python | mit | 9,255 | 0.000108 | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.gi... | self.notary_journals = notary_journals
if previous_uri is not None:
self.previous_uri = previous_uri
if result_set_size is not None:
self.result_set_size = result_set_size
if start_position is not | None:
self.start_position = start_position
if total_set_size is not None:
self.total_set_size = total_set_size
@property
def end_position(self):
"""Gets the end_position of this NotaryJournalList. # noqa: E501
The last position in the result set. # noqa: E50... |
googleads/google-ads-python | google/ads/googleads/v10/enums/types/seasonality_event_status.py | Python | apache-2.0 | 1,255 | 0.000797 | # -*- coding: utf-8 -*-
# Copyright 2020 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... | missions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v10.enums",
marshal="google.ads.googleads.v10",
manifest={"SeasonalityEventStatusEnum",},
)
class SeasonalityEventStatusEnum(proto.Message):
r"""Message describing ... | alityAdjustments and
BiddingDataExclusions.
"""
class SeasonalityEventStatus(proto.Enum):
r"""The possible statuses of a Seasonality Event."""
UNSPECIFIED = 0
UNKNOWN = 1
ENABLED = 2
REMOVED = 4
__all__ = tuple(sorted(__protobuf__.manifest))
|
zstackio/zstack-woodpecker | integrationtest/vm/vpc_ha/suite_teardown.py | Python | apache-2.0 | 1,332 | 0.005255 | '''
Integration Test Teardown case
@author: Youyk
'''
import zstacklib.utils.linux as linux
import zstacklib.utils.http as http
import zstackwoodpecker.setup_actions as setup_actions
import zstackwoodpecker.test_util as test_util |
import zstackwoodpecker.clean_util as clean_util
import zstackwoodpecker.test_lib as test_lib
import zstacktestagent.plugins.host as host_plugin
import zstacktestagent.testagent as testagent
def test():
clean_util.cleanup_all_vms_violently()
clean_util.cleanup_none_vm_volumes_violently()
clean_util.umount... | eviceCmd()
cmd.vlan_ethname = 'eth0.10'
hosts = test_lib.lib_get_all_hosts_from_plan()
if type(hosts) != type([]):
hosts = [hosts]
for host in hosts:
http.json_dump_post(testagent.build_http_path(host.managementIp_, host_plugin.DELETE_VLAN_DEVICE_PATH), cmd)
cmd.vlan_ethname = ... |
matthieu-meaux/DLLM | examples/broken_wing_validation/valid_dpR_dpiAoA.py | Python | gpl-2.0 | 2,233 | 0.012987 | # -*-mode: python; py-indent-offset: 4; tab-width: 8; coding: iso-8859-1 -*-
# DLLM (non-linear Differentiated Lifting Line Model, open source software)
#
# Copyright (C) 2013-2015 Airbus Group SAS
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Pub... |
from MDOTools.OC.operating_condition import OperatingCondition
import numpy
OC=OperatingCondition('cond1')
OC.set_Mach(0.8)
OC.set_AoA(3.5)
OC.set_altitude(10000.)
OC.set_T0_deg(15.)
OC.set_P0(101325.)
OC.set_humidity(0.)
OC.compute_atmosphere()
wing_param=Wing_Broken('broken_wing',n_sect | =20)
wing_param.import_BC_from_file('input_parameters.par')
wing_param.build_linear_airfoil(OC, AoA0=0.0, set_as_ref=True)
wing_param.build_airfoils_from_ref()
wing_param.update()
print wing_param
DLLM = DLLMSolver('Simple',wing_param,OC)
DLLM.run_direct()
iAoA0=DLLM.get_iAoA()
print 'iAoA0 shape',iAoA0.shape
print '... |
masayukig/tempest | tempest/api/compute/test_extensions.py | Python | apache-2.0 | 2,098 | 0 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | me'], extensions))
elif ext:
self.ass | ertIn(ext, extension_list)
else:
raise self.skipException('There are not any extensions configured')
@decorators.idempotent_id('05762f39-bdfa-4cdb-9b46-b78f8e78e2fd')
@utils.requires_ext(extension='os-consoles', service='compute')
def test_get_extension(self):
# get the specifie... |
fangohr/oommf-python | joommf/odtreader.py | Python | bsd-2-clause | 1,380 | 0 | """
odtreader.py
Contains class ODTFile for reading OOMMF ODT data into a Pandas dataframe
Author: Ryan Pepper (2016)
University of Southampton
"""
import pandas as pd
import tempfile
import re
class ODTFile(object):
def __init__(self, filename):
f = open(filename)
# Can't use 'w+b' for compatibility... | = tempfile.NamedTemporaryFile(mode='w')
metadata = []
for line in f:
if line[0] == '#':
metadata.append(line)
else:
new_line = re.sub(r'\s+', ',', line.lstrip().rstrip()) + '\n'
temporar | y_file.write(new_line)
temporary_file.flush()
self.dataframe = pd.read_csv(temporary_file.name, header=None)
header = []
for column in metadata[3].split('Oxs_')[1:]:
column = column.replace('{', '')
column = column.replace('}', '')
column = column.rstr... |
ianfhunter/LoLss | secondscreen/synch/migrations/0002_auto__chg_field_screen_page_id.py | Python | gpl-2.0 | 3,281 | 0.007315 | # -*- 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):
# Changing field 'Screen.page_id'
db.alter_column(u'synch_screen', 'page_id', self.gf('django.db.models.fie... | ,
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'position_x': ('django.db.models.fields.IntegerField', [], {'max_length': '3', 'null': 'True'}),
'position_y': ('django.db.models.fields.IntegerField', [], {'max_length': '3', 'null': 'True'}),
| 'screen': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u"orm['synch.Screen']", 'null': 'True', 'blank': 'True'}),
'team': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'timer': ('django.db.models.fields.IntegerField', [], {'max_length': '... |
99cloud/keystone_register | horizon/test/tests/tables.py | Python | apache-2.0 | 31,356 | 0.000128 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Nebula, 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
#
# ... | up', 'optional_1', 'excluded_1'),
)
TEST_DATA_4 = (
FakeObject('1', 'object_1', 2, | 'up'),
FakeObject('2', 'object_2', 4, 'up'),
)
TEST_DATA_5 = (
FakeObject('1', 'object_1', 'A Value That is longer than 35 characters!',
'down', 'optional_1'),
)
class MyLinkAction(tables.LinkAction):
name = "login"
verbose_name = "Log In"
url = "login"
attrs = {
"class... |
zqfan/leetcode | algorithms/216. Combination Sum III/solution2.py | Python | gpl-3.0 | 557 | 0 | class Solution(object):
def combinationSum3(self, k, n):
""" |
:type k: int
:type n: int
:rtype: List[List[int]]
"""
def dfs(s, n):
if len(path) >= k:
if n == 0:
result.append(path[:])
return
for i in xrange(s, 10):
if n < i:
retu... | dfs(1, n)
return result
|
daite/JAVImageDownloader | jav_image_download.py | Python | mit | 3,951 | 0.026069 | #!/usr/bin/env python2
# -*- coding: utf-8 -*
#The MIT License (MIT)
# Copyright (c) 2015 daite
# 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 limitat... | tion(res_text)
if not img_urls:
print('No images!!!!')
continue
sub_dir_name = url.split('/')[-1].strip('.html')
self.save_stuff(sub_dir_name, img_urls, desc_contents)
if __name__ == '__main__':
gana_urlgen = lambda x : 'http://blog.livedoor.jp/kirekawa39-siro/archives/200GANA-%d.html' %x
siro_urlg... | umber')
parser.add_argument("end", type=int, help='end number')
parser.add_argument('-g', '--gana',
help='download image from gana200',
action="store_true")
parser.add_argument('-s', '--siro',
help='download image from siro',
action="store_true")
args = parser.parse_args()
if args.g... |
kennethlove/django_bookmarks | dj_bookmarks/bookmarks/migrations/0006_bookmark_collections.py | Python | bsd-3-clause | 476 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-15 17:18
from __futu | re__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookmarks', '0005_auto_20170915_1015'),
]
| operations = [
migrations.AddField(
model_name='bookmark',
name='collections',
field=models.ManyToManyField(to='bookmarks.Collection'),
),
]
|
loomchild/icoin | test/integration_test/test_mail.py | Python | agpl-3.0 | 727 | 0.009629 | from | time import sleep
from icoin import app
from icoin.core.mail import mail, send
class TestMail:
def test_send_sync(self):
with app.app_context(), mail.record_messages() as outbox:
send("[email protected]", "subjectnow", | "test", async=False)
assert len(outbox) == 1
assert outbox[0].subject == "subjectnow"
def test_send_async(self):
with app.app_context(), mail.record_messages() as outbox:
send("[email protected]", "subject", "test")
# message is not sent im... |
jumpserver/jumpserver | apps/assets/tasks/account_connectivity.py | Python | gpl-3.0 | 2,991 | 0.000335 | # ~*~ coding: utf-8 ~*~
from celery import shared_task
from django.utils.translation import ugettext as _, gettext_noop
from common.utils import get_logger
from orgs.utils import org_aware_func
from ..models import Connectivity
from . import const
from .utils import check_asset_can_run_ansible
logger = get_logger(_... | raw, summary = test_user_connectivity(
task_name=task_name, asset=account.asset,
username=account.username, password=account.password,
private_key=account.private_key_file
)
except Exception as e:
logger.warn("Failed run adhoc {}, {}".format(task_name, e))
... | )
def test_accounts_connectivity_manual(accounts):
"""
:param accounts: <AuthBook>对象
"""
for account in accounts:
task_name = gettext_noop("Test account connectivity: ") + str(account)
test_account_connectivity_util(account, task_name)
print(".\n")
|
Elico-Corp/openerp-7.0 | account_alternate_invoice/__openerp__.py | Python | agpl-3.0 | 580 | 0.003454 | # -*- coding: utf-8 -*-
# © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
{
'name': 'Account Alternate Invoice',
'version': '7.0.1.0.0',
'author': 'Elico Corp',
'website': 'https://www.elico-corp.com',
'description': """
Acco... | ate Invoice
""",
'depends': ['base', 'account', ],
'sequence': 10,
'data': [
'account_invoice_view.xml',
'report.xml',
],
'installable': True,
'application': | False,
'auto_install': False,
}
|
terrycojones/dark-matter | test/test_local_align.py | Python | mit | 11,532 | 0 | import six
from unittest import TestCase
from dark.reads import Read
from dark.local_align import LocalAlignment
class TestLocalAlign(TestCase):
"""
Test the LocalAlignment class.
With match +1, mismatch -1, gap open -1, gap extend -1 and
gap extend decay 0.0.
"""
def testPositiveMismatch... | result = align.createAlignment | (resultFormat=str)
alignment = ('\nCigar string of aligned region: 6=\n'
'seq1 Match start: 2 Match end: 7\n'
'seq2 Match start: 1 Match end: 6\n'
'seq1 2 GAATCG 7\n'
' ||||||\n'
'seq2 1 GAATCG 6')
... |
hitsl/bouser_simargl | bouser_simargl/web.py | Python | isc | 577 | 0 | # -*- coding: utf-8 -*-
from twisted.web.resource import Resource
from bouser.helpers.plugin_helpers import Dependency
__author__ = 'viruzzz-kun'
class SimarglResource(Resource):
web = Dep | endency('bouser.web')
es = Dependency('bouser.ezekiel.eventsource', optional=True)
rpc = Dependency('bouser.ezekiel.rest', optional=True)
@web.on
def web_on(self, web):
web.root_re | source.putChild('ezekiel', self)
@es.on
def es_on(self, es):
self.putChild('es', es)
@rpc.on
def rpc_on(self, rpc):
self.putChild('rpc', rpc)
|
TriOptima/tri.form | tests/settings.py | Python | bsd-3-clause | 710 | 0 | import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = [
os.path.join(BASE_DIR, 'tests'),
os.path.join(BASE_DIR, 'tri_form/templates'),
]
TEMPLATE_DEBUG = True
# Django | >=1.9
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': TEMPLATE_DIRS,
'APP_DIRS': True,
'OPTIONS': {
'debug': TEMPLATE_DEBUG,
}
}
]
SECRET_KEY = "foobar"
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.c... | 'db.sqlite3'),
}
}
|
jerome-jacob/selenium | py/test/selenium/webdriver/common/page_loading_tests.py | Python | apache-2.0 | 5,014 | 0.007579 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | testShouldBeAbleToNavigateBackInTheBrowserHistory(self):
self._loadPage("formPage")
self.driver.find_element(by=By.ID, value="imageButton").submit()
self.assertEqual(self.driver.title, "We Arrive Here")
self.driver.back()
self.assertEqual(sel | f.driver.title, "We Leave From Here")
def testShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes(self):
self._loadPage("xhtmlTest")
self.driver.find_element(by=By.NAME,value="sameWindow").click()
self.assertEqual(self.driver.title, "This page has iframes")
self.driv... |
testing-cabal/mock | mock/tests/testmock.py | Python | bsd-2-clause | 72,280 | 0.002048 | import copy
import re
import sys
import tempfile
import unittest
from mock.tests.support import ALWAYS_EQ
from mock.tests.support import is_instance
from mock import (
call, DEFAULT, patch, sentinel,
MagicMock, Mock, NonCallableMock,
NonCallableMagicMock, AsyncMock,
create_autospec, mock
)
from mock.mo... | next
class Something(object):
def meth(self, a, b, c, d=None): pass
@classmethod
def cmeth(cls, a, b, c, d=None): pass
@staticmethod
def smeth(a, b, c, d=None): pass
def something(a): pass
class MockTest(unittest.TestCase):
def test_all(self):
# if __all__ is badly define | d then import * will raise an error
# We have to exec it because you can't import * inside a method
# in Python 3
exec("from mock.mock import *")
def test_constructor(self):
mock = Mock()
self.assertFalse(mock.called, "called not initialised correctly")
self.assert... |
pixelated-project/pixelated-user-agent | service/test/unit/adapter/test_mailbox_indexer_listener.py | Python | agpl-3.0 | 2,690 | 0.003717 | #
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated 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.
#
# Pixelated is distrib... | ndexerListene | r.listen(self.account, 'INBOX', self.mail_store, mock())
self.assertIn(MailboxIndexerListener('INBOX', self.mail_store, mock()), mailbox.listeners)
def test_reindex_missing_idents(self):
mail = mock()
search_engine = mock()
when(search_engine).search('tag:inbox', all_mails=True).th... |
kartta-labs/noter-backend | noter_backend/main/migrations/0003_create_public_group.py | Python | apache-2.0 | 664 | 0.003012 | from django.db import models, migr | ations
import uuid
from django.contrib.auth.hashers import make_password
PUBLIC_ID = 1
def apply_migration(apps, schema_editor):
Group = apps.get_model('auth', 'Group')
public_group = Group()
public_group.name = "public"
public_group.id = PUBLIC_ID
public_group.save()
def revert_migration(apps, s... | ('main', '0002_auto_20200821_0710'),
]
operations = [
migrations.RunPython(apply_migration, revert_migration)
] |
sailfish-sdk/sailfish-qtcreator | scripts/common.py | Python | gpl-3.0 | 7,269 | 0.003027 | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | ot is_debug_file(os.path.join(path, fn))]
def codesign(app_path):
sig | ning_identity = os.environ.get('SIGNING_IDENTITY')
if is_mac_platform() and signing_identity:
codesign_call = ['codesign', '--force', '--deep', '-s', signing_identity, '-v']
signing_flags = os.environ.get('SIGNING_FLAGS')
if signing_flags:
codesign_call.extend(signing_flags.split... |
ebigelow/LOTlib | LOTlib/Testing/old/Examples/SymbolicRegression/old/test_simple_functionTest.py | Python | gpl-3.0 | 522 | 0.007663 | """
cl | ass to test test_simple_function.py
follows the standards in https://docs.python.org/2/library/unittest.html
"""
import unittest
from LOTlib.Examples.SymbolicRegression.old.test_simple_function import *
class test_simple_functionTest(unittest.TestCase):
# initialization that happens before each test is carried o... | # function that is executed after each test is carried out
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
shash/IconDB | django_extensions/management/commands/print_user_for_session.py | Python | agpl-3.0 | 1,826 | 0 | from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from django_extensions.future_1_5 import get_user_model
from django.contrib.sessions.models import Session
import re
SESSION_RE = re.compile("^[0-9a-f]{20,40}$... | decoded()
print('Session to Expire: %s' % session.expire_date)
print('Raw Data: %s' % data)
uid = data.get('_auth_user_id', None)
if uid is None:
print('No user associated with session')
return
print("User id: %s" % uid)
User = get_user_model()
... | th that id.")
return
for key in ['username', 'email', 'first_name', 'last_name']:
print("%s: %s" % (key, getattr(user, key)))
|
SurielRuano/Orientador-Legal | colaboradores/forms.py | Python | mit | 287 | 0.031359 | from django import f | orms
from django.contrib.auth.models import User
from .models import Perfil,SolicitudColaboracion
class SolicitudColaboracionForm(forms.ModelForm):
class Meta:
model = SolicitudColaboracio | n
fields = ('name','licenciatura_leyes','telefono','fecha_nacimiento')
|
UCRoboticsLab/BaxterTictactoe | src/baxter_face_animation/src/baxter_face_animation/hear_words.py | Python | apache-2.0 | 926 | 0.009719 | #!/usr/bin/env python
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String
import rospkg
cla | ss Hear_orders:
def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publish_emotion)
self.emotion_publisher = rospy.Publisher("/emotion", String, queue_size=10)
# self.timer = rospy.Timer(rospy.Duration(self.velocity), self.timer_cb)
def pu... | rospy.Rate(30)
rospack = rospkg.RosPack()
# path = rospack.get_path('baxter_face_animation') + "/data/"
Hear_orders()
while not rospy.is_shutdown():
rate.sleep()
if __name__ == "__main__":
main()
|
collectiveacuity/pocketLab | pocketlab/methods/service.py | Python | mit | 8,378 | 0.005132 | __author__ = 'rcj1492'
__created__ = '2016.10'
__license__ = 'MIT'
def retrieve_service_name(service_root):
service_name = ''
# construct registry client
from os import path
from pocketlab import __module__
from labpack.storage.appdata import appdataClient
registry_client = appdataCli... | add local path to service list
else:
path_list.append({'name': '', 'path': './'})
return path_list, msg_insert
def retrieve_service_config(service_root, service_name, command_title):
from os import path
from pocketlab.methods.validation import validate_compose
from pock... | ader
from jsonmodel.validators import jsonModel
compose_schema = jsonLoader(__module__, 'models/compose-config.json')
service_schema = jsonLoader(__module__, 'models/service-config.json')
compose_model = jsonModel(compose_schema)
service_model = jsonModel(service_schema)
compose_path = pat... |
willu47/SALib | src/SALib/test_functions/Sobol_G.py | Python | mit | 1,685 | 0.003561 | from __future__ import division
import numpy as np
# Non-monotonic Sobol G Function (8 parameters)
# First-order indices:
# x1: 0.7165
# x2: 0.1791
# x3: 0.0237
# x4: 0.0072
# x5-x8: 0.0001
def evaluate(values, a=None):
if type(values) != np.ndarray:
raise TypeError("The argument `values` m... | urn np.subtract(1, np.divide(np.subtract | (sum_pv, pv.T), tv))
|
Ginfung/FSSE | Algorithms/WORTHY.py | Python | mit | 7,356 | 0.000952 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2019, Jianfeng Chen <[email protected]>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# 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 t... | arestCentroid
from sklearn.model_selection | import train_test_split
from mpl_toolkits import mplot3d
from matplotlib.pyplot import figure
from matplotlib.ticker import PercentFormatter
import matplotlib.ticker as mtick
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time
import sys
import os
import random
import random
import pdb
... |
neildhir/DCBO | tests/test_root.py | Python | mit | 5,136 | 0.003118 | import unittest
from numpy import arange, linspace
from numpy.random import seed
from src.bases.root import Root
from src.examples.example_setups import setup_stat_scm
from src.utils.sem_utils.toy_sems import StationaryDependentSEM as StatSEM
from src.utils.sequential_intervention_functions import get_interventional_g... | (self):
nr_samples = 10
interventional_variable_limits = {"X": [-15, 3], "Z": [-1, 10]}
exploration_sets = list(powerset(self.root.manipulative_variables))
grids = get_interventional_grids(exploration_sets, interventional_variable_limits, nr_samples)
compare_vector = linspace(
... | [1], num=nr_samples
).reshape(-1, 1)
self.assertEqual(compare_vector.shape, grids[exploration_sets[0]].shape)
self.assertTrue((compare_vector == grids[exploration_sets[0]]).all())
def test_target_variables(self):
self.assertEqual(self.root.all_target_variables, ["Y_0", "Y_1", "Y_2"]... |
cloew/TogglDriver | toggl_driver/args/project_arg.py | Python | mit | 547 | 0.007313 | from ..config import GlobalConfig, LocalConfig
from kao_command.args import FlagArg
class ProjectArg(FlagArg):
""" Represents an CLI Arg | ument that specifies a Project """
def __init__(self, *, help):
""" Initialize the Arg """
FlagArg.__init__(self, '-p', '--project', action="store", help=help)
def getValue(self, args):
""" Return the value from the args """
projectName = FlagArg.getValue(self, ... | withName(projectName).first |
unioslo/cerebrum | Cerebrum/extlib/Plex/DFA.py | Python | gpl-2.0 | 5,539 | 0.015165 | # -*- coding: utf-8 -*-
#=======================================================================
#
# Python Lexical Analyser
#
# Converting NFA to DFA
#
#=======================================================================
import Machines
from Machines import LOWEST_PRIORITY
from Transitions import TransitionMa... | nsitions out of any
# of the correspon | ding old states. The new state reached on a given
# character is the one corresponding to the set of states reachable
# on that character from any of the old states. As new combinations of
# old states are created, new states are added as needed until closure
# is reached.
new_machine = Machines.FastMachine()... |
MichelRottleuthner/RIOT | tests/trace/tests/01-run.py | Python | lgpl-2.1 | 676 | 0 | #!/usr/bin/env python3
# Copyright (C) 2016 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import os
import sys
def testfunc(child):
child.expect(r"TRACE_SIZE: (\d+... | ner'))
import testrunner
sys.exit(testrunner.run(testfun | c, timeout=1, echo=True, traceback=True))
|
ghtdak/pyaxo | examples/create_states.py | Python | gpl-3.0 | 539 | 0 | #!/usr/bin/env python
import os
from pyaxo import Axolotl
# start with a fresh database
try:
os.remove('./alice.db')
os.remove('./bob.db')
except OSError:
pass
# unencrypted databases
a = Axolotl('alice', dbname='alice.db', dbpassphrase=None)
b = Axolotl('bob', dbname='bob.db', dbpassphrase=None)
a.in... | ify=False)
a.saveState()
b.saveS | tate()
|
SAlkhairy/trabd | voting/migrations/0005_add_is_city_results_due_for_SACYear.py | Python | agpl-3.0 | 1,341 | 0.002237 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-22 07:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('voting' | , '0004_winner_annoucement'),
]
operations = [
migrations.AddField(
model_name='sacyear',
name='alahsa_results_datetime',
field=models.DateTimeField(blank=True, null=True, verbose_name='\u062a\u0627\u0631\u064a\u062e \u0625\u0639\u0644\u0627\u0646 \u0627\u0644\u0646\... |
GuessWhoSamFoo/pandas | pandas/tests/scalar/interval/test_interval.py | Python | bsd-3-clause | 7,179 | 0 | from __future__ import division
import numpy as np
import pytest
from pandas import Interval, Timedelta, Timestamp
import pandas.core.common as com
@pytest.fixture
def interval():
return Interval(0, 1)
class TestInterval(object):
def test_properties(self, interval):
assert interval.closed == 'rig... | match=msg):
interval * interval
msg = r"can\'t multiply sequence by non-int"
with pytest.raises(TypeError, matc | h=msg):
interval * 'foo'
def test_math_div(self, closed):
interval = Interval(0, 1, closed=closed)
expected = Interval(0, 0.5, closed=closed)
result = interval / 2.0
assert result == expected
result = interval
result /= 2.0
assert result == expe... |
hep-cce/hpc-edge-service | argo/test_jobs/test_submit_alpgen.py | Python | bsd-3-clause | 2,987 | 0.035152 | #!/usr/bin/env python
import sys,logging,optparse
from AlpgenArgoJob import AlpgenArgoJob
sys.path.append('/users/hpcusers/balsam/argo_deploy/argo_core')
from MessageInterface import MessageInterface
def main():
parser = optparse.OptionParser(description='submit alpgen job to ARGO')
parser.add_option('-e','--ev... | ser.error('Must define the number of weighted events to produce')
if options.num_warmup is N | one:
parser.error('Must define the number of weighted events to produce in the warmup step.')
if options.alpgen_input_file is None:
parser.error('Must define the AlpGen input file')
if options.walltime is None:
parser.error('Must specify a wall time')
user = os.environ.get('USER','nob... |
oVirt/vdsm | tests/throttledlog_test.py | Python | gpl-2.0 | 3,280 | 0 | #
# Copyright 2016 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... |
self.assertEqual(throttledlog._logger.messages,
['Cycle: 0', 'Cycle: 3'])
@MonkeyPatch(throttledlog, "_logger", FakeLogger(logging.INFO))
def test_no_logging(self):
throttledlog.throttle('test', 3)
for i in range(5):
throttledlog.debug('test', "Cycl... | MonkeyPatch(throttledlog, "_logger", FakeLogger(logging.DEBUG))
def test_default(self):
throttledlog.throttle('test', 3)
for i in range(5):
throttledlog.debug('other', "Cycle: %s", i)
self.assertEqual(throttledlog._logger.messages,
['Cycle: %s' % (i,) for... |
GroupBank/global-server | rest_app/decorators.py | Python | agpl-3.0 | 1,619 | 0.001853 | import logging
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from functools import wraps
import groupbank_crypto.ec_secp256k1 as crypto
logger = logging.getLogger(__name__)
# decorator for verifying the payload is signed by the author of the request
def verify_author(view):
@wraps(view... | author, signature, payload = request.POST['author'], request.POST['signature'], request.POST['payload']
except KeyError:
logger.info('Request with missing author, signature or payload')
return HttpResponseBadRequest()
# get user pubkey
# what if the author CAN'T already ... | not verify if the signer is authorized for the operation.
# It only verifies if the signature matches the given pub key
try:
crypto.verify(author, signature, payload)
return view(request)
except (crypto.InvalidSignature, crypto.InvalidKey):
logger.info... |
braysia/CellTK | celltk/utils/morphsnakes.py | Python | mit | 11,905 | 0.011937 | # -*- coding: utf-8 -*-
"""
morphsnakes
===========
This is a Python implementation of the algorithms introduced in the paper
Márquez-Neila, P., Baumela, L., Álvarez, L., "A morphological approach
to curvature-based evolution of curves and surfaces". IEEE Transactions
on Pattern Analysis and Machine Intelligence... |
data = self.data
# Determine c0 and c1.
inside = u>0
outside = u<=0
c0 = data[outside].sum() / float(outside.sum())
c1 = data[inside].sum() / float(inside.sum())
# Image attachment.
dres = np.array(np.gradient(u))
abs_dre... | res = np.copy(u)
res[aux < 0] = 1
res[aux > 0] = 0
# Smoothing.
for i in range(self.smoothing):
res = curvop(res)
self._u = res
def run(self, iterations):
"""Run several iterations of the morphological Chan-Vese method."""
... |
XTAv2/Enigma2 | lib/python/Screens/SkinSelector.py | Python | gpl-2.0 | 5,279 | 0.028793 | # -*- coding: utf-8 -*-
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuL... |
if self.SKINXML and os.path.exists(os.path.join(self.root, self.SKINXML)):
self.skinlist.append(self.DEFAULTSKIN)
if self.PICONSKINXML and os.path.exists(os.path.join(self.root, self.PICONSKINXML)):
self.skinlist.append(self.PICONDEFAULTSKIN)
for root, dirs, files in os.walk(self.root, followlinks=True):
... | sts(os.path.join(dir,self.SKINXML)):
self.skinlist.append(subdir)
dirs = []
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Save"))
self["introduction"] = StaticText(_("Press OK to activate the selected skin."))
self["SkinList"] = MenuList(self.skinlist)
self["Preview"] = P... |
eHealthAfrica/rapidsms_textit | rapidsms_textit/views.py | Python | bsd-3-clause | 3,591 | 0.004456 | # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from __future__ import print_function, unicode_literals
import logging
from django.http import HttpResponse, HttpResponseServerError, HttpResponseBadRequest
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.ht... | backend = settings.INSTALLED_BACKENDS[backend_name]
except KeyError:
logger.error('Name "{}" not found in settings INSTALLED_BACKENDS.'.format(backend_name))
return HttpResponseBa | dRequest('Name "{}" not found in settings INSTALLED_BACKENDS.'.format(backend_name))
try:
if request.META['QUERY_STRING'] != backend['config']['query_key']:
r = 'query_key "{}" does not match configured value from django settings "{}"'.format(
request.META['QUERY_STRING'], ba... |
sr-gi/paysense | utils/tor/tools.py | Python | bsd-3-clause | 2,930 | 0.001706 | # Copyright (c) <2015> <Sergi Delgado Segura>
# Distributed under the BSD software license, see the accompanying file LICENSE
import pycurl
import stem.process
from stem.control import Controller
from stem.util import term
from StringIO import StringIO
__author__ = 'sdelgado'
SOCKS_PORT = 9050
CONTROL_PORT = 9051
... | """ Performs a http query using tor.
:param url: server address.
:type url: str
:param method: request method (GET, POST, ...).
:type method: str
:param data: data to be sent to the server.
:param data: JSON dumped object
:param head | ers: headers of the request.
:type headers: str array
:param socks_port: local socket port where tor is listening to requests (configurable in tor.rc).
:type socks_port: int
:return: response code and some server response data.
:rtype: str, str
"""
output = StringIO()
if socks_port is N... |
SpoonITCurrency/SpoonITCoin | spoonitcoin/share/qt/clean_mac_info_plist.py | Python | mit | 897 | 0.016722 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Litecoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from | string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Litecoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for l | ine in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open... |
Grumbel/dirtool | experiments/qnotify/qnotify.py | Python | gpl-3.0 | 1,673 | 0 | #!/usr/bin/env python3
# dirtool.py - diff tool for directories
# Copyright (C) 2018 Ingo Ruhnke <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t | he GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A ... | se for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import signal
import sys
from PyQt5.QtCore import QCoreApplication, QFileSystemWatcher
def directory_changed(path):
print("directory_changed: {}".for... |
ifduyue/sentry | tests/sentry/middleware/test_useractive.py | Python | bsd-3-clause | 912 | 0 | from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from django.test import RequestFactory
from exam import fixture
from sentry.middleware.user import UserActiveMiddleware
from sentry.testutils import TestCase
class UserActiveMiddlewareTest(TestCase) | :
middleware = fixture(UserActiveMiddleware)
factory = fixture(RequestFactory)
def test_simple(self):
self.view = lambda x: None
user = self.user
req = self.factory.get('/')
req.user = user
resp = self.middleware.process_view(req, self.view, [], {})
assert ... | user.last_active = None
resp = self.middleware.process_view(req, self.view, [], {})
assert resp is None
assert timezone.now() - user.last_active < timedelta(minutes=1)
|
Acehaidrey/incubator-airflow | airflow/providers/google/suite/transfers/sql_to_sheets.py | Python | apache-2.0 | 5,101 | 0.00196 | # 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 u... | et_range
self.delegate_to = delegate_to
self.impersonation_chain = impersonation_chain
def _data_prep(self, data):
for row in data:
item_list = []
for item in row:
if isinstance(item, (datetime.date, datetime.datetime)):
item = ite... | pass
elif isinstance(item, numbers.Number):
item = float(item)
item_list.append(item)
yield item_list
def _get_data(self):
hook = self.get_db_hook()
with closing(hook.get_conn()) as conn, closing(conn.cursor()) as cur:
... |
hirolovesbeer/tfs | tfs.py | Python | apache-2.0 | 1,111 | 0.0027 | #!/usr/bin/env python
import sys
import glob
import hdfs3
from hdfs3 import HDFileSystem
hdfs_nn = '192.168.33.10'
hdfs = HDFileSystem(host=hdfs_nn, port=8020)
class TransparentFileSystem:
def __init__(self):
self.hdfs_flag = False
return
def set_hdfs_flag(self, flag=True):
self.hd... | self.hdfs_flag = True
else:
print target + ' This dir is not HDFS. Local FS.'
# if os.path.exists('')
def glob(self, target):
if self.hdfs_flag is True:
return hdfs.glob(target)
else:
return glob.glob(target)
if __name__ == "__main__":
... | mp')
print tfs_hdfs.hdfs_flag
print tfs_hdfs.glob('/tmp')
tfs_local = TransparentFileSystem()
tfs_local.exists('dir to local')
tfs_local.set_hdfs_flag(False)
print tfs_local.hdfs_flag
print tfs_local.glob('dir to local')
sys.exit(0)
|
syrusakbary/Flask-SuperAdmin | flask_superadmin/tests/test_mongoengine.py | Python | bsd-3-clause | 9,707 | 0.001751 | from nose.tools import eq_, ok_, raises
import wtforms
from flask import Flask
from mongoengine import *
from flask_superadmin import Admin
from flask_superadmin.model.backends.mongoengine.view import ModelAdmin
class CustomModelView(ModelAdmin):
def __init__(self, model, name=None, category=None, endpoint=Non... | fields = ('name', 'age', 'pet')
readonly_fields = ('pet',)
Dog.drop_collection()
Person.drop_collect | ion()
dog = Dog.objects.create(name='Sparky')
person = Person.objects.create(name='Stan', age=10, pet=dog)
admin.register(Dog, DogAdmin, name='Dogs')
admin.register(Person, PersonAdmin, name='People')
client = app.test_client()
# te |
zenoss/pywbem | attic/irecv/pycimlistener.py | Python | lgpl-2.1 | 6,068 | 0.012525 | #!/usr/bin/python
#
# Simple indication receiver using Twisted Python. HTTP post requests
# are listened for on port 5988 and port 5899 using SSL.
#
# Requires Twisted Python and
#
import sys
import optparse
import pywbem
from twisted.internet import reactor
from twisted.web import server, resource
global conn
conn=... | proto = 'https'
url = '%s://%s' % (proto, options.host)
self.conn = pywbem.WBEMConnection(
url,
(options.user, options.password),
default_namespace = options.name | space)
'''
global conn
conn = self.conn
class CIMOM(resource.Resource):
isLeaf = 1
def render_POST(self, request):
for line in request.content.readlines():
print(line)
return ''
from OpenSSL import SSL
class ServerContextFactory:
def getContext(se... |
singingwolfboy/flask-dance | tests/contrib/test_github.py | Python | mit | 2,744 | 0.001093 | import pytest
import responses
from urlobject import URLObject
from flask import Flask
from flask_dance.contrib.github import make_github_blueprint, github
from flask_ | dance.consumer import OAuth2ConsumerBlueprint
from flask_dance.consumer.storage import MemoryStorage
@pytest.fixture
def make_app():
"A callable to create a Flask app with the GitHub provider"
def _make_app(*args, **kwargs):
app = Flask(__name__)
app.secret_key = "whatever"
blueprint ... | ake_github_blueprint(*args, **kwargs)
app.register_blueprint(blueprint)
return app
return _make_app
def test_blueprint_factory():
github_bp = make_github_blueprint(
client_id="foo", client_secret="bar", scope="user:email", redirect_to="index"
)
assert isinstance(github_bp, OAu... |
south-coast-science/scs_dfe_eng | src/scs_dfe/particulate/sps_30/sps_30.py | Python | mit | 8,991 | 0.008008 | """
Created on 1 May 2019
@author: Bruno Beloff ([email protected])
https://www.sensirion.com/en/environmental-sensors/particulate-matter-sensors-pm25/
https://bytes.com/topic/python/answers/171354-struct-ieee-754-internal-representation
Firmware report:
89667EE8A8B34BC0
"""
import time
from scs_c... |
counts = SPSDatumCounts(pm0p5_count, pm1_count, pm2p5_count, pm4_count, pm10_count)
return SPSDatum(self.SOURCE, rec, pm1, pm2p5, pm4, pm10, counts, tps)
# ----------------------------------------------------------------------------------------------------------------
def version(self):
... | ''.join(chr(byte) for byte in r)
return version
def serial_no(self):
r = self.__read(self.__CMD_READ_SERIAL_NUMBER, 0, 48)
serial_no = ''.join(chr(byte) for byte in r)
return serial_no
def firmware(self):
return self.serial_no()
# -----------------------------... |
pdebuyl-lab/RMPCDMD | experiments/03-single-janus/plot_planar.py | Python | bsd-3-clause | 1,110 | 0.00991 | #!/usr/bin/env python
"""
Display the planar concentration and velocity fields of a RMPCDMD simulation.
"""
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', help="H5MD file")
parser.add_argument('--species', type=int, default=0)
args = parser.parse_args()
import h5py
i... | 'dy'][()]
thickness = c.attrs['thickness'][()]
c = c[:]
v = v[:]
N_x, N_y = c.shape[:2]
# x and y must overshoot c.shape by one for pcolormesh
x = x_min + np.arange(N_x+1)*dx
y = y_min + np.arange(N_y+1)*dy
c /= dx*dy*thickness
plt.subplot(121, aspect=1)
plt.pcolormesh(x, y, c[:,:,a... | ()
plt.subplot(122, aspect=1)
x, y = np.meshgrid(x[:-1], y[:-1])
plt.quiver(x, y, v[:,:,args.species,0].T, v[:,:,args.species,1].T)
plt.show()
|
veltzer/demos-python | src/examples/short/pandas/tuples_as_indices.py | Python | gpl-3.0 | 308 | 0.003247 | #!/usr/bin/env python
"""
A basic demo of pand | as
"""
from pandas import DataFrame
df = DataFrame(["a | ", "b", "c"], index=[("0", "1"), ("1", "2"), ("2", "3")])
print(df.get_values())
try:
print(df.ix[("0", "1")])
except:
print("yes, accessing .ix with tuple does not work")
print(df.xs(("0", "1")))
|
sileht/pastamaker | pastamaker/gh_pr_fullifier.py | Python | apache-2.0 | 9,306 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright © 2017 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 applica... | gical order.
# The first status in the list will be the latest one.
commit = pull.base.repo.get_commit(pull.head.sha)
raw_statuses = [s.raw_data
for s in reversed(list(commit.get_statuses()))]
statuses = {}
for s in raw_s | tatuses:
statuses[s["context"]] = {"state": s["state"], "url": s["target_url"]}
return statuses
def compute_approved(pull, **extra):
approved = len(pull.pastamaker["approvals"][0])
requested_changes = len(pull.pastamaker['approvals'][1])
required = pull.pastamaker['approvals'][2]
if reques... |
RyanJenkins/ISS | ISS/migrations/0012_privatemessage.py | Python | gpl-3.0 | 1,032 | 0.004845 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
('ISS', '0011_poster_timezone'),
]
operations = [
mi... | s.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('chain', models.UUIDField(default=uuid.uuid4, editable=False)),
('created' | , models.DateTimeField(default=django.utils.timezone.now)),
('subject', models.CharField(max_length=256)),
('content', models.TextField()),
('receiver', models.ForeignKey(related_name='pms_received', to=settings.AUTH_USER_MODEL)),
('sender', models.Foreign... |
atlefren/beerdatabase | alembic/versions/3b3de4db8006_fix_stock_again_17_03_16.py | Python | mit | 642 | 0.004673 | """fix stock again (17.03.16)
Revision ID: 3b3de4db8006
Revises: 1b434f6a7b5
Create Date: 2016-03-17 22:02:55.090285
"""
# revision identifiers, used by Alembic.
revision = '3b3de4db8006'
down_revision = '1b434f | 6a7b5'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute('DROP VIEW pol_stock_latest;')
op.execute('''
CREATE VIEW po | l_stock_latest as
SELECT DISTINCT ON (pol_beer_id, shop_id) shop_id, pol_beer_id, stock, updated
FROM pol_stock
ORDER BY pol_beer_id, shop_id, updated DESC;
''')
def downgrade():
pass
|
ColinKeigher/McAfeeWebGateway | mwg/parse.py | Python | gpl-2.0 | 236 | 0.012712 | import xmltodict
|
def parseData(data):
try:
return xmltodict.parse(data)
except:
if len(data.split()) is 0:
retu | rn None
else:
raise Exception('Invalid XML data', data)
|
stardog-union/stardog-graviton | release/release.py | Python | apache-2.0 | 8,041 | 0.000871 | import os
import shutil
import subprocess
import sys
import tempfile
import threading
_g_failed = []
def this_location():
return os.path.abspath(os.path.dirname(__file__))
def checkenv(sd_license, release, ssh_key_path):
required_vars = ['AWS_ACCESS_KEY_ID',
'AWS_SECRET_ACCESS_KEY',... | refix="graviton",
dir=os.path.abspath(os.path.dirname(__file__)))
try:
files_to_join_and_copy = ['rows.rdf', 'smoke_test_1.py']
for f in files_to_join_and_copy:
shutil.copy(os.path.join(src_dir, f),
os.path.join(work_dir, f))
... | ey.bin"))
shutil.copy(release,
os.path.join(work_dir, os.path.basename(release)))
shutil.copy(grav_exe,
os.path.join(work_dir, "stardog-graviton"))
shutil.copy(ssh_key_path,
os.path.join(work_dir, "ssh_key"))
return work_dir
... |
MrOnlineCoder/shockd | scripts/get.py | Python | mit | 523 | 0.00956 | # Sends GET to local server
# Author: schdub
#!/usr/bin/python
import socket
import sys
def GET(host, path, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.30)
s.connect((host, port))
s.send("GET %s HTTP/1.0\r\n" % (path))
total_data = []
while True:
data = s... | a)>0):
total_data.append(data)
else:
break
print ''.join( | total_data)
s.shutdown(1)
s.close()
GET(sys.argv[1], sys.argv[2], 3000) |
arantebillywilson/python-snippets | py3/py344-tutor/ch06-modules/importing_modules.py | Python | mit | 444 | 0.004505 | #! /usr/bin/env python3
#
# importing_modules.py
#
# Author: Billy Wilson Arante
# Created: 2/24/2016 PHT
#
import fibo
def test():
"""Test cases."""
print('Exam | ple 1:')
fibo.fib(1000)
print('Example 2:')
print(fibo.fib1(1000))
print('Example 3:')
print(fibo.__name__ | )
# Assigning function a local name
fib = fibo.fib
print('Example 4:')
fib(1000)
if __name__ == '__main__':
test()
|
kerneltask/micropython | tools/metrics.py | Python | mit | 7,086 | 0.001129 | #!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2020 Damien P. George
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... | lines = []
found_sizes = False
with open(filename) as f:
for line | in f:
line = line.strip()
if line.strip() == "COMPUTING SIZES":
found_sizes = True
elif found_sizes:
lines.append(line)
is_size_line = False
for line in lines:
if is_size_line:
fields = line.split()
data[fields[... |
alexeyraspopov/aiohttp-mongodb-example | server.py | Python | mit | 1,357 | 0 | import asyncio
from aiohttp.web import Application
from Todos import handlers
def create_server(loop, handler, host, port):
srv = loop.create_server(handler, host, port)
return loop.run_until_complete(srv)
def create_app(loop):
app = Application(loop=loop)
handler = app.make_handler()
return app... | odos)
app.router.add_route('DELETE', '/todos', handlers.remove_todos)
app.router.add_route('GET', '/todos/{id}', handlers.get_todo)
app.router.add_route('PATCH', '/todos/{id}', handlers.update_todo)
app.router.add_route('DELETE', '/todos/{id}', handlers.remove_todo)
try:
loop.run_forever()
... | ly:
server.close()
loop.run_until_complete(server.wait_closed())
loop.run_until_complete(handler.finish_connections(1.0))
loop.run_until_complete(app.finish())
loop.close()
if __name__ == '__main__':
run_server()
|
jgerschler/ESL-Games | Camera Pistol/range-detector.py | Python | mit | 1,679 | 0.004169 | # This was pulled from one of the python/opencv sites appearing
# in a Google search. Need to find site and add attribution!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# USAGE: You need to specify a filter and "only one" image source
#
# (python) range-detector --filter RGB --image /path/to/image.png
# or
# (pytho... | thresh = cv2.inRange(frame_to_thresh, (v1_min, v2_min, v3_min), (v1_max, v2_max, v3_max))
cv2.imshow("Original", image)
cv2. | imshow("Thresh", thresh)
if cv2.waitKey(1) & 0xFF is ord('q'):
break
if __name__ == '__main__':
main()
|
theflockers/sober-filter | programs/webservice/__init__.py | Python | gpl-2.0 | 9,399 | 0.005001 | #!/usr/bin/env python2.6
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import cgi
import SocketServer
import ssl
import re
import setproctitle
import others.dict2xml as dict2xml
import sober.config
import sober.settings
import sober.rule
__version__ = 'Sober HTTP/1.0'
_... | i] = tuple(val)
elif reg.group(1) == 'condition':
try:
parts = val[0].split(':')
conditions[i] = {parts[0]: { parts[1]: None}}
except:
conditions[i] = {val[0]: None}
... | for skey, sval in val.iteritems():
if type(sval).__name__ == 'dict':
temp[skey] = {sval.keys()[0]: ('in', items[key])}
else:
temp[skey] = ('in', items[key])
sobermailrulecondition = '(%s)' % str(temp)
... |
nikitos/npui | netprofile/netprofile/pdf/__init__.py | Python | agpl-3.0 | 10,229 | 0.03257 | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: PDF-related tables, utility functions etc.
# © Copyright 2015 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU A... | agesizes.B6[1] * 0.5)),
'c0' : ('C0 (ISO 269)', (91.7 * cm, 129.7 * cm)),
'c1' : ('C1 (ISO 269)', (64.8 * c | m, 91.7 * cm)),
'c2' : ('C2 (ISO 269)', (45.8 * cm, 64.8 * cm)),
'c3' : ('C3 (ISO 269)', (32.4 * cm, 45.8 * cm)),
'c4' : ('C4 (ISO 269)', (22.9 * cm, 32.4 * cm)),
'c5' : ('C5 (ISO 269)', (16.2 * cm, 22.9 * cm)),
'c6' : ('C6 (ISO 269)', (11.4 * cm, 16.2 * cm)),... |
kocicjelena/python-docs-samples | tests/__init__.py | Python | apache-2.0 | 3,946 | 0 | # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | )), 'resources')
class mock_raw_input(object):
def __init__(self, list_):
self.i = 0
self.list_ = list_
def get_next_value(self, question):
ret = self.list_[self.i]
self.i += 1
return ret
def __enter__(self):
self.r | aw_input_cache = __builtin__.raw_input
__builtin__.raw_input = self.get_next_value
def __exit__(self, exc_type, exc_value, traceback):
__builtin__.raw_input = self.raw_input_cache
class CloudBaseTest(unittest.TestCase):
def setUp(self):
self.resource_path = RESOURCE_PATH
# A... |
LinuxChristian/home-assistant | tests/components/sensor/test_sonarr.py | Python | apache-2.0 | 34,600 | 0 | """The tests for the Sonarr platform."""
import unittest
import time
from datetime import datetime
import pytest
from homeassistant.components.sensor import sonarr
from tests.common import get_test_home_assistant
def mocked_exception(*args, **kwargs):
"""Mock exception thrown by requests.get."""
raise OSEr... | "hasFile": "false",
"monitored": "true",
"sceneEpisodeNumber": 0,
"sceneSeasonNumber": 0,
"tvDbEpisodeId": 0,
"absoluteEpisodeNumber": 50,
"series": {
... | dbId": 110381,
"tvRageId": 23354,
"imdbId": "tt1486217",
"title": "Archer (2009)",
"cleanTitle": "archer2009",
"status": "continuing",
"overview": "At I... |
maui-packages/calamares | src/modules/displaymanager/main.py | Python | gpl-3.0 | 17,415 | 0.002871 | #!/usr/bin/env python3
# encoding: utf-8
# === This file is part of Calamares - <http://github.com/calamares> ===
#
# Copyright 2014, Philip Müller <[email protected]>
# Copyright 2014, Teo Mrnjavac <[email protected]>
#
# Calamares is free software: you can redistribute it and/or modify
# it under the terms of the G... | laymanagers:
# Systems with GDM as Desktop Manager
gdm_conf_path = os.path.join(root_mount_point, "etc/gdm/custom.conf")
if os.path.exists(gdm_conf_path):
with open(gdm_conf_path, 'r') as gdm_conf:
text = gdm_conf.readlines()
with open(gdm_conf_path, 'w') ... | ue\n' % username
gdm_conf.write(line)
else:
with open(gdm_conf_path, 'w') as gdm_conf:
gdm_conf.write(
'# Calamares - Enable automatic login for user\n')
gdm_conf.write('[daemon]\n')
gdm_conf.write('AutomaticLogi... |
bridadan/yotta | yotta/lib/fsutils.py | Python | apache-2.0 | 2,102 | 0.004757 | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import os
import errno
import shutil
import platform
import stat
def mkDirP(path):
try:
os.makedirs(path)
except O | SError as exception:
if exception.errno != errno.EEXIST:
raise
def rmF(path):
try:
os.remove(path)
except OSError as exception:
if exception.errno != errno.ENOENT:
raise
def rmRf(path):
# we may have to make files writable before we can successfully delete
... | raise
else:
os.chmod(path, stat.S_IWUSR)
fn(path)
try:
shutil.rmtree(path, onerror=fixPermissions)
except OSError as exception:
if 'cannot call rmtree on a symbolic link' in str(exception).lower():
os.unlink(path)
elif exception.errno == err... |
mdmintz/SeleniumBase | seleniumbase/plugins/pytest_plugin.py | Python | mit | 34,757 | 0 | # -*- coding: utf-8 -*-
""" This is the pytest configuration file """
import colorama
import pytest
import sys
from seleniumbase import config as sb_config
from seleniumbase.core import log_helper
from seleniumbase.core import proxy_helper
from seleniumbase.fixtures import constants
def pytest_addoption(parser):
... | constants.Environment.DEVELOP,
constants.Environment.PRODUCTION,
constants.Environment.MASTER,
constants.Environment.LOCAL,
constants.Environment.TEST
),
default=constants.Enviro... | run the tests in.")
parser.addoption('--data',
dest='data',
default=None,
help='Extra data to pass to tests from the command line.')
parser.addoption('--var1',
dest='var1',
default=None,
... |
joopert/home-assistant | homeassistant/components/nmbs/sensor.py | Python | apache-2.0 | 8,620 | 0.000232 | """Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
)
import home... | sensors.append(NMBSLiveBoard(api_client, station_live))
add_entities(sensors, T | rue)
class NMBSLiveBoard(Entity):
"""Get the next train from a station's liveboard."""
def __init__(self, api_client, live_station):
"""Initialize the sensor for getting liveboard data."""
self._station = live_station
self._api_client = api_client
self._attrs = {}
sel... |
zaresdelweb/tecnoservicio | tecnoservicio/ordenes/migrations/0009_auto_20150513_1841.py | Python | bsd-3-clause | 449 | 0.002227 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ordenes', '0008_tecnico_orden'),
]
operations = [
migrations.AlterField( |
model_name='concepto',
name='nombre',
field=models.CharField(max_length=100, null=True, verbose_name=b'Concepto', blank=True),
),
| ]
|
huran2014/huran.github.io | wot_gateway/usr/lib/python2.7/email/mime/application.py | Python | gpl-2.0 | 1,256 | 0 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Keith Dart
# Contact: [email protected]
"""Class representing application/* type MIME documents."""
__all__ = ["MIMEApplication"]
from email import encoders
from email.mime.nonmultipart import MIMENonMultipart
class MIMEApplication(MIMENonMultipart)... | self, _data, _subtype='octet-stream',
_encoder=encoders.encode_base64, **_params):
"""Create an application/* type MIME document.
_data is a string containing the raw application data.
_subtype is the MIME content type subtype, defaulting to
'octet-stream'.
_e... | e64 encoding.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
raise TypeError('Invalid application MIME subtype')
MIMENonMultipart.__init__(self, ... |
dslackw/slpkg | slpkg/repolist.py | Python | gpl-3.0 | 2,957 | 0 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# repolist.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <[email protected]>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware in | stallations
# https://gitlab.com/dslackw/slpkg
# Slpkg 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 ve | rsion 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should h... |
snyderr/robotframework | src/robot/reporting/stringcache.py | Python | apache-2.0 | 1,574 | 0 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | nder the License.
from robot.utils import OrderedDict, compress_text
class StringIndex(int):
pass
class StringCache(object):
_compress_threshold = 80
_use_compressed_threshold = 1.1
_zero_index = StringIndex(0)
def __init__(self):
self._cache = OrderedDict({'*': self._zero_index})
... |
if text not in self._cache:
self._cache[text] = StringIndex(len(self._cache))
return self._cache[text]
def _encode(self, text):
raw = self._raw(text)
if raw in self._cache or len(raw) < self._compress_threshold:
return raw
compressed = compress_text(... |
lwldcr/keyboardman | common/const.py | Python | gpl-3.0 | 214 | 0.009346 | # -*- coding: utf-8 -*-
__author__ = 'LIWEI2 | 40'
"""
Constants definition
"""
class Const(object):
class RetCode(object):
OK = 0
Inv | alidParam = -1
NotExist = -2
ParseError = -3 |
KineticCookie/mist | examples-python/simple_streaming.py | Python | apache-2.0 | 1,188 | 0.004209 | from mist.mist_job import *
class SimpleStreaming(MistJob, WithStreamingContext, WithPublisher):
def execute(self, parameters):
import time
def takeAndPublish(time, rdd):
taken = rdd.take(11)
self.publisher.publish("-------------------------------------------")
... | type(ssc)
rddQueue = []
for i in range(500):
rddQueue += [ssc.sparkContext.parallelize([j for j in range(1, 1001)], 10)]
# Create the QueueInputDStream and use it do some processing
inputStream = ssc.queueStream(rddQueue)
mappedStream = inputStream.map(lambda... | dStream.foreachRDD(takeAndPublish)
ssc.start()
time.sleep(15)
ssc.stop(stopSparkContext=False, stopGraceFully=False)
result = "success"
return {"result": result}
|
ufjfeng/leetcode-jf-soln | python/189_rotate_array.py | Python | mit | 1,252 | 0.003994 | """
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to
[5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different
ways to solve this problem.
Hint:
Could you do it in-place with O(1) ext... | elf, nums, k):
n = len(nums)
k %= n
self.reverse(nums, 0, n - k)
self.reverse(nums, n - k, n)
self.reverse(nums, 0, n)
def reverse(self, n | ums, start, end):
for x in range(start, (start + end) / 2):
nums[x] ^= nums[start + end - x - 1]
nums[start + end - x - 1] ^= nums[x]
nums[x] ^= nums[start + end - x - 1]
"""
|
gangadharkadam/johnfrappe | frappe/website/render.py | Python | mit | 4,424 | 0.028707 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr
import mimetypes, json
from werkzeug.wrappers import Response
from frappe.website.context import get_context
f... | 1 else None
if doctype in doctypes:
return doctype, name
# try scrubbed
doctype = doctype.replace("_", " ").title()
if doctype in doctypes:
return doctype, name
return None, None
def build_response(path, data, http_status_code):
# build response
response = Response()
response. | data = set_content_type(response, data, path)
response.status_code = http_status_code
response.headers[b"X-Page-Name"] = path.encode("utf-8")
response.headers[b"X-From-Cache"] = frappe.local.response.from_cache or False
return response
def render_page(path):
"""get page html"""
cache_key = ("page_context:{}" if ... |
lmazuel/azure-sdk-for-python | azure-mgmt-servicebus/tests/test_azure_mgmt_servicebus_check_name_availability.py | Python | mit | 1,330 | 0.003765 | # coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#------------------------------------- | -------------------------------------
import unittest
import azure.mgmt.servicebus.models
from azure.mgmt.servicebus.models import SBNamespace
from azure.common.credentials import ServicePrincipalCredentials
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
class MgmtServiceBusTest(AzureMgmtTe... | etUp(self):
super(MgmtServiceBusTest, self).setUp()
self.servicebus_client = self.create_mgmt_client(
azure.mgmt.servicebus.ServiceBusManagementClient
)
def process(self, result):
pass
@ResourceGroupPreparer()
def test_sb_namespace_available(self, resource_grou... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/psrc/household_x_zone/travel_time_hbw_am_drive_alone_from_home_to_work_alt.py | Python | gpl-2.0 | 2,397 | 0.01627 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.abstract_variables.abstract_travel_time_variable import abstract_travel_time_variable
class travel_time_hbw_am_drive_alone_from_home_to_work_alt(abstract_travel_time_variable):
... |
from urbansim.variable_test_toolbox import VariableTestToolbox
from psrc.opus_package_info import package
from urbansim.datasets.zone_dataset import ZoneDataset
from urbansim.datasets.household_dataset impo | rt HouseholdDataset
from psrc.datasets.person_x_zone_dataset import PersonXZoneDataset
from psrc.datasets.person_dataset import PersonDataset
class Tests(opus_unittest.OpusTestCase):
variable_name = "psrc.household_x_zone.travel_time_hbw_am_drive_alone_from_home_to_work_alt"
def test_my_inputs(self):
... |
lbybee/reddit_spelling_index | reddit_db_scraper.py | Python | gpl-2.0 | 2,876 | 0.004868 | from pymongo import MongoClient
import json
import requests
import time
from datetime import datetime
def subredditInfo(sr, limit=100, sorting="top", period="day",
user_agent="ChicagoSchool's scraper", **kwargs):
"""retrieves X (max 100) amount of stories in a subreddit
'sorting' is whether ... | ChicagoSchool's scraper", **kwargs):
url = "http://www.reddit.com/%s.json?sort=%s&limit=%d" % (link, sorting, limit)
r = requests.get(url, headers={"user-agent": user_agent})
j = json.loads(r.text)
date = datetime.fromtimestamp(j[0]["data"]["children"][0]["data"]["created"])
db_data = {"date": date... | all the threads for a subreddit and stores them in a
mongodb db"""
m_ind = 0
t_f = datetime.now()
sub_ln = len(sub_l)
client = MongoClient()
db = client[db_n]
col = db[col_n]
while True:
t_1 = datetime.now()
for i, s in enumerate(sub_l):
try:
... |
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/script.module.elementtree/lib/elementtree/ElementInclude.py | Python | gpl-2.0 | 5,051 | 0.00099 | #
# ElementTree
# $Id: ElementInclude.py 3225 2007-08-27 21:32:08Z fredrik $
#
# limited xinclude support for element trees
#
# history:
# 2003-08-15 fl created
# 2003-11-14 fl fixed default loader
#
# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
#
# [email protected]
# http://www.pythonware... | he tree contains malformed XInclude elements.
# @throws IOError If the function fails to load a given resource.
def include(elem, loader=None):
if loader is None:
loader = default_loader
# look for xinclude elements
i = 0
while i < len(elem):
e = elem[i]
if e.tag == XINCLUDE_INC... | ref")
parse = e.get("parse", "xml")
if parse == "xml":
node = loader(href, parse)
if node is None:
raise FatalIncludeError(
"cannot load %r as %r" % (href, parse)
)
node = copy(nod... |
reverbrain/elliptics | recovery/elliptics_recovery/types/__init__.py | Python | lgpl-3.0 | 769 | 0 | # =============================================================================
# 2013+ Copyright (c) Alexey Ivanov <[email protected]>
# All rights reserved.
#
# This program is free software; you can redi | stribute it and/or modify
# it under the terms of the GNU General Public License as published by
| # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Pub... |
galaxy-genome-annotation/python-apollo | arrow/commands/cmd_remote.py | Python | mit | 643 | 0 | import click
from arrow.commands.remote.add_organism import cli as add_organism
from arrow.commands.remote.add_track import cli as add_track
from arrow.commands.remote.delete_organism import cli | as delete_organism
from arrow.commands.remote.delete_track import cli as delete_track
from | arrow.commands.remote.update_organism import cli as update_organism
from arrow.commands.remote.update_track import cli as update_track
@click.group()
def cli():
pass
cli.add_command(add_organism)
cli.add_command(add_track)
cli.add_command(delete_organism)
cli.add_command(delete_track)
cli.add_command(update_or... |
robwarm/gpaw-symm | gpaw/test/au02_absorption.py | Python | gpl-3.0 | 2,114 | 0.003784 | import numpy as np
from ase import Atoms |
from gpaw import GPAW, FermiDirac
from gpaw.response.df import DielectricFunction
from gpaw.test import equal, findpeak
GS = 1
ABS = 1
if GS:
cluster = Atoms('Au2', [(0, 0, 0), (0, 0, 2.564)])
cluster.set_cell((6, 6, 6), scale_atoms=False)
cluster.center()
calc = GPAW(mode='pw',
dtype=... | calc)
cluster.get_potential_energy()
calc.diagonalize_full_hamiltonian(nbands=24, scalapack=True)
calc.write('Au2.gpw', 'all')
if ABS:
df = DielectricFunction('Au2.gpw',
frequencies=np.linspace(0, 14, 141),
hilbert=not True,
... |
palankai/pyrs-resource | pyrs/resource/errors.py | Python | lgpl-3.0 | 5,253 | 0 | from pyrs import schema
import six
from . import lib
from . import response
class Error(Exception):
"""
This is the base exception of this framework.
The response based on this exception will be a JSON data
"""
#: HTTP status code (default=500)
status = 500
#: HTTP Response headers, (de... | n gives back an `Error` instance. The created `Error`
instance `error` property will be updated by the fully qualified name
of the `original` exception.
You could use it for `Error` instances as well, though is not
recommended.
"""
ex = cls(*original.args, cause=original)... | codes.
"""
status = 400
class ValidationError(Error):
status = 500
error = 'validation_error'
class InputValidationError(Error):
status = 400
error = 'invalid_request_format'
class DetailsSchema(schema.Object):
"""
Details part of the error schema. Additional properties possible.
... |
akozumpl/anaconda | pyanaconda/network.py | Python | gpl-2.0 | 48,413 | 0.002417 | #
# network.py - network configuration install data
#
# Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Red Hat, Inc.
# 2008, 2009
#
# 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 Fou... | fix):
""" Convert prefix (CIDR bits) to netmask """
_bytes = []
for _i in range(4):
if prefix >= 8:
_bytes.append(255)
prefix -= 8
else:
_bytes.append(256 - 2**(8 | -prefix))
prefix = 0
netmask = ".".join(str(byte) for byte in _bytes)
return netmask
# Try to determine what the hostname should be for this system
def getHostname():
hn = None
# First address (we prefer ipv4) of last device (as it used to be) wins
for dev in nm.nm_activated_devices()... |
susemeee/Chunsabot-framework | chunsabot/pi.py | Python | mit | 1,587 | 0.009452 | from decimal import *
class PI:
#Sets decimal to 25 digits of precision
getcontext().prec = 1000
@staticmethod
def factorial(n):
# if n<1:
# return 1
# else:
# return n * PI.factorial(n-1)
result = 1
for i in xrange(2, n+1):
result *=... | turn pi
@staticmethod
def chudnovskyBig(n): #http://en.wikipedia.org/wiki/Chudnovsky_algorithm
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(-1)**k)*(Deci | mal(PI.factorial(6*k))/((PI.factorial(k)**3)*(PI.factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
k += 1
pi = pi * Decimal(10005).sqrt()/4270934400
pi = pi**(-1)
return pi
@staticmethod
def calculate():
return PI.bellardBig(1000)
|
mila-iqia/babyai | scripts/make_agent_demos.py | Python | bsd-3-clause | 8,078 | 0.0026 | #!/usr/bin/env python3
"""
Generate a set of agent demonstrations.
The agent can either be a trained model or the heuristic expert (bot).
Demonstration generation can take a long time, but it can be parallelized
if you have a cluster at your disposal. Provide a script that launches
make_agent_demos.py at your cluste... | sodes', 0]))
logger.info('LAUNCH COMMAND')
logger.info(cmd_i)
output = subprocess.check_output(cmd_i)
logger.info('LAUNCH OUTPUT')
logger.info(output.decode('utf-8'))
job_demos = [None] * args.jobs
while True:
jobs_done = 0
for i in range(args.jobs):
| if job_demos[i] is None or len(job_demos[i]) < demos_per_job:
try:
logger.info("Trying to load shard {}".format(i))
job_demos[i] = utils.load_demos(utils.get_demos_path(job_demo_names[i]))
logger.info("{} demos ready in shard {}".form... |
daajoe/trellis | trellis/extractor/__init__.py | Python | gpl-3.0 | 99 | 0.010101 | f | rom edges import EdgeExtractor
from extractor import Extract | or
from parambfs import ParamExtractor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.