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 |
|---|---|---|---|---|---|---|---|---|
harpribot/deep-summarization | docs/source/conf.py | Python | mit | 9,478 | 0.005803 | # -*- coding: utf-8 -*-
#
# Deep Summarization documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 11 18:20:37 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated ... | any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as | a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Deep Summarization'
copyright = u'2017, Harshal Priyadarshi'
author = u'Ha... |
wq/wq | setup.py | Python | mit | 2,538 | 0.000394 | import os
from setuptools import setup
LONG_DESCRIPTION = """
A modular framework for mobile surveys and field data collection via offline-capable mobile web apps.
"""
def readme():
try:
readme = open('README.md')
except IOError:
return LONG_DESCRIPTION
else:
return readme.read()
... | 'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.1',
'Framework :: Django :: 3.0',
'Framework :: Django :: 3.2',
'Topic :: Software Development | :: Libraries :: Application Frameworks',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Scientific/Engineering :: GIS',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Pre-processors',
'Topic :: Database :: Database Engines/Servers',
... |
ANTsX/ANTsPy | ants/registration/metrics.py | Python | apache-2.0 | 1,024 | 0.003906 |
__all__ = ['image_mutual_information']
from .. import utils
def imag | e_mutual_information(image1, image2):
"""
Compute mutual information between two ANTsImage types
ANTsR function: `antsImageMutualInformation`
Arguments
---------
image1 : ANTsImage
image 1
image2 : ANTsImage
image 2
Returns
-------
scalar
Example
... | ) ).clone('float')
>>> mival = ants.image_mutual_information(fi, mi) # -0.1796141
"""
if (image1.pixeltype != 'float') or (image2.pixeltype != 'float'):
raise ValueError('Both images must have float pixeltype')
if image1.dimension != image2.dimension:
raise ValueError('Both images must ... |
getsentry/zeus | zeus/api/schemas/revision.py | Python | apache-2.0 | 419 | 0 | from marshmallow import Schema, fields
from .author import AuthorSchema
class RevisionSchema(Schema):
| id = fields.UUID(dump_only=True)
sha = fields.Str()
message = fields.Str()
autho | rs = fields.List(fields.Nested(AuthorSchema()), dump_only=True)
created_at = fields.DateTime(attribute="date_created", dump_only=True)
committed_at = fields.DateTime(attribute="date_committed", dump_only=True)
|
jbremer/monitor | src/capstone/bindings/python/test_skipdata.py | Python | gpl-3.0 | 2,425 | 0.003299 | #!/usr/bin/env python
# Capstone Python bindings, by Nguyen Anh Quynnh <aquynh@gmail.com>
from __future__ import print_function
from capstone import *
import binascii
from xprint import to_x, to_hex, to_x_32
X86_CODE32 = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x00\x91\x92"
RANDOM_CODE = b"\xed\x00\x00\x0... | t, syntax) in all_tests:
print('*' * 40)
print("Platform: %s" % comment)
print("Disasm:"),
print(to_hex(code))
for insn in cs_disasm_quick(arch, mo | de, code, 0x1000):
print("0x%x:\t%s\t%s" % (insn.address, insn.mnemonic, insn.op_str))
print
# Sample callback for SKIPDATA option
def testcb(buffer, size, offset, userdata):
# always skip 2 bytes of data
return 2
# ## Test class Cs
def test_class():
for (arch, mode, code, comment, s... |
TheTimmy/spack | lib/spack/spack/test/install.py | Python | lgpl-2.1 | 5,640 | 0 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | write to the Free Software
# | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import os
import pytest
import spack
import spack.store
from spack.spec import Spec
def test_install_and_uninstall(install_mockery, mock_fetch):
# Get a basic con... |
tszym/ansible | lib/ansible/modules/cloud/ovirt/ovirt_quotas_facts.py | Python | gpl-3.0 | 3,955 | 0.00177 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This fil | e is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be... | ils.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ov... |
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/pylint/test/functional/misplaced_comparison_constant.py | Python | apache-2.0 | 1,003 | 0.005982 | """Check that the constants are on the right side of the comparisons"""
# pylint: disable=singleton-comparison, missing-docstring, too-few-public-methods
class MyClass(object):
def __init__(self):
self.attr = 1
def dummy_return(self):
return self.attr
def dummy_return():
return 2
def ba... | arisons():
"""this is not ok"""
instance = MyClass()
for i in range(10):
if 5 <= i: # [misplaced-comparison-constant]
pass
if 1 == i: # [misplaced-comparison-constant]
pass
if 3 < dummy_return(): # [misplaced-comparison-constant]
pass
if... | nt]
pass
if "aaa" == instance.attr: # [misplaced-comparison-constant]
pass
def good_comparison():
"""this is ok"""
for i in range(10):
if i == 5:
pass
|
wojtask/CormenPy | src/chapter02/exercise2_3_7.py | Python | gpl-3.0 | 339 | 0 | from chapter02.exercise2_3_5 import rec | ursive_binary_search
from chapter02.textbook2_3 import merge_sort
from util import between
def sum_search(S, x):
n = S.length
merge_sort(S, 1, n)
for i in between(1, n - 1):
if recursive_binary | _search(S, x - S[i], i + 1, n) is not None:
return True
return False
|
dhongu/l10n-romania | l10n_ro_intrastat/models/l10n_ro_intrastat.py | Python | agpl-3.0 | 1,017 | 0.002953 | # © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com
# See README.rst file on addons root folder for license details
from odoo import fields, models
class IntrastatTransaction(models.Mod | el):
_name = "l10n_ro_intrastat.transaction"
_description = "Intrastat Transaction"
_rec_name = "description"
code = fields.Char("Code", required=True, readonly=True)
parent_id = fields.Many2one("l10n_ro_intrastat.transaction", "Parent Code", readonly=True)
descriptio | n = fields.Text("Description", readonly=True)
_sql_constraints = [
("l10n_ro_intrastat_trcodeunique", "UNIQUE (code)", "Code must be unique."),
]
class IntrastatTransportMode(models.Model):
_name = "l10n_ro_intrastat.transport_mode"
_description = "Intrastat Transport Mode"
code = fields... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py | Python | mit | 1,705 | 0.006452 | """Suite Standard Suite: Common terms for most applications
Level 1, version 1
Generated from /Applications/Internet Explorer.app
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = '****'
class Standard_Suite_Events:
_argmap_get = {
'as' : 'rtyp',
}
de... | - the selected text """
which = 'stxt'
want = 'TEXT'
selected_text = _Prop_selected_text()
application._superclassnames = []
application._privpropdict = {
'selected_text' : _Prop_selected_text,
}
application._privelemdict = {
}
#
# Indices of t | ypes declared in this module
#
_classdeclarations = {
'capp' : application,
}
_propdeclarations = {
'stxt' : _Prop_selected_text,
}
_compdeclarations = {
}
_enumdeclarations = {
}
|
21E14/bitcoin | test/functional/forknotify.py | Python | mit | 2,125 | 0.002353 | #!/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 the -alertnotify option."""
import os
import time
from test_framework.test_framework import Bitco... | lf.sync_all()
with open(self.alert_filename, 'r', encoding='utf8') as f:
| alert_text2 = f.read()
if alert_text != alert_text2:
raise AssertionError("-alertnotify excessive warning of up-version blocks")
if __name__ == '__main__':
ForkNotifyTest().main()
|
arve0/example_lessons | src/python/lessons/Quiz/Project Resources/Quiz.py | Python | cc0-1.0 | 553 | 0.01085 | pr | int("In Python, what do you call a 'box' used to store data?")
answer = input()
if answer == "variable":
print(" :) ")
else:
print(" :( ")
print("Thank you for playing!")
print('''
Q1 - In Python, what do you call a 'box' used to store data?
a - | text
b - variable
c - a shoe box
''')
answer = input().lower()
if answer == "a":
print(" Nope - text is a type of data :( ")
elif answer == "b":
print(" Correct!! :) ")
elif answer == "c":
print(" Don't be silly! :( ")
else:
print(" You didn't choose a, b or c :( ")
|
TheGurke/Progenitus | sleekxmpp/thirdparty/mini_dateutil.py | Python | gpl-3.0 | 9,155 | 0.002622 | # This module is a very stripped down version of the dateutil
# package for when dateutil has not been installed. As a replacement
# for dateutil.parser.parse, the parsing methods from
# http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/
#As such, the following copyri... | fset) and
self._offset == other._offset)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__,
repr(self._name),
self._... | setmins):
"""For internal use only: Returns a tzinfo with
the given fixed offset. This creates only one instance
for each offset; the zones are kept in a dictionary"""
if offsetmins == 0:
return UTC
if not offsetmins in _fixed_offset_tzs:
if offsetmins <... |
psiinon/addons-server | src/olympia/devhub/tests/test_views_submit.py | Python | bsd-3-clause | 108,742 | 0 | # -*- coding: utf-8 -*-
import json
import os
import io
import stat
import tarfile
import zipfile
from datetime import datetime, timedelta
from urllib.parse import urlencode
from django.conf import settings
from django.core.files import temp
from django.core.files.storage import default_storage as storage
from django... | =None)
response = self.client.get(reverse('devhub.submit.agreement'))
| assert response.status_code == 200
form = response.context['agreement_form']
assert 'recaptcha' in form.fields
response = self.client.post(reverse('devhub.submit.agreement'))
# Captcha is properly rendered
doc = pq(response.content)
assert doc('.g-recaptcha')
... |
Azure/azure-sdk-for-python | sdk/synapse/azure-synapse/azure/synapse/artifacts/aio/_configuration_async.py | Python | mit | 3,080 | 0.003571 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Credential
:param endpoint: The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net.
:type endpoint: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
endpoint: str,
**kwargs: Any
) -> None:
if credential is None... | uper(ArtifactsClientConfiguration, self).__init__(**kwargs)
self.credential = credential
self.endpoint = endpoint
self.api_version = "2019-06-01-preview"
self.credential_scopes = ['https://dev.azuresynapse.net/.default']
self.credential_scopes.extend(kwargs.pop('credential_scope... |
golsun/GPS | src/core/def_build_graph.py | Python | mit | 4,118 | 0.026712 | from networkx import DiGraph
from networkx.readwrite import json_graph
import cantera as ct
import numpy as np
import json
#from src.core.def_tools import *
import os
__author__ = 'Xiang Gao'
""" ----------------------------------------------
construction of the element flux graph
---------------------------------... | erefore we use abs(RR) here
dw = float(n_i2j * abs(rr[id_rxn]))
try:
flux_graph[source][target]['flux'] += dw
except KeyError:
# if this edge doesn't exist, create it
flux_graph.add_edge(source, target)
flux_g | raph[source][target]['flux'] = dw
flux_graph[source][target]['member'] = {}
flux_graph[source][target]['member'][str(id_rxn)] = dw
flux_graph[source][target]['1/flux'] = 1.0 / flux_graph[source][target]['flux']
# -------------------------------------
# save the graph using json, which is fast, and h... |
tp81/openmicroscopy | components/tools/OmeroPy/test/unit/tablestest/test_hdfstorage.py | Python | gpl-2.0 | 10,650 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test of the HDF storage for the Tables API.
Copyright 2009-2014 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import time
import pytest
import omero.columns
import omero.tables
import logging
import ... | self.lock)
self.init(hdf, True)
hdf.cleanup()
def testAddSingleRow(self):
hdf = omero.tables.HdfStorage(self.hdfpath(), self.lock)
self.init(hdf, True)
self.append(hdf, {"a": 1, "b | ": 2, "c": 3})
hdf.cleanup()
def testModifyRow(self):
hdf = omero.tables.HdfStorage(self.hdfpath(), self.lock)
self.init(hdf, True)
self.append(hdf, {"a": 1, "b": 2, "c": 3})
self.append(hdf, {"a": 5, "b": 6, "c": 7})
data = hdf.readCoordinates(hdf._stamp, [0, 1], se... |
AccelAI/accel.ai | flask-aws/lib/python2.7/site-packages/ebcli/controllers/appversion.py | Python | mit | 2,295 | 0.004793 | 8# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... | r interactive mode
self.interactive_list_version()
def interactive_list_version(self):
"""Interactive mode which allows user to see previous
versions and allow a choice to:
- deploy a different version.
- dele | te a certain version
Run when the user supplies no argument to the --delete flag.
"""
app_versions = elasticbeanstalk.get_application_versions(self.app_name)['ApplicationVersions']
appversionops.display_versions(self.app_name, self.env_name, app_versions)
|
openstack/horizon | openstack_dashboard/dashboards/admin/floating_ips/forms.py | Python | apache-2.0 | 2,877 | 0 | # Copyright 2016 Letv Cloud Computing
# 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... | n fip
except Exception:
| redirect = reverse('horizon:admin:floating_ips:index')
msg = _('Unable to allocate floating IP.')
exceptions.handle(request, msg, redirect=redirect)
|
Tomasuh/Tomasuh.github.io | files/ClamAVDatabaseDL.py | Python | mit | 5,183 | 0.01775 | #Clamav database fetcher and unpacker.
#Made by Tomasuh
#For contact: tomasuh [at]
import sys,tarfile,os,shutil,stat,urllib2,random
class ClamAvDatabase(object):
wantedFiles = ["main.db","main.fp","main.hdb","main.info","main.mdb","main.ndb","main.zmd"]
def __init__(self):
if len (sys.argv) != 2:
... | taSave)*10/fileSize))
sys.stdout.write ("\r"+"["+"*" * progress + " " * (10 - progress)+ "]")
sys.stdout.flush()
print "\n"
with open("test.cvd","wb") as f:
f.write(fileDataSave)
#Makes file writable if not.
def makeWritable(self,directory,fileN):
if... | def cleanup(self):
if os.access("clamavDB", os.F_OK):
answ = raw_input("Directory clamavDB already exists, remove previous db files to avoid collisions? yes/no/abort\n")
if answ=="yes":
#Would be so more neat with just a rmtree for
#the whole clamavDB an... |
krafczyk/spack | var/spack/repos/builtin/packages/sleef/package.py | Python | lgpl-2.1 | 1,534 | 0.000652 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@ | llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# p... | RANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free S... |
waseem18/oh-mainline | vendor/packages/amqp/funtests/test_with.py | Python | agpl-3.0 | 2,144 | 0 | #!/usr/bin/env python
"""
Test support for 'with' statements
"""
# Copyright (C) 2009 Barry Pederson <bp@barryp.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.... | # check that the channel was closed
#
self.assertEqual(1 in conn.channels, False)
| self.assertEqual(ch.is_open, False)
#
# Check that the connection was closed
#
self.assertEqual(conn.transport, None)
def main():
suite = unittest.TestLoader().loadTestsFromTestCase(TestChannel)
unittest.TextTestRunner(**settings.test_args).run(suite)
if __name__ == '_... |
numenta/nupic.research | tests/unit/frameworks/htm/spatial_pooler_compute_test.py | Python | agpl-3.0 | 4,173 | 0.00024 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2022, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following | terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ev... | e the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import time
import unitte... |
fcurella/jsx-lexer | setup.py | Python | mit | 893 | 0 | import io
import os
from setuptools import setup, find_packages
VERSION = "1.0.0"
here = os.path.abspath(os.path.dirname(__file__))
README = io.open(os.path.join(here, "README.rst"), encoding="utf8").read()
setup(
name="jsx-lexer",
description="A JSX lexer for Pygments",
long_description=README,
ver... | classifiers=[
"Environment :: Plugins",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
],
keywords="pygments highlight jsx react",
install_requires=["Pygments >= 2.7"],
test_suite="tests",
license="MIT License",
packages=find_packages(exclude=... | sts.*"]),
entry_points="""
[pygments.lexers]
jsx=jsx:JsxLexer
""",
)
|
vonnenaut/computer-network-analysis | main.py | Python | gpl-3.0 | 10,602 | 0.021977 | """
Algorithmic Thinking 1
wk 4
Aplication #2
Questions
"""
# imports
import urllib2
import random
import time
import math
import UPATrial
import numpy
from collections import deque
import matplotlib.pyplot as plt
############################################
def copy_graph(graph):
"""
Make... | ""
if num_nodes <= 0:
return {}
dict_graph = {}
for node in range(num_nodes):
node_set = set() # edges
for neighbor in range(num_nodes):
random_value = random.random()
if | node != neighbor and random_value < probability:
node_set.add(neighbor)
dict_graph[node] = node_set
return dict_graph
def test_gen_er_graph():
""" tests gen_er_graph function """
print "num_nodes = 0, probability = .004"
print gen_er_graph(0, .004)
print "num_nodes = 5, probability = .004... |
mancoast/CPythonPyc_test | cpython/223_test_scope.py | Python | gpl-3.0 | 9,168 | 0.011671 | from test_support import verify, TestFailed, check_syntax
import warnings
warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
print "1. simple nesting"
def make_adder(x):
def adder(y):
return x + y
return adder
inc = make_adder(1)
plus10 = make_adder(10)
verify(inc(1) == 2)
v... | f error(y):
exec "a = 1"
def f(x):
return x + y
return f
""")
check_syntax("""\
def f(x):
def g():
return x
del x # can't del name
""")
check_syntax("""\
def f():
def g():
from string import *
return strip # global or local?
""")
# and | verify a few cases that should work
exec """
def noproblem1():
from string import *
f = lambda x:x
def noproblem2():
from string import *
def f(x):
return x + 1
def noproblem3():
from string import *
def f(x):
global y
y = x
"""
print "12. lambdas"
f1 = lambda x: la... |
RRCKI/pilot | RunJob.py | Python | apache-2.0 | 69,493 | 0.004375 | # Class definition:
# RunJob
# This is the main RunJob class; RunJobEvent etc will inherit from this class
# Note: at the moment, this class is essentially the old runJob module turned object oriented.
# The class will later become RunJobNormal, ie responible for running normal PanDA jobs.
# At th... | or the log file
__outputDir = "" # location of output files (destination for mv site mover)
__pilot_initdir = "" # location of where the pilot | is untarred and started
__pilotlogfilename = "pilotlog.txt" # default pilotlog filename
__pilotserver = "localhost" # default server
__pilotport = 88888 # default port
__proxycheckFlag = True # True (default): perform proxy validity checks, False: no check
__... |
adviti/melange | thirdparty/google_appengine/lib/django_1_2/tests/regressiontests/datatypes/tests.py | Python | apache-2.0 | 4,274 | 0.005381 | import datetime
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase
from django.utils import tzinfo
from models import Donut, RumBaba
from django.conf import settings
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
self.assertFal... | datetime.date(1938, 6, 4))
self.assertEqual(d2.baked_time, datetime.time(5, 30))
self.assertE | qual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59))
def test_time_field(self):
#Test for ticket #12059: TimeField wrongly handling datetime.datetime object.
d = Donut(name='Apple Fritter')
d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=5... |
FilippoC/anatomize | unittest/ngram/suite.py | Python | mit | 296 | 0.006757 |
import unittest
from | ngram_window_test_case import NgramWindowTestCase
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(NgramWindowTestCase))
| return suite
if __name__ == "__main__":
unittest.TextTestRunner().run(suite())
|
RPGOne/Skynet | imbalanced-learn-master/doc/conf.py | Python | bsd-3-clause | 10,006 | 0.005397 | # -*- coding: utf-8 -*-
#
# imbalanced-learn documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 18 14:44:12 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated fi... | contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htacc... | # directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entitie... |
buxx/synergine | synergine/lib/eint.py | Python | apache-2.0 | 471 | 0.002123 | class IncrementedNamedInt:
_last_int = 0
_names = {}
@classmethod
def get(cls, name):
| cls._last_int += 1
cls._names[cls._last_int] = n | ame
return cls._last_int
@classmethod
def name_of(cls, int):
return cls._names[int]
@classmethod
def get_for_name(cls, name):
for int in cls._names:
if cls._names[int] == name:
return int
raise Exception("Named int not found") |
BartSaelen/kubb_match | kubb_match/service/battle_service.py | Python | apache-2.0 | 3,670 | 0.001907 | # -*- coding: utf-8 -*-
from kubb_match.data.models import GridPosition, Round, Game
class BattleService(object):
def __init__(self):
pass
def create_games(self, positions):
games = []
nr = int(len(positions) / 5)
field = 1
for row in ('A', 'B', 'C', 'D', 'E'):
... | :
| pos -= 8
key = row + str(pos)
else:
row = self.move_row_down(key[0])
pos = int(key[1]) + 2
if pos > 8:
pos -= 8
key = row + str(pos)
while key in [pos.position for pos in positions]:
pos += 1
... |
hkar/get-vault | tests/test_crypto.py | Python | gpl-3.0 | 1,236 | 0.002427 | __author__ = 'hkar'
import Vault.Crypto
import Vault.Key
from test_helpers import *
import os
def test_aes(tmpdir):
# make tmp text files
f = create_test_file(tmpdir)
text = str(f.read())
# define file names
file_in = str(f)
file_out = file_in + ".enc"
# generate random secret
secr... | ric.decrypt(file_out, file_in, Vault.Key.RsaKey.private())
Vault.Key.RsaKey.delete_keys()
assert text == open(file | _in, 'r').read() |
seraphln/wheel | wheel/spiders/juweixin/crawler.py | Python | gpl-3.0 | 16,096 | 0.006163 | # coding=utf8
#
"""
a crawler for juweixin.com
"""
import sys
import os.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.curdir,
os.path.pardir,
os.path.pardir,
o... | xy_dict, meta_info = generate_proxy(proxies)
else:
if 'timeout' in str(e):
return 'timeout'
if 'Connection aborted.' in str(e):
time.sleep(1)
import traceback
print traceback.print_exc()
... | """ """
for cur_cate in cate_lst:
parent_cate = Category.objects.filter(name=cur_cate.get('parent_cate')).first()
if not parent_cate:
cur_name = cur_cate.get('parent_cate')
parent_cate = Category(name=cur_name)
parent_cate.save()
for cur_sub_cate in cur_ca... |
toladata/TolaActivity | workflow/__init__.py | Python | apache-2.0 | 55 | 0 | default_app_config = 'workflo | w.apps.WorkflowAppConfi | g'
|
pguridi/pywars | manage.py | Python | mit | 255 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SET | TINGS_MODULE", "battleground.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys. | argv)
|
pantsbuild/pants | src/python/pants/backend/python/dependency_inference/parse_python_imports.py | Python | apache-2.0 | 3,338 | 0.002996 | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
import pkgutil
from dataclasses import dataclass
from pants.backe | nd.python.target_types import PythonSourceField
from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints
from pants.backend.python.util_rules.pex_environment import PythonExecutable
from pants.core.util_rules.source_files import SourceFilesRequest
from pants.core.util_rules.stripped_so... | nts.engine.fs import CreateDigest, Digest, FileContent, MergeDigests
from pants.engine.process import Process, ProcessResult
from pants.engine.rules import Get, MultiGet, collect_rules, rule
from pants.util.frozendict import FrozenDict
from pants.util.logging import LogLevel
@dataclass(frozen=True)
class ParsedPython... |
atwardowski/Dramiel | src/twisted/mod/range.py | Python | mit | 4,384 | 0.032162 | #!/usr/bin/env python
import random
import re
import time
import datetime
import sqlite3
import os
import itertools
import requests
import eveapi
from bs4 import BeautifulSoup
conn = sqlite3.connect(os.path.expanduser("~/eve.sqlite"))
HOME = "PR-8CA"
def calc_jumps(system, start):
url = "http://evemaps.dotlan.net/ro... | (args[0].strip())
if len(args)>1:
start = complete(args[1].strip())
else:
| start = complete(HOME)
if len(c)==0:
tbot.msg(channel, "System not found")
elif len(c)>1:
tbot.msg(channel, "Please be more specific: " + " ".join(map(lambda x:"%s (%s)" % (x[0], x[1]), c)))
elif len(start)==0:
tbot.msg(channel, "System not found")
elif len(start)>1:
tbot.msg(channel, "Please be more specif... |
martinmcbride/pytexture | examples/drawing/simple-make-frame.py | Python | mit | 807 | 0.002478 | from generativepy.drawing import make_image_frame, setup
from generativepy.movie import save_frame
from generativepy.geometry import text
fro | m generativepy.color import Color
from generativepy.utils import temp_file
'''
Illustrates simple use of make_image_frame
'''
def draw(ctx, pixel_width, pixel_height, frame_no, frame_count):
setup(ctx, pixel_width, pixel_height, width=5, background=Color(0.4))
ctx.se | t_source_rgba(*Color(0.5, 0, 0))
ctx.rectangle(0.5, 0.5, 2.5, 1.5)
ctx.fill()
ctx.set_source_rgba(*Color(0, 0.75, 0, 0.5))
ctx.rectangle(2, 0.25, 2.5, 1)
ctx.fill()
text(ctx, "simple-make-image-frame", 1, 3, size=0.2, color=Color('cadetblue'), font='Arial')
frame = make_image_frame(draw, 500... |
foospidy/DbDat | plugins/db2/check_privilege_dbadm.py | Python | gpl-2.0 | 1,117 | 0.008953 | class check_privilege_dbadm():
"""
check_privilege_dbadm:
The DBADM (database administration) role grants the authority to a user to perform
administrative tasks on a specific database. It is recommended that dbadm role be granted
to authorized users only.
"""
# References:
# https://be... | lt = {}
def do_check(self, *results):
output = ''
self.result['level'] = 'GREEN'
for rows in results:
for row in rows:
self.result['level'] = 'YELLOW'
output += 'DBADM granted to %s\n' % (row[0])
if 'GREEN' == self.result['level']:
... | ' + self.TITLE)
|
ChugR/qpid-dispatch | tests/router_policy_test.py | Python | apache-2.0 | 17,771 | 0.003039 | #
# 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... | (aaa, "192.168.1.2", False)
| self.check_hostaddr_match(bbb, "1.1.1.1")
self.check_hostaddr_match(bbb, "1.1.1.254")
self.check_hostaddr_match(bbb, "1.1.1.0", False)
self.check_hostaddr_match(bbb, "1.1.2.0", False)
def test_policy_hostaddr_ipv6(self):
if not is_ipv6_enabled():
self.skipTest("System I... |
earlybackhome/easy-expression | modules/DL/maxSim.py | Python | mit | 4,470 | 0.03119 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2017-05-28 10:13:14
# @Author : Sizheree (sizheree.github.io)
# @Link :
# @Version : $1.0$
import logging
import time
import numpy as np
import matplotlib.pyplot as plt
# print(__package__, __file__)
logging.basicConfig(level=logging.INFO)
log = logging.... | ba.posseg as pseg
#绝对路径
def pp(ppath):
import os
return os.path.join(os.getcwd() | , os.path.dirname(__file__), ppath)
#单个句子类
class Senten2vec():
def __init__(self, sentence):
log.debug('split: %s', sentence.split("#"))
self.sentence, self.picture = sentence.split('#')
self.picture = self.picture.strip()
self.sentence_word = []
self.sentence_vec = []
def __str__(self):
return "sentenc... |
mathLab/RBniCS | rbnics/backends/basic/wrapping/petsc_ksp_solver.py | Python | lgpl-3.0 | 1,503 | 0.001996 | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from petsc4py import PETSc
def BasicPETScKSPSolver(backend, wrapping):
class _BasicPETScKSPSolver(object):
def __init__(self, lhs, solution, rhs):
self.lhs = lhs
... | , "setFactorSolverType"): # PETSc >= 3.9
self.ksp.getPC().setFactorSolverType(value)
else:
self.ksp.getPC().setFactorSolverPackage(value)
else:
raise ValueError("Invalid paramater passed to PETSc KSP object.")
... | ad in additional options from the command line
self.ksp.setFromOptions()
def solve(self):
self.ksp.setOperators(wrapping.to_petsc4py(self.lhs))
self.ksp.solve(wrapping.to_petsc4py(self.rhs), wrapping.to_petsc4py(self.solution))
return _BasicPETScKSPSolver
|
slozier/ironpython2 | Tests/test_traceback.py | Python | apache-2.0 | 13,122 | 0.015242 | # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
# !!! DO NOT MOVE OR CHANGE THE FOLLOWING LINES
def _raise_exception():
raise Exception()
_retb = (18, 0, ... | assert_traceback([(LINE240 + 2, 0, FILE, 'test_throw_and_throw'), _retb])
try:
_raise_exception()
except:
assert_traceback( | [(LINE240 + 6, 0, FILE, 'test_throw_and_throw'), _retb])
LINE250 = 233
def test_throw_in_another_file():
if is_cli: _f_file = path_combine(get_full_dir_name(testpath.public_testdir), 'foo.py')
else: _f_file = os.getcwd() + '\\foo.py'
write_to_file(_f_file, '''
def another_raise():
raise Exception()
'''... |
aristanetworks/arista-ovs-quantum | quantum/tests/unit/test_common_utils.py | Python | apache-2.0 | 2,319 | 0 | # Copyright (c) 2012 OpenStack, 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 o... | ParseMappings(unittest.TestCase):
def parse(self, mapping_list, unique_values=True):
return utils.parse_mappings(mapping_list, unique_values)
def test_parse_mapping | s_fails_for_missing_separator(self):
with self.assertRaises(ValueError):
self.parse(['key'])
def test_parse_mappings_fails_for_missing_key(self):
with self.assertRaises(ValueError):
self.parse([':val'])
def test_parse_mappings_fails_for_missing_value(self):
with... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/aptdaemon/crash.py | Python | gpl-3.0 | 45 | 0.022222 | ../../../../share/pysh | ared/ap | tdaemon/crash.py |
EKT1/valence | valence/valencecolor.py | Python | gpl-3.0 | 9,621 | 0.001663 | # -*- coding: utf-8 -*-
from __future__ import print_function
import codecs
import re
from . import bayes
import pkg_resources
try:
_
except NameError:
def _(s): return s
hybrid = 1
htmlStart = """
<html><head>
<style>
</style>
</head>
<body>
"""
htmlEnd = """
</body>
</html>
"""
paraOpen = '<div class="'
... |
return (rtn, total, stats, bayesStats)
def textValence(all, para):
"""Calculate whole text emotion from paragraphs words counts.
where para = [neutral, positive, negative, mixed] total number of words in each type of paragraph.
and "all" is the total number of words in the text.
"""
cou... | al = pos = 0 # max and its position
for i, val in enumerate(para):
if val > 0:
count = count + 1
if val > maxVal:
maxVal = val
pos = i
valence = _('mostly mixed')
if count == 1:
valence = [_('only neutral'), _('only positive'), _('only negative'... |
plumdog/pysql_browser | main.py | Python | gpl-3.0 | 243 | 0.004115 | from PySide import QtCore, QtGui
from pysql_browser import MainWindow
import sys
def main():
| app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
mai | n()
|
business-factory/gold-digger | tests/data_providers/test_yahoo.py | Python | apache-2.0 | 5,423 | 0.000553 | from datetime import date
from decimal import Decimal
from requests import Response
YAHOO_RESPONSE = b"""
{
"spark": {
"result": [
{
"symbol": "USDEUR=X",
"response": [
{
"meta": {
"currency": "EUR",
"symbol": "USDEUR=X",
"exc... |
"regular": {
"timezone": "GMT",
"start": 1541980800,
"end": 1542067140,
"gmtoffset": 0
},
"post": {
"timezone": "GMT",
"start": 1542067140,
"end"... | "1d",
"5d",
"1mo",
"3mo",
"6mo",
"1y",
"2y",
"5y",
"10y",
"ytd",
"max"
]
},
"timestamp": [
1542021900... |
fermat618/pida | tests/core/test_events.py | Python | gpl-2.0 | 1,326 | 0.003017 | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
from pida.core.events import EventsConfig
import unittest
class MockCallback(object):
def __init__(self):
self.calls = []
def __call__(self, **kw):
self.calls.append(kw)
class MockService(object):
"""used... | f.assertEqual(len(self.c.calls), 1)
self.assertEqual(self.c.calls[0], {})
def test_emit_event_multiple(self):
self.e.emit('initial')
self.e.emit('initial')
self.e.emit('initial')
self.assertEqual(len(self.c.calls), 3)
def test_emit_event_with_argument(self):
sel... | self.assertEqual(self.c.calls[0], {'parameter': 1})
def test_emit_event_bad_argument(self):
try:
self.e.emit('initial', 1)
raise AssertionError('TypeError not raised')
except TypeError:
pass
|
netvl/contrib-python-qubell-client | qubell/api/provider/__init__.py | Python | apache-2.0 | 4,941 | 0.004048 | from functools import wraps
import inspect
import logging as log
import requests
import time
import sys
from qubell.api.private.exceptions import ApiError, api_http_code_errors
log.getLogger("requests.packages.urllib3.connectionpool").setLevel(log.ERROR)
_routes_stat = {}
def route(route_str): # decorator param
... | args)
return wrapper
def log_routes_stat():
nice_stat = [" count: {0:<4} min: {1:<6} avg: {2:<6} max: {3:<6} {4}".format(stat["count"], stat["min"], | stat["avg"], stat["max"], r) for r, stat in _routes_stat.items()]
log.info("Route Statistic\n{0}".format("\n".join(nice_stat))) |
sirrice/sirrice.github.io | genpubs.py | Python | mit | 5,788 | 0.016759 | import click
import yaml
import sys
mine = """Daniel Alabi
Fotis Psallidas
Zachary Huang
Lana Ramjit
Lampros Flokas
Gabriel Ryan
Hamed Nilforoshan
Haneen Mohammed
Qianrui Zhang
Viraj Rai
Jacob Fisher
Haoci Zhang
Ian Yiran Huang
Lauren Arnett
Robert Netzorg
James Sands
Kevin Lin
Rahul Khanna
Thibault Sellam
Yiliang Sh... | except Exception as e:
print(e)
return
data = filter(get_year, data)
data.sort(key=get_year, reverse=True)
# TODO: print future, full, then short papers.
i = 0
if bibtex:
for pub in data:
try:
print print_bibtex(pub, i)
i += 1
except:
print >>sys.stder... | return
prev_year = None
i = 0
if a:
print "\n\n"
print "&\\section{In Progress or In Review}\\\\"
for pub in filter(lambda pub: pub.get("future"), data):
year = get_year(pub)
print print_latex(pub, i+1, prev_year != year)
prev_year = year
i += 1
print "\n\n"
print "&\\... |
sebdelsol/pyload | module/plugins/hoster/SendmywayCom.py | Python | gpl-3.0 | 619 | 0.008078 | # -*- coding: utf-8 -*-
from module.plugins.internal.XFSHoster import XFSHoster, create_getInfo
class SendmywayCom(XFSHoster):
__name__ = "SendmywayCom"
__type__ = "hoster"
__version__ = "0.04"
__pattern__ = r'http://(?:www\.)?sendmyway\.com/\w{12}'
__description__ = """SendMyWay hoster p... | __authors__ = [("zoidberg", "zo | idberg@mujmail.cz")]
HOSTER_DOMAIN = "sendmyway.com"
NAME_PATTERN = r'<p class="file-name" ><.*?>\s*(?P<N>.+)'
SIZE_PATTERN = r'<small>\((?P<S>\d+) bytes\)</small>'
getInfo = create_getInfo(SendmywayCom)
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractYuzukiteaWordpressCom.py | Python | bsd-3-clause | 558 | 0.03405 |
def extractYuzukiteaWordpressCom(item):
'''
Parser for 'yuzukitea.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
ret | urn None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, c | hp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
Orange-OpenSource/cf-php-build-pack | vendor/node-semver/semver/tests/test_strict_vs_loose_version_number.py | Python | apache-2.0 | 1,134 | 0 | # -*- coding:utf-8 -*-
import pytest
# node-semver/test/index.js
# import logging
# logging.basicConfig(level=logging.DEBUG, format="%(message)s")
cands = [
['=1.2.3', '1.2.3'],
['01.02.03', '1.2.3'],
['1.2.3-beta.01', '1.2.3-beta.1'],
| [' =1.2.3', '1.2.3'],
['1.2.3foo', '1.2.3-foo']
]
@pytest.mark.parametrize("loose, strict", cands)
def test_it(loose, strict):
import pytest
from semver import make_semver, eq
with pytest.raises(ValueError):
make_semver(loose, False)
lv = make_semver(loose, True)
assert lv.version... | with pytest.raises(ValueError):
make_semver(strict, False).compare(loose)
cands = [
['>=01.02.03', '>=1.2.3'],
['~1.02.03beta', '>=1.2.3-beta <1.3.0-0']
]
@pytest.mark.parametrize("loose, comps", cands)
def test_it_for_range(loose, comps):
import pytest
from semver import make_range
... |
TheGU/deep_trading_notebook | omstang_lib/market_data.py | Python | mit | 3,626 | 0.002758 | import os, random
import numpy as np
import pandas as pd
def pctrank(data):
return pd.Series(data).rank(pct=True).iloc[-1]
def get_csv_file(days=252, datadir="", filename=""):
try_random = 10
name = None
data = None
while try_random:
if not datadir or not os.path.isdir(datadir):
... | v_info(self):
print('From : ', self.data.iloc[self.idx].name)
print('To : ', self.data.iloc[self.idx + self.days].name)
print(self.data.iloc[self.idx:self.idx + self.days])
def reset(self):
# we want conti | guous data
self.idx = np.random.randint(low=0, high=len(self.data.index) - self.days)
self.step = 0
def _step(self):
obs = self.data.iloc[self.idx].as_matrix()
self.idx += 1
self.step += 1
done = self.step >= self.days
return obs, done
|
hujiajie/chromium-crosswalk | chrome/common/extensions/docs/server2/patch_servlet_test.py | Python | bsd-3-clause | 6,593 | 0.006825 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from HTMLParser import HTMLParser
import unittest
from fake_fetchers import ConfigureFakeFetchers
from host_file_system_provider impor... | that get rewritten to
"_patch/issue".
'''
patched_response = self._RenderWithPatch(path, issue)
unpatched_response = self._RenderWithoutPatch(path)
for header in ('Cache-Control', 'ETag'):
patched_response.headers.pop(header, None)
unp | atched_response.headers.pop(header, None)
unpatched_content = unpatched_response.content.ToString()
# Check that all links in the patched content are qualified with
# the patch URL, then strip them out for checking (in)equality.
patched_content = patched_response.content.ToString()
patch_servlet_pa... |
ccqpein/Arithmetic-Exercises | Sum-of-Square-Numbers/SoSN.py | Python | apache-2.0 | 531 | 0.001883 | import math
class Solution:
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
if c == 0:
return True
elif c < 0:
| return False
for i in range(0, int(math.sqrt(c))+1):
tempI = i ** 2
try:
tempRest = math.sqrt(c-tempI)
| except:
continue
if int(tempRest) == tempRest:
return True
return False
a = Solution()
a.judgeSquareSum(5)
|
kull2222/DjangoSourceControl | dsc/djangosourcecontrol/migrations/0001_initial.py | Python | gpl-3.0 | 2,755 | 0.00363 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-02 05:05
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depe... | ow, verbose_name='date created')),
('public', models.BooleanField(default=True)),
| ('project', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='projectfiles', to='djangosourcecontrol.Project')),
],
),
migrations.CreateModel(
name='ProjectFileVersion',
fields=[
('id', models... |
gaufung/LMDI | Figures/config.py | Python | mit | 119 | 0.008403 | # -*- coding:utf | 8 -*-
FILE_NAME='data.xlsx'
SHEET_INDEX = 0
ROW_START = 1
ROW_END = 30
COLUMN_START = 1
COLUMN_END = | 4
|
python-openxml/python-docx | setup.py | Python | mit | 2,381 | 0.00042 | #!/usr/bin/env python
import os
import re
from setuptools import | find_packages, setup
def text_of(relpath):
"""
Return string containing the contents of the file at *relpath* relative to
this file.
"""
thisdir = os.path.dirname(__file__)
file_path = os.path.join(thisdir, os.path.normpath(relpath))
with open(file_path) as f:
text = f.read()
... | x.__version__ without importing the package
# (and thus attempting to import packages it depends on that may not be
# installed yet)
version = re.search(r'__version__ = "([^"]+)"', text_of("docx/__init__.py")).group(1)
NAME = "python-docx"
VERSION = version
DESCRIPTION = "Create and update Microsoft Word .docx files.... |
scriptotek/mc2skos | mc2skos/error.py | Python | unlicense | 658 | 0.00304 |
class InvalidRecordError(RuntimeError):
def __init__(self, msg, control_number=None): |
super(InvalidRecordError, self).__init__(msg)
self.control_number = control_number
class UnknownSchemeError(InvalidRecordError):
def __init__(self, code=None, **kwargs):
if code is None:
msg = 'Could not find class | ification scheme or subject vocabulary code.'
else:
msg = 'Cannot generate URIs for unknown classification scheme or subject vocabulary "%s".' % code
super(UnknownSchemeError, self).__init__(msg)
self.code = code
self.control_number = kwargs.get('control_number')
|
tiradoe/fourteeners-updated | fourteeners/apps/mountains/tests.py | Python | mit | 2,841 | 0.028159 | from datetime import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from apps.mountains.models import Mountain, Climb
class ClimbTest(TestCase):
def setUp(self):
User.objects.create(
username = "test_user",
email = "test@testemail.com",
... | X"),
finish_time = now.strftime("%X"),
total_distance = 5,
notes = "Climbed a mountain"
)
except:
test_climb = None
self.assertEquals(test_climb, None, "Climb should not save without missing field")
def test_save_with_invalid... | now = datetime.now()
try:
test_climb = Climb.objects.create(
climber = User.objects.get(username="test_user"),
mountain = Mountain.objects.get(name="Test Mountain"),
summit_date = now.isoformat(),
finish_date = now.strftime('%Y-%m-%d')... |
pbrod/numpy | numpy/typing/tests/data/pass/ufuncs.py | Python | bsd-3-clause | 447 | 0.002237 | import numpy as np
np.sin(1)
np.sin([1, 2, 3])
np.sin | (1, out=np.empty(1))
np.matmul(np.ones((2, 2, 2)), np.ones((2, 2, 2)), axes=[(0, 1), (0, 1), (0, 1)])
np.sin(1, signature="D->D")
np.sin(1, extobj=[16, 1, lambda: None])
# NOTE: `np.generic` subclasses are not guaranteed to support addition;
# re-enable this we can infer the exact return type of `np.sin(...)`.
#
# np.s... | p.sin.__name__
np.abs(np.array([1]))
|
dinhoabreu/yowsup | yowsup/layers/auth/protocolentities/test_auth.py | Python | gpl-3.0 | 439 | 0.009112 | from yowsup.layers.auth.protocolentities import AuthProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
|
class AuthProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = AuthProtocolEntity
self.node = ProtocolTreeNode("auth", {"user": "testuser", "mechanism": "WAUTH-2", "passive" | : "false"}) |
rackerlabs/Tempo | tempo/api.py | Python | apache-2.0 | 5,443 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Rackspace
# 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/licen... | :
app.logger.critical(error_msg)
return res
def _new_response(body):
"""Creates a Flask response and sets the content type"""
res = app.make_response(flask.json.dumps(body))
res.content_encoding = 'application/json'
return res
def _create_or_update_task(id, body_dict):
"""Verifies th... | ce']
for key in keys:
if key not in body_dict:
raise common_exception.MissingArgumentError(
"Missing key '%s' in body" % key)
# Validate values
cronspec.parse(body_dict['recurrence'])
values = {
'deleted': False,
'uuid': id,
'instance_uui... |
wnormandin/bftest_cli | setup.py | Python | mit | 762 | 0.001312 | #!/usr/bin/python2.7
from setuptools import setup, find_packages
setup(
name='bftest_cli',
version='0.1a',
description='A wrapper to manage docker instances',
url='https://github.com/wnormandin/bftest_cli',
autho | r='wnormandin',
author_email='bill@pokeybill.us',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python 2.7'
... | nstall_requires=['docker','click'],
py_modules=['bftest_cli'],
entry_points="""
[console_scripts]
dockcli=cli.dockcli:default
""",
)
|
feend78/evennia | evennia/game_template/commands/command.py | Python | bsd-3-clause | 7,718 | 0.001296 | """
Commands
Commands describe the input the account can do to the game.
"""
from evennia import Command as BaseCommand
# from evennia import default_cmds
class Command(BaseCommand):
"""
Inherit from this if you want to create your own command styles
from scratch. Note that Evennia's default commands ... | is
# (this allows you to know which alias was used,
# for example)
# self.args - the raw input; everything following self.cmdstring.
# self.cmdset - the cmdset from which this command was picked. Not
# often used (us... | and was defined. It is often
# the same as self.caller.
#
# A MUX command has the following possible syntax:
#
# name[ with several words][/switch[/switch..]] arg1[,arg2,...] [[=|,] arg[,..]]
#
# The 'name[ with several words]' part is already dealt with by the
# ... |
PyIran/website | project/apps/user/models.py | Python | gpl-3.0 | 3,333 | 0.029703 | from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from project.database import Base
from project.database import db_session
from sqlalchemy.orm import relationship
from sqlalchemy_utils import EmailType
from flask.ext.babel import lazy_gettext as _
# FIXME: move to extensions
from flask.ext... | n = Column(String(50), info={'label': _('description')})
def __init__(self, **kwargs):
super(Roles, self).__init__(**kwargs)
def __repr__(self):
return self.role_name
class User_Role(Base):
__tablename__ = 'user_role'
id = Column(Integer, pr | imary_key=True)
role = Column(Integer,ForeignKey('role.id'), info={'label': _('role')})
user = Column(Integer,ForeignKey('profile.id'), info={'label': _('user')})
def __init__(self, **kwargs):
super(User_Role, self).__init__(**kwargs)
def __repr__(self):
return self.role
class Profile(Base):
__tablename_... |
pydanny/staticserve | setup.py | Python | gpl-2.0 | 1,823 | 0.001646 | #!/usr/bin/env python
import os
import sys
import static
version = static.__version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_requirements(filename):
return list([x.strip() for x in open(filename).readlines()])
if sys.argv[-1] == 'test':
requ... | )
readme = open('README.rst').read()
history = open('HISTORY.rst').read()
setup(
name='staticserve',
version=version,
description='A simple WSGI way to serve static (or mixed) content.',
long_description=readme + '\n\n' + history,
author='Daniel Greenfeld',
author_email='pydanny@gmail.com',
... | zip_safe=False,
keywords='wsgi web http static content webapps',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Natu... |
fqez/JdeRobot | src/libs/comm_py/tests/testBumper.py | Python | gpl-3.0 | 501 | 0.007984 | #!/usr/bin/env python2
import config
impo | rt comm
import sys
import time
import signal
from jderobotTypes import BumperData
if __name__ == '__main__':
cfg = config.load(sys.argv[1])
jdrc= comm.init(cfg, "Test")
client = jdrc.getBumperClient("Test.Bumper")
while True:
| #print("client1", end=":")
bumper = client.getBumperData()
print bumper
if bumper.state == 1:
print bumper
break
time.sleep(1)
jdrc.destroy() |
EinfInPython-SS2017-LaJuTo/AbschlussProjekt | src/lib/Vector.py | Python | mit | 5,995 | 0.011676 | """
The MIT License (MIT)
Copyright (c) 2015 Mat Leonard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge,... | otates the vector.
"""
if len(args)==1 and type(args[0]) == type(1) or type(args[0]) == type(1.):
# So, if rotate is passed an int or a float...
if len(self) != 2:
raise ValueError("Rotation axis not defined for greater than 2D vector")
return self._ro... | matrix) or not len(matrix)==len(self):
raise ValueError("Rotation matrix must be square and same dimensions as vector")
return self.matrix_mult(matrix)
def _rotate2D(self, theta):
""" Rotate this vector by theta in degrees.
Returns a new vector.... |
KoenHoogendoorn1994/rosalind | lgis.py | Python | gpl-3.0 | 1,246 | 0.001605 | #!/usr/bin/env python
# encoding: utf-8
"""
rosalind exercises
"""
# Imports
from __future__ import division
import os
from sys import argv
import baselib as b
import math
def main(infile):
# vars
lines = []
population = []
desc = []
asc = ""
# processing
for li | ne in b.read(infile):
lines.append(line.strip())
popsize = lines[0]
for elem in lines[1:]:
for ch | aracter in elem.replace(" ", ""):
population.append(int(character))
print(population)
p = [0] * len(population)
m = [0] * (len(population)+1)
l = 0
for i in range(0, len(population)-1):
lo = 1
hi = l
while lo <= hi:
mid = int(math.ceil((lo+hi)/2))
... |
FCP-INDI/nipype | nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py | Python | bsd-3-clause | 3,081 | 0.027264 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..tracking import SphericallyDeconvolutedStreamlineTrack
def test_SphericallyDeconvolutedStreamlineTrack_inputs():
input_map = dict(args=dict(argstr='%s',
),
cutoff_value=dict(argstr='-cutoff %s',
units='NA... | =dict(argstr= | '-minlength %s',
units='mm',
),
no_mask_interpolation=dict(argstr='-nomaskinterp',
),
out_file=dict(argstr='%s',
name_source=['in_file'],
name_template='%s_tracked.tck',
output_name='tracked',
position=-1,
),
seed_file=dict(argstr='-seed %s',
xor=['seed_file', 'seed_spec'... |
xyuanmu/XX-Net | code/default/launcher/start.py | Python | bsd-2-clause | 5,393 | 0.003338 | #!/usr/bin/env python3
# coding:utf-8
import os
import sys
import time
import traceback
from datetime import datetime
import atexit
# reduce resource request for threading
# for OpenWrt
import threading
try:
threading.stack_size(128 * 1024)
except:
pass
try:
import tracemalloc
tracemalloc.start(10)
e... | (etype, value, tb))
print(("uncaught Exception:\n" + exc_info))
with open(os.path.join(data_launcher_path, "error.log"), "a") as fd:
now = datetime.now()
time_str = now.strftime("%b %d %H:%M:%S.%f")[:19]
fd.write("%s type:%s value=%s traceback:%s" % (time_str, etype, value, exc_info))
... | ception, type=%s value=%s traceback:%s", etype, value, exc_info)
# sys.exit(1)
sys.excepthook = uncaughtExceptionHandler
has_desktop = True
def unload(module):
for m in list(sys.modules.keys()):
if m == module or m.startswith(module + "."):
del sys.modules[m]
for p in list(sys.pat... |
pgk/simple-midi-parser | setup.py | Python | mit | 613 | 0.014682 | import os
from setuptools import setup, find_packages
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as file_handle:
return file_handle.read()
setup(
name = "simple_ | midi_parser",
version = "0.1.0",
url="https://pypi.python.org/pypi/simple_midi_parser",
packages = find_packages(),
author="Pan | os Kountanis",
author_email="panosktn@gmail.com",
description="Simple MIDI file parser",
long_description=read("README.rst"),
install_requires = [
'six>=1.8.0'
],
setup_requires= [
'nose>=1.0',
'mock'
]
)
|
EmreAtes/spack | var/spack/repos/builtin/packages/util-macros/package.py | Python | lgpl-2.1 | 1,752 | 0.000571 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | s needed to generate new versions
of their configure scripts with autoconf."""
homepage = "http://cgit.freedesktop.org/xorg/util/macros/"
url = "https://www.x.org/archive/individual/util/util-macros-1.19.1.tar.bz2"
version('1.19.1', '6e76e546a4e580f15cebaf8019ef1625')
version('1.19.0', '1cf9 | 84125e75f8204938d998a8b6c1e1')
|
hnakamur/saklient.python | saklient/errors/httprequestentitytoolargeexception.py | Python | mit | 573 | 0.010772 | # -*- coding:utf-8 -*-
from .httpexception import | HttpException
import saklient
# module saklient.errors.httprequestentitytoolargeexception
class HttpRequestEntityTooLargeException(HttpException):
## HTTPエラー。Request Entity Too Large.
## @param {int} status
# @param {str} code=None
# @param {str} message=""
def __init__(self, status, code=No... | ode, "HTTPエラー。Request Entity Too Large." if message is None or message == "" else message)
|
oshtaier/robottelo | robottelo/ui/template.py | Python | gpl-3.0 | 5,867 | 0 | # -*- encoding: utf-8 -*-
# vim: ts=4 sw=4 expandtab ai
"""
Implements Template UI
"""
from robottelo.ui.base import Base, UINoSuchElementError
from robottelo.ui.locators import locators, common_locators, tab_locators
from robottelo.ui.navigator import Navigator
from selenium.webdriver.support.select import Select
fr... | self.browser).go_to_provisioning_templates()
self.delete_entity(name, really, locators["provision.template_select"],
locators["provision.template_delete"],
| locators["provision.template_dropdown"])
|
nils-werner/SimpleCV | SimpleCV/MachineLearning/KNNClassifier.py | Python | bsd-3-clause | 15,965 | 0.012527 | from SimpleCV.base import *
from SimpleCV.ImageClass import Image, ImageSet
from SimpleCV.DrawingLayer import *
from SimpleCV.Features import FeatureExtractorBase
"""
This class is encapsulates almost everything needed to train, test, and deploy a
multiclass k-nearest neighbors image classifier. Training data should
be... | or discrete variables
'Maximal': orange.ExamplesDistance_Maximal(),
| 'Manhattan':orange.ExamplesDistanceConstructor_Manhattan(),
'Euclidean':orange.ExamplesDistanceConstructor_Euclidean(),
'Normalized':None
}
self.mFeatureExtractors = featureExtractors
if( dist is not None ):
self.mDistType = self.mDistDict[dist];
... |
hadmagic/Aidez-moi | ticket/views/home.py | Python | mit | 2,583 | 0.000774 | __author__ = 'had'
# The MIT License (MIT)
# Copyright (c) [2015] [Houtmann Hadrien]
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the Aidez-moi), to deal
# in the Software without restriction, including without limitation the righ... | 'assign_to',
'category')\
.filter()\
| .order_by('-created')[:10:1]
ticket_incomplete = Tickets.objects.filter(complete=0).count()
else:
ticket_list = Tickets.objects.filter(
create_by=request.user).order_by('-created')[:10:1]
ticket_incomplete = Tickets.objects.filter(
create_... |
mganeva/mantid | scripts/SANS/sans/state/convert_to_q.py | Python | gpl-3.0 | 10,526 | 0.004085 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
# pylint: disable=too-few-public-methods
"""... | "q_max": self.q_max})
is_invalid.update(entry)
if self.q_1d_rebin_string is not None:
if s | elf.q_1d_rebin_string == "":
entry = validation_message("Q rebin string does not seem to be valid.",
"Make sure to provide a valid rebin string",
{"q_1d_rebin_string": self.q_1d_rebin_string})
is_invali... |
postlund/home-assistant | homeassistant/auth/__init__.py | Python | apache-2.0 | 17,515 | 0.000914 | """Provide an authentication layer for Home Assistant."""
import asyncio
from collections import OrderedDict
from datetime import timedelta
import logging
from typing import Any, Dict, List, Optional, Tuple, cast
import jwt
from homeassistant import data_entry_flow
from homeassistant.auth.const import ACCESS_TOKEN_EX... | data: Optional[Dict[str, Any]] = None,
) -> data_entry_flow.FlowHandler:
"""Create a login flow."""
auth_provider = self.auth_manager.get_auth_provider(*handler_key)
if not auth_provider:
raise KeyError(f"Unknown auth provider {handler_key}")
return await auth_provider... | str, Any]
) -> Dict[str, Any]:
"""Return a user as result of login flow."""
flow = cast(LoginFlow, flow)
if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
return result
# we got final result
if isinstance(result["data"], models.User):
re... |
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/script.xbmc.subtitles/resources/lib/services/Subs4Free/service.py | Python | gpl-2.0 | 13,139 | 0.015526 | # -*- coding: UTF-8 -*-
import os, sys, re, xbmc, xbmcgui, string, time, urllib, urllib2
import mechanize
from utilities import log
_ = sys.modules[ "__main__" ].__language__
movie_url = "http://www.small-industry.com"
tvshow_url = "http://www.subs4series.com"
debug_pretext = "subs4free"
def get_url(url,referer=None)... | # Movie not in Library
searchstring = "%s (%#02d%#02d)" % (tvshow, int(season), int(episode))
elif len(tvshow) > 0: # TVShow
searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
content = 2
else:
searchstring = title
log( __nam | e__ ,"%s Search string = %s" % (debug_pretext, searchstring))
if content == 1:
get_movie_subtitles_list(searchstring, "el", "Greek", subtitles_list)
else:
get_tvshow_subtitles_list(searchstring, "el", "Greek", subtitles_list)
return subtitles_list, "", msg #standard output
def download_subt... |
hypernicon/pyec | pyec/tests/test_algebra_nm.py | Python | mit | 8,955 | 0.00268 | """
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... | cate_convolve():
DET = DE >> DE
assert issubclass(DET, Convolution)
det = DET(populationSize=19, space=space)
assert len(det.subs) == 2
assert isinstance(det.subs[0], DE)
assert isinstance(det.subs[1], TrajectoryTruncation)
assert det.subs[1].delay == 1
assert isinstance(det.subs[1].opt,... | pleHistory)
assert isinstance(det.subs[0].history, NelderMeadHistory)
assert isinstance(det.subs[1].history, DelayedHistory)
assert isinstance(det.subs[1].opt.history, NelderMeadHistory)
assert det.history.evals == det.subs[0].history.evals
assert det.subs[1].history.evals == det.history.evals - 1
... |
jniediek/mne-python | mne/viz/tests/test_misc.py | Python | bsd-3-clause | 5,345 | 0.000187 | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Cathy Nangini <cnangini@gmail.com>
# Mainak Jas <mainak@neuro.hut.fi>
#... | 'sample_audvis_trunc_set1.dip')
base_ | dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_fname = op.join(base_dir, 'test-eve.fif')
def _get_raw():
"""Get raw data."""
return read_raw_fif(raw_fname, preload=True, add_eeg_ref=False)... |
nakagami/reportlab | src/reportlab/platypus/frames.py | Python | bsd-3-clause | 9,389 | 0.009586 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/platypus/frames.py
__version__=''' $Id: frames.py 3959 2012-09-27 14:39:39Z robin $ '''
__doc__="""A frame is a container for content on a page.
"""
... | raIndent | = 0.0
def _getAvailableWidth(self):
return self._aW - self._leftExtraIndent - self._rightExtraIndent
def _add(self, flowable, canv, trySplit=0):
""" Draws the flowable at the current position.
Returns 1 if successful, 0 if it would not fit.
Raises a LayoutError if the object is... |
matthagy/physmath | physmath/test/test_sigfig.py | Python | apache-2.0 | 9,318 | 0.005688 |
import operator
from decimal import Decimal
from physmath.sigfig import SigFig
def parse_lines(data, n=None, split=lambda line: line.split()):
for line in data.split('\n'):
line = line.split('#',1)[0]
line = line.strip()
if line:
parts = split(line)
if n is not Non... | xpr)
assert str(sf) == canonical_str
assert sf == eq
assert sf <= eq
assert sf >= eq
assert eq == sf
assert eq <= sf
assert eq >= sf
string_checks = [
[ '1', '1', 1],
[ '1', '1', 1],
[ '10', '10', 10] | ,
[ '10', '10', 10],
[ '10', '10', 10],
[ '-3', '-3', -3],
[ '1.0', '1.0', 1],
[ '1.4', '1.4', Decimal('1.4')],
[ '-2.7', '-2.7', Decimal('-2.7')],
[ '-18', '-18', -18],
[ '120'... |
Ethernyan/EbookBot | twitter.py | Python | mit | 3,814 | 0.011536 | import logging
import time
import json
import oauth2 as oauth
import httplib2
import urllib
import twitter_settings
class TwitterError(Exception):
def __init__(self, status_code, content):
self.status_code = status_code
self.content = content
def __str__(self):
return "Twitter retur... | post_tweet(text, replyID):
if replyID == None:
urlArgs = urllib.urlencode([("status", unicode(tex | t).encode('utf-8'))])
else:
urlArgs = urllib.urlencode([("status", unicode(text).encode('utf-8')), ("in_reply_to_status_id", replyID)])
client = oauth.Client(twitter_settings.consumer, twitter_settings.token)
resp, content = client.request("https://api.twitter.com/1.1/statuses/update.json", "POST",... |
sighingnow/sel4-tutorials | tests/tutorial-tests.py | Python | bsd-2-clause | 6,071 | 0.002635 | #!/usr/bin/env python
#
# Copyright 2016, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
# Builds and runs all tutorial solutions, comparing output with expected... | ubprocess.Popen(['make', 'mrproper'], cwd=TOP_LEVEL_DIR)
make_mrproper.wait()
# run the test, storting output in a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=True)
command = '%s %s' % (arch_test_script(arch), | app)
logging.info("Running command: %s" % command)
test = pexpect.spawn(command, cwd=TOP_LEVEL_DIR)
test.logfile = temp_file
expect_strings = [completion_text] + FAILURE_TEXTS
result = test.expect(expect_strings, timeout=timeout)
# result is the index in the completion text list corresponding t... |
gatoatigrado/plcd | setup.py | Python | apache-2.0 | 1,251 | 0 | from setuptools import find_packages
from setuptools import setup
setup(
name="plcd",
version="0.1.0",
provides=["plcd"],
author="gatoatigrado",
author_email="gatoatigrado@gmail.com",
url="https://github.com/gatoatigrado/plcd",
description=(
'This is a python library for facilitati... | ckages=find_packages(exclude=['tests*']),
entry_points={
'console_scripts': [
'plcd_generate = plcd.generate:main',
],
},
long_description="""Facilitates use of pre-loaded compression dictionaries.
Pre-loaded compression means that you "seed" a compressor with some
sample data, ... | ncode.
This is primarily useful for encoding small messages, which have repeated
information with some sample small messages.
"""
)
|
jdber1/opendrop | opendrop/mvp/typing.py | Python | gpl-3.0 | 1,995 | 0.001004 | # Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com)
# OpenDrop is released under the GNU GPL License. You are free to
# modify and distribute the code, but always under the same license
#
# If you use this software in your research, please cite the following
# journal articles:
#
# J. D. Berry, M. J. ... | or, | Measurement of surface and interfacial tension using
# pendant drop tensiometry. Journal of Colloid and Interface Science 454
# (2015) 226–237. https://doi.org/10.1016/j.jcis.2015.05.012
#
# E. Huang, T. Denning, A. Skoufis, J. Qi, R. R. Dagastine, R. F. Tabor
# and J. D. Berry, OpenDrop: Open-source software for pend... |
evgeni/voltverine | tests/test_logind.py | Python | mit | 2,668 | 0.003373 | import unittest
import sys
import dbusmock
import subprocess
import voltverine.plugins
class TestLogind(dbusmock.DBusTestCase):
@classmethod
def setUpClass(klass):
klass.start_system_bus()
klass.dbus_con = klass.get_dbus(True)
def setUp(self):
self.p_mock = None
def tearDow... | self.assertTrue(action == voltverine.plugins.NOT_OK)
self.assertTrue(info == {'sessions': 1})
def test_no_session(self):
(self.p_mock, obj_logind) = self.spawn_server_template('logind', {}, stdout=subprocess.PIPE)
voltverine_plugin = voltverine.plugins.LogindSessions()
(action, ... | ine_plugin.analyze()
self.assertTrue(action == voltverine.plugins.OK)
self.assertTrue(info == {})
def test_session(self):
(self.p_mock, obj_logind) = self.spawn_server_template('logind', {}, stdout=subprocess.PIPE)
obj_logind.AddSession('c1', 'seat0', 500, 'joe', True)
voltv... |
klickagent/phantomjs | src/qt/qtwebkit/Tools/Scripts/webkitpy/port/driver.py | Python | bsd-3-clause | 25,616 | 0.003162 | # Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | , timeout=False, error='', crashed_process_name='??',
crashed_pid=None, crash_log=None, pid=None):
# FIXME: Args could be renamed to better clarify what they do.
self.text = text
self.image = image # May be empty-string if the test crashes.
self.image_hash = image_hash
... | h = crash
self.crashed_process_name = crashed_process_name
self.crashed_pid = crashed_pid
self.crash_log = crash_log
self.test_time = test_time
self.measurements = measurements
self.timeout = timeout
self.error = error # stderr output
self.pid = pid
... |
christabor/MoAL | MOAL/maths/applied/optimization/memoization.py | Python | apache-2.0 | 2,543 | 0.000393 | # -*- coding: utf-8 -*-
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
if __name__ == '__main__':
from os import getcwd
from os import sys
sys.path.append(getcwd())
from MOAL.helpers.display import Section
from MOAL.helpers.trials import test_speed
from functools import wraps
DEBUG = True if __nam... | is in keys, it attempts to access the
property directly, like a typical lookup table."""
funcname = func.__name__
@wraps(func)
def _inner(*args, **kwargs):
key = (funcname, args)
try:
| key = (funcname, args)
return memoized[key]
except KeyError:
res = func(*args, **kwargs)
memoized[key] = res
return res
return _inner
@test_speed
@memoize
def dolongthing(max_x, max_y):
"""Does a nested loop - running time is O(n^2)
Args:
... |
mpatacchiola/deepgaze | deepgaze/motion_detection.py | Python | mit | 7,320 | 0.00806 | #!/usr/bin/env python
#The MIT License (MIT)
#Copyright (c) 2016 Massimiliano Patacchiola
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ... | lgorithms. The results show the
speed of learning and the accuracy of the model using our update
algorithm over the Grimson et al tracker. When incorporate with
the shadow detection, our method results in far better segmentation
than that of Grimson et al.
"""
def __init__(self, history=10, ... | of the history
@param numberMixtures The maximum number of Gaussian Mixture components allowed.
Each pixel in the scene is modelled by a mixture of K Gaussian distributions.
This value should be a small number from 3 to 5.
@param backgroundRation define a threshold which specifi... |
plediii/coord_util | _coord_math.py | Python | bsd-3-clause | 316 | 0.003165 | """Interface module to expose f2py functions like normal pytho | n module."""
import coord_math_f
for (func_name, func) in coord_math_f.coord_math_mod.__dict__.iteritems():
if func_name != '__doc__':
vars()[func_name] = func
d | el func_name, func # Don't expose these variables to importing modules
|
whiskeyjimbo/tcppingtest | web.py | Python | gpl-3.0 | 1,191 | 0.006717 | #!/usr/bin/python3
import json
import redis
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
from collections import defaultdict
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# initi... | :
decoded = x.decode('utf-8')
name, address, port = decoded.split(':')
hits = local_redis.hget(decoded, 'Hit').decode('utf-8')
misses = local_redis.hget(dec | oded, 'Misses').decode('utf-8')
hostlist[name][address][port] = {'Hits': hits, 'Misses': misses }
return hostlist
hostlist = create_counters()
class SimpleWeb(Resource):
isLeaf = True
def render_GET(self, request):
request.setHeader(b"content-type", b"application/json")
content = u... |
google-research/google-research | ptopk_patch_selection/lib/data.py | Python | apache-2.0 | 11,369 | 0.007389 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | maxval=10,
dtype=tf.int32,
seed=4202)
ds_image = tf. | data.Dataset.from_tensor_slices(images_tensor)
ds_label = tf.data.Dataset.from_tensor_slices(labels_tensor)
ds = tf.data.Dataset.zip({"image": ds_image, "label": ds_label})
train_ds = ds
eval_ds = ds
num_classes = 10
elif dataset == "trafficsigns":
train_ds = trafficsigns.load("train")
ev... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.