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 |
|---|---|---|---|---|---|---|---|---|
pymedusa/Medusa | medusa/media/banner.py | Python | gpl-3.0 | 1,222 | 0 | # coding=utf-8
# This file is part of Medusa.
#
#
# Medusa 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.
#
# Medusa is distributed i... | ense for more details.
#
# You should have received a copy of the GNU General Public License
# along with Medusa. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from medusa import image_cache
from medusa.medi | a.generic import GenericMedia
class ShowBanner(GenericMedia):
"""Get the banner of a show."""
default_media_name = 'banner.png'
@property
def img_type(self):
"""Get the image type (normal or thumbnail)."""
if self.media_format == 'normal':
return image_cache.BANNER
... |
glensc/osquery-python | osquery/extension_client.py | Python | bsd-3-clause | 1,845 | 0.000542 | """This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import... | Keyword arguments:
path -- the path of the extension socket to connect to
uuid -- the additional UUID to use when constructing the socket path
"""
self.path = pa | th
if uuid:
self.path += ".%s" % str(uuid)
sock = TSocket.TSocket(unix_socket=self.path)
self._transport = TTransport.TBufferedTransport(sock)
self._protocol = TBinaryProtocol.TBinaryProtocol(self._transport)
def close(self):
"""Close the extension client connect... |
IEEERobotics/libbot | setup.py | Python | bsd-2-clause | 970 | 0 | import os
from glob import glob
from setuptools import setup, find_packages
# Setup flags and parameters
pkg_name = 'libbot' # top-level package name
# Cache readm | e contents for use as long_description
readme = open('README.md').read()
# Call setup()
setup(
name=pkg_name,
version='0.1',
description='Library of common bot functions',
long_description=re | adme,
url='https://github.com/IEEERobotics/libbot',
author='IEEE Robotics Team',
author_email='group-ieee-robotics@ncsu.edu',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'PyYAML'
],
test_suite=(pkg_name + '.tests'),
platforms='any',
keywords='lib lib... |
erhs-robotics/Robo2013 | board/MainServer.py | Python | bsd-3-clause | 2,312 | 0.009083 | #!/usr/bin/python2
import commands
import BaseHTTPServer
from os import curdir, sep
import sys
sys.path.append('lib')
import struct
import Lock
def pack_data(string):
data = []
utf8 = string.encode('utf-8')
length = len(utf8)
data.append(struct.pack('!H', length))
format = '!' + str(length) + 's'
data.ap... |
Lock.unlockfile("info.json")
data = pack_data(f.read())
s.wfile.write(data[0])
s.wfile.write(data[1])
else:
s.send_response(200)
s.send_header("Content-Type", "application/json")
s.send_header("Access-Contr... | server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print "Server Starting - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print "Server Stopping - %s:%s" % (HOST_NA... |
patricksnape/menpo | menpo/math/test/test_decomposition_base.py | Python | bsd-3-clause | 6,220 | 0.000965 | import numpy as np
from numpy.testing import assert_almost_equal
from menpo.math import eigenvalue_decomposition, pca, ipca
# Positive semi-definite matrix
cov_matrix = np.array([[3, 1], [1, 3]])
# Data values taken from:
# http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf
# Tested values ar... | 0.4794398,
0.39407387,
0.28 | 217662,
0.16535718,
0.24399096,
0.15681507,
],
[
-0.25575629,
0.17561812,
0.58718113,
0.19319469,
-0.29239933,
0.27184299,
-0.5344514,
0.04200527,
0.01146941,
... |
ucfopen/canvasapi | scripts/validate_docstrings.py | Python | mit | 4,981 | 0 | import inspect
import os
import re
import sys
import requests
sys.path.append(os.path.join(sys.path[0], '..'))
import canvasapi # noqa
def validate_method(themethod, quiet=False):
# No docstring means no erroneous docstrings
if not inspect.getdoc(themethod):
return True
# Docstrings without A... | me:
if not quiet:
print((
'{} docstring URL does not contain an endpoint name in link'
' to API documentation'
).format(method_string))
return False
if not endpoint_h2:
if not quiet:
print('{} docstring refers to {} in {}, n... | ))
return False
endpoint_element_re = re.compile(
r'<h3 class=[\"\']endpoint[\"\']>[^<]*<\/h3>'
)
endpoint_search_start_match = endpoint_element_re.search(
html_doc_response.text,
endpoint_h2.end()
)
if not endpoint_search_start_match:
if not quie... |
2ndQuadrant/ansible | lib/ansible/executor/module_common.py | Python | gpl-3.0 | 61,921 | 0.003472 | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either... | ZipInfo to work around zipfile limitation on hosts with
# clocks set to a pre-1980 year (for instance, Raspberry Pi)
| zinfo = zipfile.ZipInfo()
zinfo.filename = 'sitecustomize.py'
zinfo.date_time = ( %(year)i, %(month)i, %(day)i, %(hour)i, %(minute)i, %(second)i)
z.writestr(zinfo, sitecustomize)
z.close()
# Put the zipped up module_utils we got from the controller first in the python path so ... |
colddew/mix-python | crawler/ZQplantImageCrawler.py | Python | mit | 2,848 | 0.00316 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2017-09-08 10:20:46
# Project: zqplant
from pymongo import MongoClient
import os
import sys
import urllib
reload(sys)
sys.setdefaultencoding('utf8')
class ZQplantImageCrawler(object):
def __init__(self):
self.image_path = '/Users/anmy/Downloa... | :
for skip in range(0, 50, 10):
cursor = self.mongo_db['spider_zqplant_image'].find({}).sort('_id').limit(10).skip(skip)
for c in cursor:
if c and c.get('image'):
species_name = c.get('speciesName')
image = c.get('image')
... | age_path + species_name + "/"
if not os.path.exists(dir_path):
os.makedirs(dir_path)
image_path = dir_path + image[image.rfind('/') + 1:]
if not os.path.exists(image_path):
try:
u = u... |
Eksmo/calibre | src/calibre/gui2/store/stores/mobileread/adv_search_builder.py | Python | gpl-3.0 | 3,934 | 0.002796 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
from PyQt4.Qt import (QDialog, QDialogButtonBox)
from calibre.gui2.store.st... | = ''
if phrase:
| ans += '"%s"'%phrase
if all:
ans += (' and ' if ans else '') + all
if none:
ans += (' and not ' if ans else 'not ') + none
if any:
ans += (' or ' if ans else '') + any
return ans
def token(self):
txt = unicode(self.text.text()).strip(... |
anaran/olympia | apps/editors/helpers.py | Python | bsd-3-clause | 31,475 | 0 | import datetime
import commonware.log
import django_tables as tables
import jinja2
from django.conf import settings
from django.template import Context, loader
from django.utils.datastructures import SortedDict
from jingo import register
from tower import ugettext as _, ugettext_lazy as _lazy, ungettext as ngettext
i... | amo.STATUS_NOMINATED: 'nominated',
amo.STATUS_PUBLIC: 'pending',
amo.STATUS_LITE: 'prelim',
| amo.STATUS_LITE_AND_NOMINATED: 'nominated',
amo.STATUS_PENDING: 'pending'}
queue = queue_ids.get(queue_id, 'queue')
if queue:
queues = {
'queue': _('Queue'),
'pending': _('Pending Updates'),
'nominated': _('Full Reviews'),
... |
adrianpaesani/odoo-argentina | portal_sale_l10n_ar_aeroo_sale/__openerp__.py | Python | agpl-3.0 | 1,846 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | ncies': {
},
'data': [
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': True,
'application': False,
}
# vim:exp | andtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
lmazuel/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/managedapplications/operations/__init__.py | Python | mit | 700 | 0.001429 | # 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) A | utoRest Code Generator.
# Changes ma | y cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .applications_operations import ApplicationsOperations
from .application_definitions_operations import ApplicationDefinitionsOperations
__all__ = [
'Applicati... |
knuu/competitive-programming | atcoder/abc/abc140_c.py | Python | mit | 163 | 0 | N = int(input( | ))
B = [int(x) for x in | input().split()]
A = [10**5] * N
for i, b in enumerate(B):
A[i] = min(A[i], b)
A[i+1] = min(A[i+1], b)
print(sum(A))
|
biokit/biokit | test/rtools/test_package.py | Python | bsd-2-clause | 1,053 | 0.009497 | from biokit.rtools import package
import pytest
try:
import create_dummy_packa | ge as dun
except:
from . import create_dummy_package as dun
def test_install_packages():
d = dun.CreateDummy()
d()
package.install_package('./dummy/dummytest_1.0.0.tar.gz', | verbose=True)
d._clean()
def test_install_packages():
package.install_package("truncnorm")
def test_get_r_version():
package.get_R_version()
def test_pm():
pm = package.RPackageManager()
pm.packages
pm.installed
pm.available
pm.get_package_version('base')
try:
pm.g... |
unikmhz/npui | netprofile/netprofile/common/magic.py | Python | agpl-3.0 | 7,229 | 0.00083 | #!/usr/bin/env python
'''
Python bindings for libmagic
'''
import ctypes
from ctypes import *
from ctypes.util import find_library
def _init():
"""
Loads the shared library through ctypes and returns a library
L{ctypes.CDLL} instance
"""
dll = None
lib = find_library('magic') or find_library... | = [c_int]
_close = _libraries['magic'].magic_close
_close.restype = None
_close.argtypes = [magic_t]
_file = _libraries['magic'].magic_file
_file.restype = c_char_p
_file.argtypes = [ | magic_t, c_char_p]
_descriptor = _libraries['magic'].magic_descriptor
_descriptor.restype = c_char_p
_descriptor.argtypes = [magic_t, c_int]
_buffer = _libraries['magic'].magic_buffer
_buffer.restype = c_char_p
_buffer.argtypes = [magic_t, c_void_p, c_size_t]
_error = _libraries['magic'].magic_error
_error.restype =... |
cboling/xos | xos/tosca/resources/flavor.py | Python | apache-2.0 | 948 | 0.006329 | # note: this m | odule named xossite.py instead of site.py due to conflict with
# /usr/lib/python2.7/site.py
import os
import pdb
import sys
import tempfi | le
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
from core.models import User, Deployment, Flavor
from xosresource import XOSResource
class XOSFlavor(XOSResource):
provides = "tosca.nodes.Flavor"
xos_model = Flavor
copyin_props = ["flavor"]
def get_xos_ar... |
MSeifert04/astropy | astropy/modeling/rotations.py | Python | bsd-3-clause | 16,505 | 0.000666 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Implements rotations, including spherical rotations as defined in WCS Paper II
[1]_
`RotateNative2Celestial` and `RotateCelestial2Native` follow the convention in
WCS Paper II to rotate to/from a native sphere and the celestial sphere.
The implement... | ter=_to_radian)
psi = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
def __init__(self, phi, theta, psi, axes_order, **kwargs):
self.axes = ['x', 'y', 'z']
if len(axes_order) != 3:
raise TypeError(
"Expected axes_order to be a character sequence of len... | )
if unrecognized:
raise ValueError("Unrecognized axis label {}; "
"should be one of {} ".format(unrecognized, self.axes))
self.axes_order = axes_order
qs = [isinstance(par, u.Quantity) for par in [phi, theta, psi]]
if any(qs) and not all(qs):
... |
wooga/airflow | tests/providers/amazon/aws/operators/test_gcs_to_s3.py | Python | apache-2.0 | 8,747 | 0.000457 | #
# 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... | replace=False)
# create dest bucket without files
hook = S3Hook(aws_conn_id='airflow_gcs_test')
| bucket = hook.get_bucket('bucket')
bucket.create()
# we expect all MOCK_FILES to be uploaded
# and all MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
self.assertEqual(sorted(MOCK_FILES),
sorted(uploaded_files))
... |
voidabhi/python-scripts | blinker-example.py | Python | mit | 554 | 0.005415 | import blinker
frobnicated = blinker.signal('frobnicated')
class Receiver(object):
def __init__(self):
| def handle_frobnicated(sender, **kwargs):
self.on_frobnicated(sender, **kwargs)
self.handle_frobnicated = handle_frobnicated
frobnicated.connect(handle_frobnicated)
def on_frobnicated(self, sender, **kwargs):
print sender, kwargs['message']
if __name__ == ... | .send('Sender %s' % i, message='hello')
|
rrooij/youtube-dl | youtube_dl/extractor/yahoo.py | Python | unlicense | 23,544 | 0.002263 | # coding: utf-8
from __future__ import unicode_literals
import itertools
import json
import re
from .common import InfoExtractor, SearchInfoExtractor
from ..compat import (
compat_urllib_parse,
compat_urlparse,
)
from ..utils import (
clean_html,
determine_ext,
ExtractorError,
extract_attribut... | 'upload_date': '20150313',
'uploader': 'NBCU-SPORTS',
'timestamp': 1426270238,
}
}, {
'url': 'https://tw.news.yahoo.com/-100120367.html',
'only_matching': True,
}, {
# Query result is embedded in webpage, but ... | ity-episode-1-ladders-154501237.html',
'md5': '4fbafb9c9b6f07aa8f870629f6671b35',
'info_dict': {
'id': '1f32853c-a271-3eef-8cb6-f6d6872cb504',
'ext': 'mp4',
'title': 'Communitary - Community Episode 1: Ladders',
'description': 'md5:... |
katakumpo/nicedjango | tests/samples_compact_yaml.py | Python | mit | 6,357 | 0.000472 | SAMPLES_YAML = {
'a': """\
- a1-a: [pk]
- [A1]
- [A2]
- [B1]
- [C1]
- [C2]
- [D1]
- [E1]
- [P1]
""",
'b': """\
- a1-a: [pk]
- [B1]
- [C1]
- [C2]
- [D1]
- [E1]
- a1-b: [pk]
... | ""\
- a1-a: [pk]
- [A2]
- [D1]
""",
'a_some_a_b': """\
- a1-a: [pk]
- [A2]
- [D1]
- a1-b: [pk]
- [D1]
""",
'f_a_d': """\
- a1-a: [pk]
- [A1]
- [D1]
- a1-f: [pk, a]
- [F1, null]
- [F2, ... | f': """\
- a1-a: [pk]
- [D1]
- a1-b: [pk]
- [D1]
- a1-c: [pk]
- [D1]
- a1-d: [pk]
- [D1]
- a1-f: [pk, a]
- [F4, D1]
""",
'o_one_o_s': """\
- a1-a: [pk]
- [C2]
- [D1]
- a1-b: [pk]
- [C2]
... |
activitycentral/ebookreader | src/ReadTab/epubview/navmap.py | Python | gpl-2.0 | 5,036 | 0.004369 | import os
import env_settings as env
from gi.repository import Gtk
from lxml import etree
class NavPoint(object):
def __init__(self, label, contentsrc, children=[]):
self._label = label
self._contentsrc = contentsrc
self._children = children
def get_label(self):
return self._... | hildnavpointlist:
self._process_navpoint(ch | ildnavpoint, parent=iter)
else:
return
def get_gtktreestore(self):
'''
Returns a GtkTreeModel representation of the
Epub table of contents
'''
return self._gtktreestore
def get_flattoc(self):
'''
Returns a flat (linear) list of files ... |
noirbizarre/minibench | minibench/__init__.py | Python | mit | 365 | 0.00274 | # -*- coding: utf-8 -*-
# flake8: noqa
from __future__ import unicode_literals
from .__about__ import | __version__, __description__, __author__, __url__
from .benchmark import Benchmark, RunResult, DEFAULT_TIMES
from .report import BaseReporter, JsonReporter, CsvReporter, MarkdownReporter, R | stReporter, FileReporter, FixedWidth
from .runner import BenchmarkRunner
|
ESOedX/edx-platform | common/test/acceptance/pages/lms/edxnotes.py | Python | agpl-3.0 | 20,755 | 0.002024 | """
LMS edxnotes page
"""
from __future__ import absolute_import
from bok_choy.page_object import PageLoadError, PageObject, unguarded
from bok_choy.promise import BrokenPromise, EmptyPromise
from selenium.webdriver.common.action_chains import ActionChains
from common.test.acceptance.pages.common.paging import Pagina... | """
Helper class that works with chapter (section) grouping of notes in the Course Structure view on the | Note page.
"""
BODY_SELECTOR = ".note-group"
@property
def title(self):
return self._get_element_text(".course-title")
@property
def subtitles(self):
return [section.title for section in self.children]
@property
def children(self):
children = self.q(css=self._... |
adkerr/tempest | tempest/tests/stress/test_stress.py | Python | apache-2.0 | 1,945 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Deutsche Telekom AG
# 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... | cense.
import shlex
import subprocess
import tempest.cli as cli
from tempest.openstack.common import log as logging
import tempest.test
LOG = logging.getLogger(__name__)
class StressFrameworkTest(tempest.test.BaseTestCase):
"""Basic test for the stress test framework.
"""
def _cmd(self, cmd, param):
... | cmd = ' '.join([cmd, param])
LOG.info("running: '%s'" % cmd)
cmd_str = cmd
cmd = shlex.split(cmd)
result = ''
result_err = ''
try:
stdout = subprocess.PIPE
stderr = subprocess.PIPE
proc = subprocess.Popen(
cmd, stdou... |
ntt-sic/neutron | neutron/agent/linux/ovs_lib.py | Python | apache-2.0 | 17,481 | 0.001144 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nicira Networks, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | kwargs:
raise Exception(_("Must specify one or more actions"))
if "priority" not in kwargs:
kwargs["priority"] = "0"
flow_expr_arr = self._build_flow_expr_arr(**kwargs)
flow_expr_arr.append("actions=%s" % (kwargs["actions" | ]))
flow_str = ",".join(flow_expr_arr)
return flow_str
def add_flow(self, **kwargs):
flow_str = self.add_or_mod_flow_str(**kwargs)
if self.defer_apply_f |
hagne/atm-py | atmPy/atmosphere/standards.py | Python | mit | 5,525 | 0.004525 | # -*- coding: utf-8 -*-
"""
This module contains atmospheric constands and standards.
@author: Hagen
"""
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
class Standard_Atmosphere(object):
def __init__(self, standard='international'):
"""Returns pressure, temperature, an... | alue: float or ndarray.
Depending on the keyword "quantity" this is:
- altitude in meters.
- pressure in mbar.
quantity: 'altitude' or 'pressure'.
quantaty of the argument value.
standard: 'US' or 'international'.
defines which st | andard is used.
return_standard: bool, optional.
if True argument "value" and "quantity" are ignored and a pandas dataTable with the standard is returned.
Returns
-------
tuple of two floats or two ndarrays depending on type of h:
First quantaty the tuple is pre... |
Fubukimaru/asMSX | test/environment.py | Python | gpl-3.0 | 588 | 0.003401 | from behave import fixture, use_fixture
import os
def after_scenar | io(context, scenario):
extensions = ["bin", "txt", "cas", "sym", "wav", "rom", "z80", "com", "ram"]
# cleanup build temp files
for i in range(0, 4):
file = f"~tmppre.{i}"
if os.path.isfile(file):
os.remove(file)
if os.path.isfile("test.asm"):
os.remove("test.asm")
... | ove(file)
|
plotly/python-api | packages/python/plotly/plotly/validators/carpet/aaxis/_rangemode.py | Python | mit | 535 | 0.001869 | import _plotly_utils.basevalidators
class RangemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="rangemode", parent_name="carpet.aaxis", **kwargs):
super(RangemodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_n... | s.pop("edit_type", "calc"),
role=kwargs.pop("role", "sty | le"),
values=kwargs.pop("values", ["normal", "tozero", "nonnegative"]),
**kwargs
)
|
DLR-SC/RepoGuard | src/repoguard/handlers/hudson.py | Python | apache-2.0 | 1,478 | 0.004736 | # pylint: disable-msg=W0232
# Copyright 2008 German Aerospace Center (DLR)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:/ | /www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissio... | ore.module import Handler, HandlerConfig, String
class Config(HandlerConfig):
class types(HandlerConfig.types):
url = String
token = String(optional=True)
class Hudson(Handler):
"""
Hudson handler for build triggering.
"""
__config__ = Config
d... |
3xbun/elab-cpe | code/lecture/ex1.py | Python | mit | 252 | 0.031746 | n = 5
count = 0
total = 0
startCount = n - 3
while True:
if count == n:
break
elif count < n:
x = int(input())
if count > startCount:
total = total + x
|
count = count + 1
print('')
print('Sum is | %d.' % total)
|
imammedo/virt-test | virttest/libvirt_xml.py | Python | gpl-2.0 | 16,009 | 0.003685 | """
Intermediate module for working with XML-related virsh functions/methods.
The intention of this module is to hide the details of working with XML
from test module code. Helper methods are all high-level and not
condusive to direct use in error-testing. However, access to a virsh
instance is available.
All class... | pass # no XML was loaded yet
return the_copy
class LibvirtXML(LibvirtXMLBase):
"""
Handler of libvirt capabilities and nonspecific item operations.
Properties:
os_arch_machine_map: strores None, virtual, read-only
get: dict map from os type names to dict map from arch ... | ful stats
# e.g. guest_count, arch, uuid, cpu_count, etc.
__slots__ = LibvirtXMLBase.__slots__ + ('os_arch_machine_map',)
def __init__(self, virsh_instance=virsh):
super(LibvirtXML, self).__init__(virsh_instance)
# calls set_xml accessor method
self['xml'] = self.virsh.capabilities... |
crashlytics/aurora | src/main/python/apache/aurora/client/cli/jobs.py | Python | apache-2.0 | 27,008 | 0.010923 | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | CONFIG_ARGUMENT]
def execute(self, context):
config = context.get_job_config(
context.options.instance_spec.jobkey,
context.options.config_file | )
if context.options.rename_from is not None:
cluster = context.options.rename_from.cluster
role = context.options.rename_from.role
env = context.options.rename_from.environment
name = context.options.rename_from.name
else:
cluster = config.cluster()
role = config.role()
... |
safwanrahman/kuma | kuma/wiki/tests/test_models.py | Python | mpl-2.0 | 71,294 | 0.000238 | import json
import time
from datetime import date, datetime, timedelta
from xml.sax.saxutils import escape
import mock
import pytest
from constance import config
from constance.test import override_config
from waffle.models import Switch
from django.conf import settings
from django.core.exceptions import ValidationEr... | oveError)
from ..models import (Document, DocumentTag, Revision, RevisionIP,
TaggedDocument)
from ..templatetags.jinja_helpers import absolutify
from ..utils import tidy_content
from ..signals import render_done
def _objects_eq(manager, list_):
"""Assert that the objects contained by `manage... | content='REDIRECT [[%s]]' % redirect_to,
is_approved=True,
save=True)
class DocumentTests(UserTestCase):
"""Tests for the Document model"""
def test_json_data(self):
"""bug 875349"""
# Set up a doc with tags
rev = revision(is_approved=True, save=True, content='Samp... |
eagleamon/home-assistant | homeassistant/components/media_player/anthemav.py | Python | apache-2.0 | 5,361 | 0 | """
Support for Anthem Network Receivers and Processors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.anthemav/
"""
import logging
import asyncio
import voluptuous as vol
from homeassistant.components.media_player import (
PLATFORM_S... | n_off(self):
"""Turn AVR power off."""
self._update_avr('power', False)
@asyncio.coroutine
def async_turn_on(self):
"""Turn AVR power on."""
self._update_avr('power', True)
@asyncio.coroutine
def async_set_volume_level(self, volume):
"""Set AVR volume (0 to 1)."... | e
def async_mute_volume(self, mute):
"""Engage AVR mute."""
self._update_avr('mute', mute)
def _update_avr(self, propname, value):
"""Update a property in the AVR."""
_LOGGER.info('Sending command to AVR: set '+propname+' to '+str(value))
setattr(self.avr.protocol, propn... |
mr-uuid/snippets | python/comprehension.py | Python | mit | 1,057 | 0.000946 | import | unittest
class Tester(unittest.TestCase):
def test_list_comprehension(self):
a = [(x, y)
for x in [1, 2, 3]
for y in [3, 1, 4]
if x != y]
b = []
for x in [1, 2, 3]:
| for y in [3, 1, 4]:
if x != y:
b.append((x, y))
self.assertEqual(a, b)
def test_dict_comprehension(self):
_dict = {x: x**2 for x in (2, 4, 6)}
self.assertEqual(
_dict,
{2: 4, 4: 16, 6: 36}
)
_dict = {k:... |
ticklemepierce/osf.io | api/tokens/serializers.py | Python | apache-2.0 | 2,864 | 0.002793 | from rest_framework import serializers as ser
from rest_framework import exceptions
from framework.auth.oauth_scopes import public_scopes
from website.models import ApiOAuth2PersonalToken
from api.base.serializers import JSONAPISerializer, LinksField, IDField, TypeField
class ApiOAuth2PersonalTokenSerializer(JSONAP... | a']['attributes'].pop('token_id')
| else:
data['attributes'].pop('token_id')
return data
def create(self, validated_data):
validate_requested_scopes(validated_data)
instance = ApiOAuth2PersonalToken(**validated_data)
instance.save()
return instance
def update(self, instance, validated_d... |
tab10/student_retainer | gui/Main.py | Python | mit | 44,810 | 0.00857 | ###################
# Imports
###################
# External files
from Tkinter import *
import tkMessageBox
from PIL import Image,ImageTk
import rpy2.robjects as robjects
import rpy2.robjects.numpy2ri
# Homemade files
import Point
import Pointer_List
import Clusters_value
###################
# Globals
##############... | umn=0, sticky='news')
p9.grid(row=1, column=0, sticky='news')
p10.grid(row=1, column=0, sticky='news')
#####
##### Page 1
msg = ('Welcome to the tutorial! \n \n'
'This application will attempt to classify whether or not a new student will likely stay in school at OU.\n'
'Thi... | of other students data were collected in order to try and find a trend on whether or not they would be retained. \n '
'Using this data, we can take new student entries and say with a certain confidence whether or not \n'
'the student will be likely to continue in their studies. \n'
'... |
josyb/myhdl | myhdl/test/conversion/general/test_randscrambler.py | Python | lgpl-2.1 | 2,592 | 0.010031 | import os
path = os.path
import unittest
from unittest import TestCase
import random
from random import randrange
random.seed(2)
import time
import myhdl
from myhdl import *
from myhdl.conversion import verify
N = 8
M = 2 ** N
DEPTH = 5
@block
def xor(z, a, b, c):
@instance
def logic():
while 1:
... | for i in range(N):
j, k = randOthers(i, N)
i1[i] = xo | r(sl1[i], il[i], il[j], il[k])
rs = randscrambler(sl2, sl1, stage=stage+1)
for i in range(N):
j, k = randOthers(i, N)
i2[i] = xor(ol[i], sl2[i], sl2[j], sl2[k])
return i1, i2, rs
else:
for i in range(N):
j, k = randOthers(i, N)
i1[i] = ... |
TeamEOS/external_chromium_org | tools/telemetry/telemetry/core/user_agent.py | Python | bsd-3-clause | 1,017 | 0.003933 | # Copyright 2012 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.
UA_TYPE_MAPPING = {
'desktop':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) '
'AppleWebKit/537.22 (KHTML, like Gecko) '
'Chrome/27.0.1... | ile':
'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) | '
'AppleWebKit/535.19 (KHTML, like Gecko) Chrome/27.0.1453.111 Mobile '
'Safari/535.19',
'tablet':
'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus 7 Build/IMM76B) '
'AppleWebKit/535.19 (KHTML, like Gecko) Chrome/27.0.1453.111 '
'Safari/535.19',
}
def GetChromeUserAgentArgumentFromTyp... |
taraokelly/Graph-Theory-Assignment | data/progParser.py | Python | mit | 3,689 | 0.010843 | import xml.etree.ElementTree as ET
import csv
'''
Tara O'Kelly - G00322214,
Graph Theory Assignment,
Third Year, Graph Theory, Software Development.
A program to parse the xml file with data taken from http://timetable.gmit.ie/.
'''
# adapted from https://docs.python.org/3/library/xml.etree.elementtree.html
out = ... | [4], s[0], s[2 | ], d]
elif s[1] == "Cons" :
row = [s[3], s[0] + s[1], "SPA", d]
# courses with no specified name
else:
for subs in s:
if count == 1:
ss += subs
if count > 1:
ss += " " + subs
count += ... |
Ledoux/ShareYourSystem | Pythonlogy/draft/Eulerer/__init__.py | Python | mit | 1,369 | 0.04748 | # -*- coding: utf-8 -*-
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
An Eulerer
"""
#<DefineAugmentation>
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Specials.Simulaters.Populater"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Classe... | oatsArray',
]
def default_init(self,
_EuleringPreFloatsArray=None,
_EuleringJacMethodStr="euler_null",
_EuleringStepTimeFloat=0.1,
_EuleredPostFloatsArray=None,
**_KwargVariablesDict
):
#Call the parent __init__ method
BaseClass.__init__(self,**_KwargVariablesDict)
def eule... | self.debug(('self.',self,[
'EuleringJacMethodStr'
]))
'''
#Do euler
self.EuleredPostFloatsArray=self.EuleringPreFloatsArray+getattr(
self,self.EuleringJacMethodStr)()*self.EuleringStepTimeFloat
#</DefineClass>
|
CodeForAfrica/WAZImap.Kenya | hurumap_zm/profiles.py | Python | gpl-3.0 | 33,757 | 0.004532 | from collections import OrderedDict
from django.conf import settings
from wazimap.data.utils import get_session, get_stat_data, group_remainder, \
current_context, dataset_context
from wazimap.geo import LocationNotFound
# ensure tables are loaded
import hurumap_zm.tables # noqa
LOCATIONNOTFOUND = {'is_missing... | TIONNOTFOUND
election_attend_a_campaign_rally = LOCATIONNOTFOUND
last_national_election_attend_a_campaign_meeting = LOCATIONNOTFOUND
| courts_make_binding_decisions = LOCATIONNOTFOUND
vote_for_which_party = LOCATIONNOTFOUND
level_of_corruption = LOCATIONNOTFOUND
chinas_assistance_meets_countrys_needs = LOCATIONNOTFOUND
employment_status = LOCATIONNOTFOUND
main_reason_for_not_reporting_corruption = LOCATIONNOT... |
nimbis/django-cms | cms/utils/compat/__init__.py | Python | bsd-3-clause | 325 | 0 | from distutils.version import LooseVersion
import django
# These means "less than or equal to DJANGO_FOO_BAR"
DJANGO_1_8 = LooseVersion(django.get_version()) < | LooseVersion('1.9')
DJANGO_1_9 = L | ooseVersion(django.get_version()) < LooseVersion('1.10')
DJANGO_1_10 = LooseVersion(django.get_version()) < LooseVersion('1.11')
|
jangler/vcii | setup.py | Python | mit | 745 | 0 | from distutils.core import setup
setup(
name='vcii',
version='0.0.0',
author='Brandon Mulcahy',
author_email='brandon@jangler.info',
url='https://github.com/jangler/vcii',
description='A TUI spreadsheet application.',
long_description=open( | 'README.txt').read(),
packages=['vcii', 'vcii.test'],
script | s=['bin/vcii'],
license='MIT',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: End U... |
pcon/mpd-rest | mpdrest/webserver.py | Python | gpl-2.0 | 3,381 | 0.005028 | # Copyright 2011 Patrick Connelly
#
# This file is part of mpd-rest
#
# mpd-rest 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.
#
# Th... |
return StatusSong.html(self)
class StatusServer:
@cherrypy.expose
@cherrypy.tools.jsonify()
def json(self):
return json.dumps(Config.client.status())
@cherrypy.expose
def html(self):
server | = Config.client.status()
return "<html><body>Server is currently: %s</body></html>" % (server['state'],)
@cherrypy.expose
def index(self, format=None):
if format == "json":
return StatusServer.json(self)
return StatusServer.html(self)
class Status:
song = StatusSong()
... |
alexandrul-ci/robotframework | src/robot/model/stats.py | Python | apache-2.0 | 6,395 | 0.000156 | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | psed = suite.elapsedtime
self._name = suite.name
def _get_custom_attrs(self):
return {'id': | self.id, 'name': self._name}
def _update_elapsed(self, test):
pass
def add_stat(self, other):
self.passed += other.passed
self.failed += other.failed
class TagStat(Stat):
"""Stores statistic values for a single tag."""
type = 'tag'
def __init__(self, name, doc='', links=... |
robk5uj/invenio | modules/bibformat/lib/elements/bfe_sciencewise.py | Python | gpl-2.0 | 3,743 | 0.008549 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2011 CERN.
##
## Invenio 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) a... | regexp in (_RE_MODERN_ARXIV, _RE_OLD_ARXIV):
g = regexp.match(reportnumber)
| if g:
return g.group('number')
return ""
def escape_values(bfo):
"""
Called by BibFormat in order to check if output of this element
should be escaped.
"""
return 0
def create_sciencewise_url(reportnumber):
"""
If the reportnumber is a valid arXiv reportnumber ret... |
tiborsimko/invenio-formatter | tests/test_filters.py | Python | mit | 2,728 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Tests for Jinja2 filters."""
from __future__ import absolute_import, print_functi... | """Test from_isodate filter."""
with app.test_request_context():
assert render_template_string(
"{{ 'yes' if dt|from_isodatetime < now else 'no'}}",
dt='2002-01-01T00:01:00', now=arrow.now()) == 'yes'
assert render_template_string(" | {{ dt|from_isodatetime }}", dt='') \
== 'None'
assert render_template_string(
"{{ dt|from_isodatetime }}", dt=datetime(2002, 1, 1, 1, 1)) == \
'2002-01-01 01:01:00+00:00'
pytest.raises(
TypeError, render_template_string,
"{{ 'yes' if dt < now e... |
alxgu/ansible | lib/ansible/modules/storage/netapp/na_elementsw_cluster_pair.py | Python | gpl-3.0 | 6,983 | 0.001575 | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | _SF_SDK = False
class ElementSWClusterPair(object):
""" class to handle cluster | pairing operations """
def __init__(self):
"""
Setup Ansible parameters and ElementSW connection
"""
self.argument_spec = netapp_utils.ontap_sf_host_argument_spec()
self.argument_spec.update(dict(
state=dict(required=False, choices=['present', 'absent'],
... |
cdegroc/scikit-learn | examples/tree/plot_iris.py | Python | bsd-3-clause | 2,073 | 0.002894 | """
================================================================
Plot the decision surface of a decision tree on the iris dataset
================================================================
Plot the decision surface of a :ref:`decision tree <tree>` trained on pairs
of features of the iris dataset.
For each p... | pe)
cs = pl.contourf(xx, yy, Z)
pl.xlabel(iris.feature_names[pair[0]])
pl.ylabel(iris.feature_names[pair[1]])
pl.axis("tight")
# Plot the training points
for i, color in zip(xrange(n_classes), plot_colors) | :
idx = np.where(y == i)
pl.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i])
pl.axis("tight")
pl.suptitle("Decision surface of a decision tree using paired features")
pl.legend()
pl.show()
|
meine-stadt-transparent/meine-stadt-transparent | mainapp/migrations/0023_auto_20190405_0911.py | Python | mit | 612 | 0 | # Generated by Django 2.1.8 on 2019-04-05 07:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencie | s = [
('mainapp', '0022_auto_20190404_1605'),
]
operations = [
migrations.AlterField(
model_name='historicalpaper',
name='reference_number',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AlterField(
mo... | ank=True, max_length=50, null=True),
),
]
|
SYSTRAN/nlp-api-python-client | systran_nlp_api/models/lid_paragraph_response.py | Python | apache-2.0 | 1,692 | 0.004728 | #!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licen... | .format(name=__name__, props=' '.join(properties))
| |
JasonSanchez/w261 | week2/NBPredict.py | Python | mit | 1,580 | 0.009494 |
import re
from mrjob.job import MRJob
from math import log
def tsv_model_to_dict(file):
results = {}
with open(file, "r") as model:
for line in model:
term, ham, spam = line.strip().split("\t")
results[term] = (float(ham), float(spam))
return results
class NBPredict(M... | .model = tsv_model_to_dict("SPAM_Model_MND.tsv")
def mapper(self, _, lines):
_, spam_actual, subject, email = lines.split("\t")
words = re.findall(r'[a-z]+', (email.lower()+" "+subject.lower()))
ham_prob, spam_prob = self.model["***Priors"]
ham_prob, spam_prob = log(ham... | log(spam_prob)
for word in words:
ham, spam = self.model[word]
if ham*spam == 0:
ham += .0001
spam += .0001
ham_prob += log(ham)
spam_prob += log(spam)
result = 1 if ham_prob < spam_prob else 0
... |
bugness/ask-and-answer | qa/migrations/0001_initial.py | Python | mit | 1,214 | 0.002471 | # - | *- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-16 14:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... | True, serialize=False, verbose_name='ID')),
('text', models.TextField()),
('created_at', models.DateTimeField()),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary... |
Micronaet/micronaet-contract | contract_manage_report/wizard/wizard_report.py | Python | agpl-3.0 | 9,417 | 0.01115 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP module
# Copyright (C) 2010 Micronaet srl (<http://www.micronaet.it>) and the
# Italian OpenERP Community (<http://www.openerp-italia.com>)
#
# ###############################################... | :fields | .boolean('All department',),
'active':fields.boolean('Only active', help='In open state'),
'department_id':fields.many2one('hr.department', 'Department',
required=False),
'mode':fields.selection([
('list','Short list'),
('detailed','Detailed'), |
jonparrott/botocore | botocore/retryhandler.py | Python | mit | 921 | 0 | import time
import random
def delay_exponential(attempts):
time.sleep(random.random() * (2 ** attempts))
class RetryHandler(object):
"""
Super simple retry handler.
Pass in the callable to be retried and another callable, the statusfn.
The statusfn will get called with | the attempt number and the return
value and is responsible for performing any kind of delay needed. It
should also return a boolean, True if the retryable needs to be
retried and False if it does not.
"""
def __init__(self, retryable, statusfn):
self.retryable = retryable
self.sta... | try:
return_value = self.retryable(*args, **kwargs)
self.attempts += 1
retry = self.statusfn(self.attempts, return_value)
return return_value
|
wmayner/pyphi | pyphi/conf.py | Python | gpl-3.0 | 27,730 | 0.000217 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# conf.py
"""
Loading a configuration
~~~~~~~~~~~~~~~~~~~~~~~
Various aspects of PyPhi's behavior can be configured.
When PyPhi is imported, it checks for a YAML file named ``pyphi_config.yml`` in
the current directory and automatically loads it if it exists; otherwise ... | not None and not isinstance(value, self.type):
raise ValueError(
"{} must be of type {} for {}; got {}".format(
value, self.type, self.name, type(value)
)
)
if self.values and value not in self.values:
raise ValueError(
... | ust be one of:\n {}".format(
value,
type(value),
self.name,
"\n ".join(["{} ({})".format(v, type(v)) for v in self.values]),
)
)
def _callback(self, obj):
"""Trigger any callbacks."""
i... |
balajikris/autorest | src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py | Python | mit | 899 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# C | ode generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class LongWrappe | r(Model):
"""LongWrapper.
:param field1:
:type field1: long
:param field2:
:type field2: long
"""
_attribute_map = {
'field1': {'key': 'field1', 'type': 'long'},
'field2': {'key': 'field2', 'type': 'long'},
}
def __init__(self, field1=None, field2=None):
se... |
bcdev/beam | beam-python/src/main/resources/beampy-examples/beampy_flh.py | Python | gpl-3.0 | 1,866 | 0.00268 | import sys
import numpy
from beampy import String
from beampy import Product
from beampy import ProductData
from beampy import ProductIO
from beampy import ProductUtils
if len(sys.argv) != 2:
print("usage: %s <file>" % sys.argv[0]);
sys.exit(1)
# Uncomment if you receive errors of type com.sun.media.jai.uti... | = numpy.zeros(width, dtype=numpy.float32)
r3 = numpy.zeros(width, dtype=numpy.float32)
print("Writing...")
for y in range(height):
b1.readPixels(0, y, width, 1, r1)
b2.readPixels(0, y, width, 1, r2)
b2.readPixels(0, y, width, 1, r3)
print("processing line ", y, " of ", height)
FLH = r2 - k * (r1 ... | - k * (r1 + a * (r3 - r1))
targetBand.writePixels(0, y, width, 1, FLH)
targetProduct.closeIO()
print("Done.") |
kyleconroy/dataflakes | etl/etl.py | Python | mit | 2,694 | 0.007795 | import argparse
import csv
import json
import re
MANUFACTURER = {
"A": "American Home Food Products",
"G": "General Mills",
"K": "Kellogs",
"N": "Nabisco",
"P": "Post",
"Q": "Quaker Oats",
"R": "Ralston Purina",
}
NORMAL_FIELDS = [
"calories",
"protein",
"fat",
"sodium"... | er_serving"] = 1
return cereal
def main():
parser = ar | gparse.ArgumentParser(description="Turn the cereal csv file into usable json files")
parser.add_argument("csvfile", type=str, help="The csv file to read")
parser.add_argument("-n", "--normalize", default=False, action="store_true")
args = parser.parse_args()
cerealReader = csv.reader(open(args.csvfile),... |
jobiols/odoo-addons | base_module_record/tests/test_base_module_record.py | Python | agpl-3.0 | 2,364 | 0 | # See LICENSE file for full copyright and licensing details.
from odoo.tests import common
from datetime import datetime, timedelta
class BaseModuleRecordTestCase(common.TransactionCase):
def setUp(self):
super(BaseModuleRecordTestCase, self).setUp()
def test_BaseModuleRecord_action(self):
s... | oduledata_obj = self.env['base.module.data']
check_date = datetime.\
strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"%Y-%m-%d %H:%M:%S")
check_date += timedelta(days=-3)
object_lst = []
for o_id in self.basemoduledata_obj._get_default_objects():
... | ledata_obj.\
create({'check_date': check_date,
'filter_cond': 'created',
'objects': [(6, 0, object_lst)]
})
self.basemoduledata_id.record_objects()
|
nttks/edx-platform | biz/djangoapps/gx_login/views.py | Python | agpl-3.0 | 3,215 | 0.001555 | """
Views for contract feature
"""
import logging
from edxmako.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from biz.djangoapps.ga_manager.models impo... | _email = request.POST.get('email', '')
post_password = request.POST.get("password")
post_remember = False
if request.method == 'POST':
next_url = request.POST.get("next", '')
if "remember" in request.POST:
post_remember = True
if not 0 < len(post_email) <= 255:
... | info('Login failed - password length over')
account_check = LOGIN_ERROR
if User.objects.filter(email=post_email, is_active=True).exists():
user = User.objects.get(email=post_email, is_active=True)
else:
log.info("Login failed - password for {0} is invalid".format(pos... |
hzlf/openbroadcast | website/tools/selectable/base.py | Python | gpl-3.0 | 5,321 | 0.000188 | "Base classes for lookup creation."
from __future__ import unicode_literals
import json
import operator
import re
from functools import reduce
from django.conf import settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.core.serializers.... | ECTABLE_ESCAPED_KEYS:
if key in result:
result[key] = conditional_escape(result[key])
return result
def paginate_results(self, results, options):
"Return a django.core.paginator.Page of results."
limit = options.get('limit', settings.SELECTABLE_MAX_LIMIT)
... | s = paginator.page(page)
except (EmptyPage, InvalidPage):
results = paginator.page(paginator.num_pages)
return results
def results(self, request):
"Match results to given term and return the serialized HttpResponse."
results = {}
form = self.form(request.GET)
... |
xpybuild/xpybuild | xpybuild/targets/docker.py | Python | apache-2.0 | 5,855 | 0.025448 | # xpyBuild - eXtensible Python-based Build System
#
# Copyright (c) 2013 - 2018, 2022 Software AG, Darmstadt, Germany and/or its licensors
#
# 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 a... | pertyValues(x) for x in self.buildArgs])
if self.dockerfile: dargs.extend(["-f", context.expandPropertyValues(self.dockerfile)])
inputs = self.inputs.resolve(context)
if len(inputs) != 1: raise BuildException("Must specify a single input for Docker.BUILD", location = self.location)
dargs.append(inputs[0])
cwd... | d', treatStdErrAsErrors=False, options=self.options), timeout=self.getOption('process.timeout'), env=environs, cwd=cwd)
# update the stamp file
self.updateStampFile()
class DockerPushTag(DockerBase):
def __init__(self, imagename, fromimage):
"""
Push a docker tag from the specified image.
"""
DockerBas... |
ShadySQL/mortar-recsys | udfs/jython/recsys.py | Python | apache-2.0 | 1,151 | 0.007819 | from math import exp
from collections import defaultdict
@outputSchema("scaled: double")
def logistic_scale(val, logistic_param):
return -1.0 + 2.0 / (1.0 + exp(-logistic_param * val))
@outputSchema("t: (item_A, item_B, dist: double, raw_weight: double)")
def best_path(paths):
return sorted(paths, key=lambda ... |
def aggregate_signal_types(signal_list):
signal_dict = {}
for row in signal_list:
if row[3]:
if not signal_dict.get(row[3]):
signal_dic | t[row[3]] = 0
signal_dict[row[3]] += 1
return signal_dict
@outputSchema("signal_map:map[]")
def combine_signals(signal_list):
signal_dict = {}
for row in signal_list:
if row[3]:
for val in row[3].keys():
if not signal_dict.get(row[3]):
sig... |
unho/pootle | tests/pootle_profile/profile.py | Python | gpl-3.0 | 2,638 | 0.000758 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the | Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from datetime import timedelta
import pytest
from django.utils import timezone
from pootle.core.delegate import profile
from pootle.co... | rofile.utils import UserMembership, UserProfile
from pootle_score.utils import UserScores
@pytest.mark.django_db
def test_profile_user(member):
user_profile = profile.get(member.__class__)(member)
assert isinstance(user_profile, UserProfile)
assert user_profile.user == member
user_membership = user_pr... |
materialsproject/MPContribs | mpcontribs-api/maintenance.py | Python | mit | 1,365 | 0.00293 | from boltons.iterutils import remap
from mongoengine.queryset.visitor import Q
from mpcontribs.api import enter
from mpcontribs.api.projects.document import Projects
from mpcontribs.api.contributions.document import Contributions
def visit(pa | th, key, value):
if isinstance(value, dict) and "display" in value:
return key, value["display"]
return True
def fix_units(name):
# make sure correct units are indicated in project.columns before running this
fields = list(Contributions._fields.keys())
project = Projects.objects.with_id(na... | query = Q()
for column in project.columns:
if column.unit and column.unit != "NaN":
path = column.path.replace(".", "__")
q = {f"{path}__unit__ne": column["unit"]}
query |= Q(**q)
contribs = Contributions.objects(Q(project=name) & query).only(*fields)
num = cont... |
theSage21/dataflow | dataflow/scribe.py | Python | mit | 5,172 | 0.003867 | import os
import json
import datetime
from functools import reduce
from copy import deepcopy
from dataflow import config
def read_data(name):
"READ JSON DATA and return a dict"
with open(os.path.join(config.static_dir, 'scripts', name), 'r') as fl:
data= json.loads(fl.read())
return data
def wrap... | xt_step.update({to: ops[to]})
poplist.add(frm)
current_step = next_step
for name in poplist:
ops.pop(name)
if this_step:
traversal.appen | d(this_step)
elif not this_step and not next_step:
traversal.append(deepcopy(ops))
ops = {}
return traversal
def name_variables(traversal, data):
variable_map = dict()
# Generate a variable map
unique_nodes_from = dict()
var_name_count = 0
for link in data['links... |
Beeblio/django | django/core/handlers/wsgi.py | Python | bsd-3-clause | 9,989 | 0.000701 | from __future__ import unicode_literals
import codecs
import logging
import sys
from io import BytesIO
from threading import Lock
import warnings
from django import http
from django.conf import settings
from django.core import signals
from django.core.handlers import base
from django.core.urlresolvers import set_scri... | .lstrip('/'))
self.META = environ
self.META['PATH_INFO'] = path_info
self.META['SCRIPT_NAME'] = script_name
self.method = environ['REQUEST_METHOD'].upper()
_, content_params = self._parse | _content_type(environ.get('CONTENT_TYPE', ''))
if 'charset' in content_params:
try:
codecs.lookup(content_params['charset'])
except LookupError:
pass
else:
self.encoding = content_params['charset']
self._post_parse_error... |
lucernae/feti | django_project/feti/models/education_training_quality_assurance.py | Python | bsd-2-clause | 623 | 0 | # coding=utf-8
"""Model class for Education and Training Quali | ty Assurance (ETQA)."""
__author__ = 'Christian Christelis <christian@kartoza.com>'
__date__ = '04/2015'
__license__ = "GPL"
__copyright__ = 'kartoza.com'
from django.contrib.gis.db import models
class EducationTrainingQualityAssurance(models.Model):
acronym = models.CharField(max_length=30)
body_name = mode... | % (self.acronym, self.acronym)
class Meta:
app_label = 'feti'
|
datanel/navitia | source/jormungandr/jormungandr/interfaces/v1/Schedules.py | Python | agpl-3.0 | 13,275 | 0.001582 | # coding=utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility an... | to publish the disruptions from."
" Default is the current date and it is mainly used for debug.")
self.method_decorators.append(complete_links(self))
def get(self, uri=None, region=None, lon=None, lat=None):
args = self.parsers["get"].parse_args()
| args["nb_stoptimes"] = args["count"]
args["interface_version"] = 1
if uri is None:
first_filter = args["filter"].lower().split("and")[0].strip()
parts = first_filter.lower().split("=")
if len(parts) != 2:
error = "Unable to parse filter {filter}... |
calston/xenzen | xenapi/XenAPI.py | Python | mit | 10,402 | 0.002115 | # Copyright (c) Citrix Systems, 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:
#
# 1) Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | ssion, but failed')
def _login(self, method, params):
try:
result = _parse_result(
getattr(self, 'session.%s' % method)(*params))
if result is _RECONNECT_AND_RETRY:
raise xmlrpclib.Fault(
500, 'Received SESSION_INVALID when logging... | f.API_version = self._get_api_version()
except socket.error, e:
if e.errno == socket.errno.ETIMEDOUT:
raise xmlrpclib.Fault(504, 'The connection timed out')
else:
raise e
def _logout(self):
try:
if self.last_login_method.startswith... |
macosforge/ccs-calendarserver | txdav/dps/commands.py | Python | apache-2.0 | 6,689 | 0 | ##
# Copyright (c) 2014-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | ('items', amp.ListOf(amp.String())),
('continuation', amp.String(optional=True)),
]
class SetAutoScheduleModeCommand(amp.Command):
arguments = [
('uid', amp.String()),
('autoScheduleMode', amp.String()),
]
response = [
('success', amp.Boolean()),
]
class Flu... | p.Boolean()),
]
class StatsCommand(amp.Command):
arguments = []
response = [
('stats', amp.String()),
]
|
andrewyoung1991/supriya | supriya/tools/requesttools/GroupQueryTreeRequest.py | Python | mit | 1,918 | 0.003128 | # -*- encoding: utf-8 -*-
from supriya.tools import osctools
from supriya.tools.requesttools.Request import Request
class GroupQueryTreeRequest(Request):
r'''A /g_queryTree request.
::
>>> from supriya.tools import requesttools
>>> request = requesttools.GroupQueryTreeRequest(
... ... |
return message
### PUBLIC PROPERTIES ###
@property
def include_controls(self):
return self._include_controls
@property
def node_id(self):
return self._node_id
@property
def | response_specification(self):
from supriya.tools import responsetools
return {
responsetools.QueryTreeResponse: None,
}
@property
def request_id(self):
from supriya.tools import requesttools
return requesttools.RequestId.GROUP_QUERY_TREE |
bdh1011/wau | venv/lib/python2.7/site-packages/nbconvert/exporters/pdf.py | Python | mit | 5,560 | 0.005576 | """Export to PDF via latex"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import subprocess
import os
import sys
from ipython_genutils.py3compat import which
from traitlets import Integer, List, Bool, Instance
from ipython_genutils.tempdir import TemporaryWork... | f cmd is None:
raise OSError("%s not found on PATH" % command_list[0])
times = 'time' if count == 1 else 'times'
self.log.info("Running %s %i %s: %s", command_list[0], count, times, command)
with open(os.devnull, 'rb') as null:
stdout = subprocess.PIPE if not sel... | verbose else None
for index in range(count):
p = subprocess.Popen(command, stdout=stdout, stdin=null)
out, err = p.communicate()
if p.returncode:
if self.verbose:
# verbose means I didn't capture stdout with PIPE,
... |
decabyte/vehicle_core | scripts/pilot_cli.py | Python | bsd-3-clause | 5,387 | 0.003898 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import sys
import signal
import argparse
import numpy as np
np.set_printoptions(precision=3, suppress=True)
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
# see: http://stackoverflow.com/questions/2891790/pretty-printing-of-num... | itude', default='n', nargs='?')
parser.add_argument('mode', choices=MODES, | metavar='mode', help='select z-axis mode', default='depth', nargs='?')
parser.add_argument('-v', '--verbose', action='store_true', help='Print detailed information.')
if len(sys.argv) <= 1:
parser.print_help()
sys.exit(1)
# parse input
args = parser.parse_args()
# default request... |
EricMuller/mynotes-backend | requirements/twisted/Twisted-17.1.0/src/twisted/internet/test/test_posixbase.py | Python | mit | 9,536 | 0.003041 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet.posixbase} and supporting code.
"""
from __future__ import division, absolute_import
from twisted.trial.unittest import TestCase
from twisted.internet.defer import Deferred
from twisted.internet.posixbase import ... | elf):
"""
If a delayed call is scheduled and then some time passes, the
timeout passed to C{doIteration} is reduced by the amount of tim | e
which passed.
"""
reactor = TimeoutReportReactor()
reactor.callLater(100, lambda: None)
reactor.now += 25
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, 75)
def test_multipleDelayedCalls(self):
"""
If there are sev... |
bdestombe/flopy-1 | examples/groundwater_paper/scripts/uspb_capture_par.py | Python | bsd-3-clause | 11,211 | 0.009901 | # parallel version of uspb_capture.py
# modified to run in parallel on mac and windows os
#
import os
import sys
import platform
import shutil
import time
import numpy as np
import subprocess as sp
import multiprocessing as mp
import flopy
# global executable name and output precision
precision = 'double'
exe_name ... | flopy.utils.CellBudgetFile(os.path.join(pth, 'DG.cbc'), precision=precision)
kk = hedObj.get_kstpkper()
h = hedObj.get_ts((k, i, j))
for idx, kon in enumerate(kk):
if h[idx, 1] == hdry:
v[idx] = np.nan
else:
v1 =... | text='STREAM LEAKAGE', full3D=True)[0]
v3 = cbcObj.get_data(kstpkper=kon, text='ET', full3D=True)[0]
v[idx] = ((v1.sum() + v2.sum() + v3.sum()) - base) / (-Qt)
except:
line += ' Error: Model run: {} of {} (model number {}) - '.format(ion+1, nmax, imod)
... |
fedspendingtransparency/data-act-broker-backend | tests/unit/dataactvalidator/test_fabs30_detached_award_financial_assistance.py | Python | cc0-1.0 | 1,646 | 0.006683 | from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabs30_detached_award_financial_assistance'
def test_column_headers(database):
expected_subset = {'row_number', 'business_funds_indic... | must contain one of the following values: REC or NON. | Case doesn't matter """
det_award = DetachedAwardFinancialAssistanceFactory(business_funds_indicator='REC', correction_delete_indicatr='c')
det_award_2 = DetachedAwardFinancialAssistanceFactory(business_funds_indicator='non', correction_delete_indicatr='')
# Ignore correction delete indicator of D
det_... |
raycarnes/project | project_sla/__openerp__.py | Python | agpl-3.0 | 5,303 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software... | xml',
'analytic_account_view.xml',
'project_view.xml',
'project_issue_view.xml', |
'project_task_view.xml',
'security/ir.model.access.csv',
'report/report_sla_view.xml',
],
'demo': ['project_sla_demo.xml'],
'test': ['test/project_sla.yml'],
'installable': True,
}
|
encolpe/maxfield | lib/orderedTSP.py | Python | gpl-3.0 | 5,855 | 0.012468 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import branch_bound
np = branch_bound.np
MAX_BRANCHES = 10000
# This could be used if more splits are wanted than are possible
infState = branch_bound.InfState()
class OTSPstate:
def __init__(self,d,order,nagents,visit2agent=[0],time=[0.],lastat=None,):
'''
... | time: time at which the nodes were visited
lastat[i,j]: the node where agent j most re | cently was at time[i]
nagents: number of agents
visit2agent[i] is the agent who makes visit i
'''
# This is the root
if lastat == None:
self.n = d.shape[0]
lastat = [[None]*nagents]
lastat[0][0] = 0
# Make a "start location" that ... |
yigor/stupid | setup.py | Python | bsd-3-clause | 2,103 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = "1.5.2"
if sys.argv[-1] == 'publish':
try:
import wheel # noqa
except ImportError:
raise ImportError("Fix: pip install ... | age :: Python :: 3.4',
'Progr | amming Language :: Python :: 3.6',
],
entry_points={
'console_scripts': [
'stupid = stupid.main:main',
]
},
setup_requires=['nose>=1.0', 'pytest-runner'],
tests_require=get_requirements('requirements-dev.txt'),
)
|
otnt/SimpleAppStore | HuaweiAppStore/HuaweiAppStore/settings.py | Python | apache-2.0 | 4,073 | 0.009575 | # -*- coding: utf-8 -*-
# Scrapy settings for HuaweiAppStore project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en... | ares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'HuaweiAppStore.middlewares.MyCustomSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES ... | y.downloadermiddlewares.useragent.UserAgentMiddleware' : None,
'HuaweiAppStore.RandomUserAgent.RandomUserAgentMiddleware' : 400,
#'HuaweiAppStore.RandomProxy.RandomProxyMiddleware' : 100,
#'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110
}
# Proxy list containing entries like
# http:... |
guardianproject/keysync | otrapps/adium.py | Python | gpl-3.0 | 4,023 | 0.002237 | #!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import platform
import plistlib
import sys
if __name__ == '__main__':
sys.path.insert(0, "../") # so the main() test suite can find otrapps module
import otrapps.util
from otrapps.otr_private_key import OtrPrivateKeys... | Using:')
print('\t"' + accountsfile + '"')
else:
print('Adium ERROR: No usable Accounts.plist file found, cannot create Adium files!')
return []
# make sure the plist is in XML format, not binary,
# this should be converted to use python-biplis... | s']
@staticmethod
def parse(settingsdir=None):
if settingsdir == None:
settingsdir = AdiumProperties.path
kf = os.path.join(settingsdir, AdiumProperties.keyfile)
if os.path.exists(kf):
keydict = OtrPrivateKeys.parse(kf)
else:
keydict = dict()... |
Azure/azure-sdk-for-python | build_package.py | Python | mit | 1,417 | 0.005646 | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# License | d under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------- | ---------------------------------------
import argparse
import os
import glob
import sys
from subprocess import check_call
DEFAULT_DEST_FOLDER = "./dist"
def create_package(name, dest_folder=DEFAULT_DEST_FOLDER):
# a package will exist in either one, or the other folder. this is why we can resolve both at the s... |
gengwg/leetcode | 378_kth_smallest_element_in_a_sorted_matrix.py | Python | apache-2.0 | 2,958 | 0.003719 | # 378. Kth Smallest Element in a Sorted Matrix
#
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
# Example:
#
# matrix = [
# [ 1, 5,... | i))
# pop k-1 times
for i in range(k-1):
val, x, y = heappop(h)
if x < len(matrix) - 1:
heappush(h, (matrix[x+1][y], x+1, y))
return h[0][0] # smallest element in heap. 0th index in tuple
# binary searc | h
# We can eventually find the k-th smallest element by shrinking the search range in binary search.
# Binary search is feasible for this problem since left, right,and mid in binary search are integers
# and we know that matrix elements are integers.
# The algorithm takes O(nlogN) time (N is the range ... |
SaptakS/pune.pycon.org | symposion/conference/migrations/0002_create_site.py | Python | bsd-3-clause | 753 | 0.001328 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def create_site(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly i | mport it, it'll be the wrong version
Site = apps.get_model('sites', 'Site')
db_alias = schema_editor.connection.alias
Site.objects.using(db_alias).get_or_create(
pk=1,
defaults= {
"pk": 1,
"domain": "us.pycon.org",
"name": "PyCon 2017"
}
)
cl... | encies = [
('conference', '0001_initial'),
('sites', '0001_initial'),
]
operations = [
migrations.RunPython(create_site),
]
|
like2000/PyCOBRA | PyCOBRA_run.py | Python | mit | 1,736 | 0.001152 | import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import c, e, m_p
import matplotlib.pyplot as plt
plt.switch_backend('TkAgg')
plt.ion()
from PyCOBRA_accelerator import TwissMap
from PyCOBRA_beam import Bunch, gaussian_generator
R = 6911./(2*np.pi)
energy = 26e9
gamma = np.sqrt(1 + (e*energy/(... | 0, ('z', 'dp'), 0, beta_z))
fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(12, 14), tight_layout=True)
one_turn_map = [twiss_x, twiss_y, twiss_z]
for k in range(60):
for m in one_turn_map:
m.kick(bunch)
ax1.scatt | er(bunch.x, bunch.xp, c='g', lw=0.1)
ax2.scatter(bunch.y, bunch.yp, c='g', lw=0.1)
ax3.scatter(bunch.z, bunch.dp, c='g', lw=0.1)
ax1.plot(np.mean(bunch.x), np.mean(bunch.xp), 'ro')
ax2.plot(np.mean(bunch.y), np.mean(bunch.yp), 'ro')
ax3.plot(np.mean(bunch.z), np.mean(bunch.dp), 'ro')
[ax.set_x... |
wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/IPython/nbconvert/filters/highlight.py | Python | mit | 4,619 | 0.002814 | """
Module containing filter functions that allow code to be highlighted
from within Jinja templates.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
# pygments must not be imported at the module level
# because errors should be raised at runtime if it's actual... | ource, output_formatter, language='ipython', metadata=None):
"""
Return a syntax-highlighted version of the input source
Parameters
----------
source : str
source of | the cell to highlight
output_formatter : Pygments formatter
language : str
language to highlight the syntax of
metadata : NotebookNode cell metadata
metadata of the cell to highlight
"""
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygment... |
xrmx/django | tests/urlpatterns_reverse/tests.py | Python | bsd-3-clause | 42,356 | 0.002999 | # -*- coding: utf-8 -*-
"""
Unit tests for reverse URL lookups.
"""
from __future__ import unicode_literals
import sys
import unittest
from admin_scripts.tests import AdminScriptTestCase
from django.conf import settings
from django.conf.urls import include
from django.contrib.auth.models import User
from django.core... | mpty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
('/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'other-ns1:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
# Nested namespaces
('/ns-included1/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:test-n... | 'inc-ns1:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
('/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:inc-ns4:inc-ns2:test-ns3', 'inc-ns1:inc-ns4:inc-ns2:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', '... |
crossbario/autobahn-python | examples/twisted/wamp/overview/frontend.py | Python | mit | 883 | 0 | from os import environ
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
# or: from autobahn.asyncio.wamp import ApplicationSession
class Component(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
# listening for ... | e procedure.
res = yield self.call('com.myapp.add2', 2, 3)
print("Got result: {}".format(res))
if __name__ == '__main__':
url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws")
realm = "crossbardemo"
runner = Applicatio | nRunner(url, realm)
runner.run(Component)
|
huhamhire/Hyper-hosts | hyperhosts/network/filter.py | Python | mit | 1,532 | 0.001958 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyleft (C) 2015 - huhamhire <me@huhamhire.com>
import ipaddress
import os
from abc import ABCMeta, abstractmet | hod
from hyperhosts.constants import RES_PATH
class FilterBase(object):
__metaclass__ = ABCMeta
def __init__(self):
super(FilterBase, self).__init__()
@abstractmethod
def filter(self, target):
return False
class IPFilter(FilterBase):
def __init__(self, is_ipv6=False):
... | self._list_file = os.path.join(RES_PATH, 'blacklists/ipv6.conf')
else:
self._list_file = os.path.join(RES_PATH, 'blacklists/ipv4.conf')
with open(self._list_file, 'r') as list_file:
ls = list_file.readlines()
blacklist = []
for l in ls:
... |
ThomasBollmeier/GObjectCreator2 | src/bin/gobject_creator2.py | Python | gpl-3.0 | 10,957 | 0.014603 | #!/usr/bin/python
#
# Copyright 2011 Thomas Bollmeier
#
# This file is part of GObjectCreator2.
#
# GObjectCreator2 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 you... | SION
def _create_option_parser():
res = OptionParser(usage = "usage: %prog [options] <goc_file>",
version = "%%prog, Version: %s, Author: Thomas Bollmeier" % \
VERSION
)
res.add_option("-d", "--dir",
dest = "outd... | res.add_option("-r", "--root",
dest = "root",
default = "",
metavar = "ROOT_NAME",
help = "generate objects of subtree ROOT_NAME only"
)
res.add_option("-I", "--include",
action = "append",
... |
charmander/livestreamer | src/livestreamer/plugins/alieztv.py | Python | bsd-2-clause | 2,005 | 0.002993 | import re
from os.path import splitext
from livestreamer.compat import urlparse, unquote
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HTTPStream, RTMPStream
_url_re = re.compile("""
http(s)?://(\w+\.)?aliez.tv
(?:
/live/[^/]... | scheme="http",
path=validate.ends | with("swf")
)
)
)
)
})
)
class Aliez(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _get_streams(self):
res = http.get(self.url, schema=_schema)
streams = {}
for url in res["url... |
kdart/pycopia | WWW/pycopia/WWW/fcgiserver.py | Python | apache-2.0 | 5,953 | 0.00336 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... | ERVERNAME) >= 0:
return pid
return 0
def kill_server(config):
import signal
pid = check4server(config)
if pid:
os.kill(pid, signal.SIGTERM)
print ("Killed %s (%s)." % (config.SERVERNAME, pid))
e | lse:
print ("%s not running." % (config.SERVERNAME,))
def run_server(argv):
username = None
do_daemon = True
debug = False
killserver = False
try:
optlist, args = getopt.getopt(argv[1:], "dnh?kl:f:p:s:")
except getopt.GetoptError:
print (run_server._doc % (argv[0],))
... |
OpenMined/PySyft | tests/integration/smpc/store/crypto_store_test.py | Python | apache-2.0 | 1,613 | 0 | # # stdlib
# from typing import Any
# from typing import Dict
# from typing import Iterable
# from typing import List
# from typing import Tuple
# # third party
# import pytest
# # syft absolute
# from syft.core.smpc.store import CryptoStore
# from syft.core.smpc.store import register_primitive_store_add
# from syft.... | nr_instances)]
# @pytest.mark.skip
# @register_primitive_store_add("test_crypto_store")
# def provider_test_add(
# store: Dict[str, List[Any]], primitives: Iterable[Any]
# ) -> List[Tuple[int]]:
# store["test_key_store"] = pri | mitives
# @pytest.mark.skip
# def test_add_store() -> None:
# crypto_store = CryptoStore()
# primitives = list(range(100))
# crypto_store.populate_store("test_crypto_store", primitives)
# crypto_store.store["test_key_store"] == primitives
# @pytest.mark.skip
# @pytest.mark.parametrize("nr_instance... |
dsbrown1331/CoRL2019-DREX | drex-atari/baselines/baselines/run.py | Python | mit | 8,217 | 0.003651 | import sys
import multiprocessing
import os.path as osp
import gym
from collections import defaultdict
import tensorflow as tf
import numpy as np
from baselines.common.vec_env.vec_video_recorder import VecVideoRecorder
from baselines.common.vec_env.vec_frame_stack import VecFrameStack
from baselines.common.cmd_util im... | make_env
from baselines.common.tf_util import get_session
from baselines import logger
from importlib import import_module
from baselines.common.vec_env.vec_normalize import VecNormalize, VecNormalizeRewards
try:
from mpi4py import MPI
except ImportError:
MPI = None
try:
import pybullet_envs
except Impo... | this with regexes
env_type = env._entry_point.split(':')[0].split('.')[-1]
_game_envs[env_type].add(env.id)
# reading benchmark names directly from retro requires
# importing retro here, and for some reason that crashes tensorflow
# in ubuntu
_game_envs['retro'] = {
'BubbleBobble-Nes',
'SuperMarioBros... |
CarlosMart626/umusicfy | umusicfy/mockups/contrib/auth.py | Python | apache-2.0 | 3,112 | 0.000643 | # -*- coding: utf-8 -*-
import mockups
from datetime import datetime
from django.contrib.auth.models import User, UNUSABLE_PASSWORD
from mockups import Mockup, Factory
from mockups import generators
class UserFactory(Factory):
username = generators.UUIDGenerator(max_length=30)
first_name = generators.LoremWor... | self.password)
return instance
mockups.register( | User, UserMockup, fail_silently=True)
|
salopensource/sal | server/templatetags/dashboard_extras.py | Python | apache-2.0 | 3,473 | 0.000288 | import json
import time
from distutils.version import LooseVersion
import dateutil.parser
from django import template
from django.shortcuts import get_object_or_404
from django.utils.timezone import utc
import utils.text_utils
from server.models import MachineGroup, BusinessUnit
register = template.Library()
@re... | n("10.11.99"):
return "macOS"
else:
return "OS X"
@register.filter
def bu_machine_count(bu_id):
"""Returns the number of machines contained within the child Machine Groups. Input is
BusinessUnit.id"""
| # Get the BusinessUnit
business_unit = get_object_or_404(BusinessUnit, pk=bu_id)
machine_groups = business_unit.machinegroup_set.all()
count = 0
for machinegroup in machine_groups:
count = count + machinegroup.machine_set.filter(deployed=True).count()
return count
@register.filter
def ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.