prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import os
import shutil
import unittest
import pytest
from pyontutils import obo_io as oio
from .common import temp_path
obo_test_string = """format-version: 1.2
ontology: uberon/core
subsetdef: cumbo "CUMBO"
treat-xrefs-as-has-subclass: EV
import: http://purl.obolibrary.org/obo/uberon/chebi_import.owl
treat-xrefs-as-... | tv = _test(ouch)
hrm = ('p | roperty_value: editor_note "TODO -'
' consider relationship to UBERON:0000091 ! bilaminar disc" xsd:string')
pv, tv = _test(hrm)
def test_robot(self):
of1 = oio.OboFile(data=obo_test_string)
obo1 = of1.asObo(stamp=False)
obor1 = of1.asObo(stamp=False, version=oio.OBO_... |
#!/usr/bin/env python
# Copyright (c) 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.
"""Script for a testing an existing SDK.
This script is normally run immediately after build_sdk.py.
"""
import argparse
import o... | ]
if options.phases:
phase_names = [p[0] for p in phases]
for arg in options.phases:
if arg not in phase_names:
msg = 'Invalid argument: %s\n' % arg
msg += 'Possible | arguments:\n'
for name in phase_names:
msg += ' %s\n' % name
parser.error(msg.strip())
for phase in phases:
phase_name = phase[0]
if options.phases and phase_name not in options.phases:
continue
phase_func = phase[1]
phase_args = phase[2:]
phase_func(*phase_args... |
class | dstat_plugin(dstat):
def __init__(self):
self.name = 'snooze'
self.vars = ('snooze',)
self.type = 's'
self.width = 6
self.scale = 0
self.before = time.time()
def extract(self):
now = time.time()
if loop != 0:
self.val['snooze'] = now ... | self.val['snooze'] = self.before
if step == op.delay:
self.before = now
def show(self):
if self.val['snooze'] > step + 1:
return ansi['default'] + ' -'
color = 'white'
if step != op.delay:
color = 'gray'
snoze, c = fchg(self.val['sno... |
ltithread: if set to True, lock send method.
skip_utf8_validation: skip utf8 validation.
"""
def __init__(self, get_mask_key=None, sockopt=None, sslopt=None,
fire_cont_frame=False, enable_multithread=False,
skip_utf8_validation=False):
"""
Initalize WebSock... | st 1 argument as integer.
The argument means length of mask key.
This func must be return string(byte array),
which length is argument specified.
| """
self.get_mask_key = func
def gettimeout(self):
"""
Get the websocket timeout(second).
"""
return self.sock_opt.timeout
def settimeout(self, timeout):
"""
Set the timeout to the websocket.
timeout: timeout time(second).
"""
se... |
import cherrypy
from cherrypy.test import helper
script_names = ["", "/path/to/myapp"]
class ProxyTest(helper.CPWebCase):
def setup_server():
# Set up site
cherrypy.config.update({
'tools.proxy.on': True,
'tools.proxy.base': 'www.mydomain.test',
})
# Set... | rypy/issues/562).
self.getPage("/xhost/", headers=[('X-Host', 'www.example.test')])
self.assertHeader('Location', "%s://www.example.test/x | host"
% self.scheme)
|
import os
import sys
import django
def main():
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
sys.path.append(os.path.abspath(os.path.dirnam... | ib.contenttypes',
'websettings',
)
global_settings.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
global_settings.MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contri... | 'django.contrib.auth.middleware.AuthenticationMiddleware',
)
global_settings.SECRET_KEY = "secret_key_for_testing"
global_settings.ROOT_URLCONF = "websettings.urls"
global_settings.WEBSETTINGS_MODULE = 'websettings.tests.settingstore'
from django.test.utils import get_runner
test_runner = ge... |
#! /usr/bin/env python
# --*-- coding:utf-8 --*--
import os
import sys
sys.path.append(os.path.split(os.path.split(os.path.abspath(sys.path[0]))[0])[0])
from CountMan.monitor.util import *
from CountMan.monitor.setting import *
class Queryer(object):
def __init__(self):
self.dao = DatabaseInterface()
... | f getData(self):
for queryKey in QUERYPARAM:
self.dataSet[queryKey] = getResponse(QUERYPARAM.get(queryKey))
@property
def set2db(self):
self.getData()
self.logger.info('get query data: {0} success'.format(self.dataSet))
self.dao.insertC | ollection(self.dataSet)
if __name__ == '__main__':
q = Queryer()
if ISDEBUG:
import cProfile
cProfile.run("q.set2db")
else:
q.set2db
|
# Copyright (c) 2015, Lars Tingelstad
# All rights reserved.
#
# All righ | ts reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in ... | otice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pyversor nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior writte... |
from django.conf.urls import include, url
fro | m . import views
urlpatterns = [
url(r'^$', views.post_list), #URL para lista de todos los | post
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail), #URL para ver los detalles del post
url(r'^post/new/$', views.post_new, name='post_new'), #URL para crear un nuevo post sin el panel de admin
url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'), #URL para editar los po... |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
'''
Bundle a context and its packages into a relocatable dir.
'''
from __future__ import print_function
import os
import os.path
import sys
def setup_parser(parser, completions=False):
group = parser.add_mutually_exclusive_group(... | dled, rather than raise an error")
group.add_argument(
"-f", "--force", action="store_true",
help="bundle package even if it isn't relocatable (use at your own risk)")
group.add_argument(
"-n", "--no-lib-patch", action="store_true",
help="don't apply library patching within the b... | ")
def command(opts, parser, extra_arg_groups=None):
from rez.utils.logging_ import print_error
from rez.bundle_context import bundle_context
from rez.resolved_context import ResolvedContext
rxt_filepath = os.path.abspath(os.path.expanduser(opts.RXT))
dest_dir = os.path.abspath(os.path.expanduser... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | r option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICUL | AR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
impor... |
from io import StringIO
import re
import httpretty
from django.core.management import call_command
from oppia.test import OppiaTestCase
from settings import constants
from settings.models import SettingProperties
from tests.utils import get_file_contents
class CartoDBUpdateTest(OppiaTestCase):
fixtures = ['test... | (self.cartodb_valid_response)
httpretty.register_uri(httpretty.GET,
self.cartodb_uri_regex,
body=cartodb_response)
SettingProperties.set_string(constants.OPPIA_CARTODB_ACCOUNT,
| "account")
SettingProperties.set_string(constants.OPPIA_CARTODB_KEY,
"FAKE_APIKEY")
SettingProperties.set_string(constants.OPPIA_HOSTNAME, "localhost")
out = StringIO()
call_command('cartodb_update', stdout=out)
@httpretty.activate
def te... |
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011 Nick Hall
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... | """
Displays the back references for a Citation,.
"""
def db_changed( | self):
self.dbstate.db.connect('citation-update', self.update)
self.connect_signal('Citation', self.update)
def update_has_data(self):
active_handle = self.get_active('Citation')
self.set_has_data(self.get_has_data(active_handle))
def main(self):
active_handle = sel... |
"""
Mapping functions
"""
# pylint: disable=invalid-name, missing-docstring, no-member
from __future__ import print_function
import pandas
from mpl_toolkits.basemap import Basemap
def create_map(lon, lat):
"""
Create a map projection.
"""
lon_center = lon[0]
lat_center = lat[0]
return Basem... | ',
width=1e-5, height=1e-5)
def project_lat_lon(df):
gps_map = Basemap(lat_0=df.GPS_Lat.values[0],
lon_0=df.GPS_Lon.values[0],
width=11e-5, height=1e-5, projection='tmer | c')
gps_y, gps_x = gps_map(df.GPS_Lon.values, df.GPS_Lat.values)
gps_z = df.GPS_Alt - df.GPS_Alt.values[0]
df_new = pandas.DataFrame(pandas.DataFrame({
'GPS_X': gps_x, 'GPS_Y': gps_y, 'GPS_Z': gps_z}, index=df.index))
return pandas.concat([df, df_new], axis=1)
# vim: set et fenc= ff=unix sts=0 ... |
# My files
from handlers import MainPage
from handlers import WelcomePage
from handlers import SignUpPage
from handlers import SignIn
from handlers import SignOut
from handlers import NewPost
from handlers import EditPost
from handlers import DeletePost
from handlers import SinglePost
from handlers import LikePost
from... | ignUpPage),
('/welcome', WelcomePage),
('/post/([0-9]+)', SinglePost),
('/new-post', NewPost),
('/edit-post/([0-9]+)', EditPost),
| ('/delete-post', DeletePost),
('/like-post', LikePost),
('/dislike-post', DislikePost),
('/edit-comment', EditComment),
('/delete-comment', DeleteComment),
('/login', SignIn),
('/logout', SignOut)
], debug=True)
|
# -*- coding: utf-8 -*-
from __future__ import unic | ode_literals, absolute_import, division
from alchemist import management
from flask import Flask
class TestManager:
def setup(self):
self.app = Flask('alchemist')
self.app.config['COMPONENTS'] = ['alchemist']
def test_discover_commands(self):
"""Should discover commands from register... | nager._commands
|
#!/bin/env python
# -*- coding: utf-8; -*-
#
# (c) 2016 FABtotum, http://www.fabtotum.com
#
# This file is | part of FABUI.
#
# FABUI 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.
#
# FABUI is distributed in the hope that it wi | ll be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FABUI. If not, see <http://www.gnu.org/license... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from rcr.robots.dagucar.DaguCar import DaguCar
def main():
car = DaguCar( "/dev/rfcomm1", 500 )
car.MoveForward( 15 )
| car.Pause( 1000 )
car.MoveBackward( 15 )
car.Pause( 1000 )
car.MoveLeft( 15 )
car.Pause( 1000 )
car.MoveRight( 15 ) |
car.Pause( 1000 )
car.MoveForwardLeft( 15 )
car.Pause( 1000 )
car.MoveForwardRight( 15 )
car.Pause( 1000 )
car.MoveBackwardLeft( 15 )
car.Pause( 1000 )
car.MoveBackwardRight( 15 )
car.Pause( 1000 )
car.Stop()
car.Close()
###
main()
|
imp | ort sys
from mailpile.app import Mai | n
def main():
Main(sys.argv[1:])
if __name__ == "__main__":
main()
|
import os
from tito.builder import UpstreamBuilder
from tito.common import debug, run_command
class DistributionBuilder(UpstreamBuilder):
""" This class is used for building packages for distributions.
Parent class UpstreamBuilder build one big patch from upstream and create e.g.:
Patch0: foo-1.2.13-1-t... | .patch_files = output.split("\n")
for p_file in self.patch_files:
run_command("cp %s/%s %s" % (self.rpmbuild_gitcopy, p_file, self.rpmbuild_sourcedir))
(patch_number, patch_insert_index, patch_apply_index, lines) = self._patch_upstream()
for patch in self.patch_files:
l... | )
patch_number += 1
patch_insert_index += 1
patch_apply_index += 2
self._write_spec(lines)
|
# -*- coding: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.core.urlresolvers import reverse
from microblog import models
from microblog impo | rt settings
import os.path
class FeedsDict(dict):
"""
dict custom che solleva un FeedDoesNotExist al posto di un KeyError
"""
def __getitem__(self, k):
try:
return super(FeedsDict, self).__getitem__(k)
except KeyError:
raise FeedDoesNotExist()
languages = Feeds... | ettings.LANGUAGES)
languages[None] = settings.MICROBLOG_DEFAULT_LANGUAGE
class LatestPosts(Feed):
def get_object(self, request, lang_code=None):
return languages[lang_code]
def link(self, obj):
try:
path = reverse('microblog-feeds-latest')
except:
path = revers... |
"""Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... | factory.Sequence(
lambda n: "user{}@example.co | m".format(n)
)
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create photos for testing."""
class Meta(object):
"""Meta."""
model = Photo
title = factory.Sequence(lambda n: "photo{}".format(n))
image = SimpleUploadedFile(
name="testing.png",
content=ope... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.monkey}.
"""
from __future__ import division, absolute_import
from twisted.trial import unittest
from twisted.python.monkey import MonkeyPatcher
class TestObj:
def __init__(self):
self.foo = 'foo valu... | )
def test_empty(self):
"""
A monkey patcher without patches shouldn' | t change a thing.
"""
self.monkeyPatcher.patch()
# We can't assert that all state is unchanged, but at least we can
# check our test object.
self.assertEqual(self.originalObject.foo, self.testObject.foo)
self.assertEqual(self.originalObject.bar, self.testObject.bar)
... |
from eisoil.core.exception import CoreException
class ScheduleException(CoreException):
def __init__(self, desc):
self._desc = desc
def __str__( | self):
return "Schedule: %s" % (self._desc,)
class ScheduleOverbookingError(ScheduleException):
def __init__(self, schedule_subject, resource_id, start_time, end_time):
"""All parameters should be strings or be able to str(...) itself."""
super(ScheduleOverbookingError, self).__init__("Ther... | dy reservations for %s during [%s - %s] in the %s schedule." % (str(resource_id), str(start_time), str(end_time), str(schedule_subject)))
class ScheduleNoSuchReservationError(ScheduleException):
def __init__(self, reservation_id):
super(ScheduleNoSuchReservationError, self).__init__("Could not find reserva... |
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | ollowing disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of condit | ions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FIT... |
from __future__ import absolute_import
import weakref
import threading
import asyncore
import socket
from walky.objects import *
from walky.port import *
from walky.engine import *
class Client(object):
engine = None
settings = None
connection = None
port = None
engine_class = Engine
object... | self,*args,**kwargs):
""" Start the engine and the asyncore
"""
self.engine.start()
self.connection = self.engine.connection_new(*args,**kwargs)
def run(self):
pass
def on_readline(self,line):
try:
pass
except Exception as ex:
pas... | t(self,reg_obj_id):
return self.object_class(self.connection,reg_obj_id)
def close(self):
self.engine.shutdown()
|
# -*- coding: utf-8 -*-
import os
import codecs
import random
# this is the path of the folder that | will contain the tweet files
tweets_folder = os.path.join("D:", os.sep, "Documents", "PycharmProjects",
"easy_group_clas | sifier", "text_files")
# checks if previous path exists, if not, it creates it
if not os.path.isdir(tweets_folder):
os.makedirs(tweets_folder)
# the name of the file with clean tweets to scramble
filename = "technology"
tweets_file = os.path.join(tweets_folder, "%s.txt" % filename)
shuffled_file = os.pat... |
# generated from catkin/cmake/template/cfg-extras. | context.py.in
DEVELSPACE = 'FALSE' == 'TRUE'
INSTALLSPACE = 'TRUE' == 'TRUE'
CATKIN_DEVEL_PREFIX = '/home/pi/Documents/desenvolvimentoRos/de | vel'
CATKIN_GLOBAL_BIN_DESTINATION = 'bin'
CATKIN_GLOBAL_ETC_DESTINATION = 'etc'
CATKIN_GLOBAL_INCLUDE_DESTINATION = 'include'
CATKIN_GLOBAL_LIB_DESTINATION = 'lib'
CATKIN_GLOBAL_LIBEXEC_DESTINATION = 'lib'
CATKIN_GLOBAL_PYTHON_DESTINATION = 'lib/python2.7/dist-packages'
CATKIN_GLOBAL_SHARE_DESTINATION = 'share'
CATK... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2019) Hewlett Packard Enterprise Development LP
#
# 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... | ource.data = PRESENT_ENETS
self.resource.get_associated_profiles.return_value = ENET_ASSOCIATED_PROFILE_URIS
self.resource.get_associated_uplink_groups.return_value = ENET_ASSOCIATED_UPLINK_GROUP_URIS
profiles = []
for data in ENET_ASSOCIATED_PROFILES:
obj = mock.Mock()
... | ED_UPLINK_GROUPS:
obj = mock.Mock()
obj.data = data
uplinks.append(obj)
self.mock_ov_client.server_profiles.get_by_uri.side_effect = profiles
self.mock_ov_client.uplink_sets.get_by_uri.side_effect = uplinks
self.mock_ansible_module.params = PARAMS_GET_BY_NAM... |
f Equals(self, x):
if x is self: return 1
if self.has_service_call_name_ != x.has_service_call_name_: return 0
if self.has_service_call_name_ and self.service_call_name_ != x.service_call_name_: return 0
if self.has_total_amount_of_calls_ != x.has_total_amount_of_calls_: return 0
if self.has_total_a... | self.MergeFromString(contents)
def key(self): return self.key_
def set_key(self, x):
self.has_key_ = 1
self.key_ = x
def clear_key(self):
if self.has_key_:
self.has_key_ = 0
self.key_ = ""
def has_key(self): return self.has_key_
def value(self): return self.value_
def set_valu... | f.has_value_ = 1
self.value_ = x
def clear_value(self):
if self.has_value_:
self.has_value_ = 0
self.value_ = ""
def has_value(self): return self.has_value_
def MergeFrom(self, x):
assert x is not self
if (x.has_key()): self.set_key(x.key())
if (x.has_value()): self.set_value(x... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from lazagne.config.module_info import ModuleInfo
try:
from ConfigParser import RawConfigParser # Python 2.7
except ImportError:
from configparser import RawConfigParser # Python 3
from collections import OrderedDict
class Wifi(ModuleInfo):
d... | if os.getuid() == 0:
wireless_ssid = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for w in wireless_ssid:
cp = RawConfigParser()
cp.read(os.path.join(directory, w))
values = OrderedDic... | try:
values['SSID'] = cp.get('wifi', 'ssid')
values['Password'] = cp.get('wifi-security', 'psk')
pwd_found.append(values)
except Exception:
pass
else:
self.info('You need... |
import sys
import os.path
import subprocess
PY3 = sys.version >= '3'
from setuptools import setup, find_packages
# http://blogs.nopcode.org/brainstorm/2013/05/20/pragmatic-python-versioning-via-setuptools- | and-git-tags/
# Fetch version from git tags, and write to version.py.
# Also, when git is not available (PyPi package), use stored version.py.
version_py = os.path.join(os.path.dirname(__file__), 'dame', 'version.py')
try:
version_git = subprocess.check_output(
["git", "describe", "--always"]).rstrip()
... | t:
with open(version_py, 'r') as fh:
version_git = fh.read().strip().split('=')[-1].replace('"', '')
version_msg = ("# Do not edit this file, "
"pipeline versioning is governed by git tags")
with open(version_py, 'w') as fh:
fh.write(version_msg + os.linesep +
"__version__='... |
from distutils import log
import distutils.command.sdist as orig
import os
import sys
import io
import contextlib
from setuptools.extern import six, ordered_set
from .py36compat import sdist_add_defaults
import pkg_resources
_default_revctrl = list
def walk_revctrl(dirname=''):
"""Find all files under revisio... | on.has_pure_modules():
build_py = self.get_finalized_command('build_py') |
self.filelist.extend(build_py.get_source_files())
self._add_data_files(self._safe_data_files(build_py))
def _safe_data_files(self, build_py):
"""
Extracting data_files from build_py is known to cause
infinite recursion errors when `include_package_data`
is e... |
ms", {}) # type: Dict[str, Any]
if expand is not None:
query_parameters['$expand'] = _SERIALIZER.query("expand", expand, 'str')
if top is not None:
query_parameters['$top'] = _SERIALIZER.query("top", top, 'int')
if orderby is not None:
query_parameters['$orderby'] = _SERIALIZER.quer... | r: str
:param skus: A valid image SKU.
:type skus: str
:param version: A valid image SKU version.
:type version: str
:keyword callable cls: A custom type or function that will be pass | ed the direct response
:return: VirtualMachineImage, or the result of cls(response)
:rtype: ~azure.mgmt.compute.v2020_12_01.models.VirtualMachineImage
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineImage... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Techies' Stasis Trap
:copyright: (c) 2014 Runzhou Li (Leo)
:license: The MIT License (MIT), see LICENSE for details.
"""
import sys
from logging import Handler, NOTSET
_ref_atributes = | [
'%(levelname)s',
'%(name)s',
'%(pathname)s',
'%(module)s',
'%(funcName)s',
'%(lineno)d',
'%(message)s'
]
'''
Reference log format, best used with UniQueue or CountQueue
'''
R | EF_LOG_FORMAT = ':'.join(_ref_atributes)
class QueueHandler(Handler):
'''
Queue Logging Handler
Inherits standard logging.Handler that emits to any standard Queue
compatible implementations. Including the ones in techies.landmines module
'''
def __init__(self, q, level=NOTSET):
if s... |
# Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | ue
self.assertIsNot(getattr(phase, attr), getattr(second_phase, attr))
def testWithArgs(self):
phase = openhtf.PhaseInfo.WrapOrCopy(ExtraArgFunc)
phase = phase.WithArgs(input='input arg')
result = phase(self._phase_data)
self.assertEqual('input arg', result)
second_phase = phas... | ta)
self.assertEqual('input arg', first_result)
self.assertEqual('second input', second_result)
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform
import sys
import pytest
import spack
from spack.main import SpackCommand
python = SpackCommand('python... | ip() == sys.executable
def test_python_version():
out = python('-V')
| assert platform.python_version() in out
def test_python_with_module():
# pytest rewrites a lot of modules, which interferes with runpy, so
# it's hard to test this. Trying to import a module like sys, that
# has no code associated with it, raises an error reliably in python
# 2 and 3, which indicates... |
import sys
import argparse
import logging
import importlib
from .server import Server, build_endpoint_description_strings
from .access import AccessLogGenerator
logger = logging.getLogger(__name__)
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 8000
class CommandLineInterface(object):
"""
Acts as the main CLI en... |
)
# If verbosity is 1 or greater, or they told us explicitly, set up access log
access_log_stream = None
if args.access_log:
if args.access_log == "-":
access_log_stream = sys.stdout
else:
access_log_stream = open(args.access_log, ... |
access_log_stream = sys.stdout
# Import channel layer
sys.path.insert(0, ".")
module_path, object_path = args.channel_layer.split(":", 1)
channel_layer = importlib.import_module(module_path)
for bit in object_path.split("."):
channel_layer = getattr(chann... |
class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : a list of length 2, [index1, index2]
"""
def searchRange(self, A, target):
# write your code here
res = []
l, r = 0, len(A) - 1
while l <= r:
m = (l ... | else:
l = l + 1
res.append( | r)
if res[0] > res[1]: return [-1, -1]
return res
|
from ajenti.api import *
@interface
class UserSyncProvider (BasePlugin):
allows_renaming = False
syncs_root = False
def | test(self):
return False
def check_passw | ord(self, username, password):
return False
def sync(self):
pass |
f):
self.cts = HttpCtsRetriever("http://domainname.com/rest/cts")
def test_request_Cts_getCapabilities_arguments(self):
""" Tests that methods getCapabilities maps correctly to request"""
with patch('requests.get') as patched_get:
self.cts.getCapabilities(inventory="inventory")
... | rn="urn", inventory="inventory", leve | l=1)
patched_get.assert_called_once_with(
"http://domainname.com/rest/cts", params={
"inv": "inventory",
"request": "GetValidReff",
"level": "1",
"urn": "urn"
}
)
with patch('r... |
prefiltered_projects[p_id] = p_info
else:
if filter_projects == 'aborted':
filtered_projects[p_id] = p_info
else:
filtered_projects = projects
if filter_projects == 'pending':
for p_id, p_info in prefiltered_... | project = {
"url": '/project/'+row.key[1],
"name": row.value['project_name']
}
projects.append(project);
return projects
def prettify_css_names(s):
return s.replace("(","_").replace(")", "_")
class ProjectsDataHandler(Project... | set_header("Content-type", "application/json")
self.write(json.dumps(self.list_projects(self.get_argument('list', 'all'))))
class ProjectsFieldsDataHandler(ProjectsBaseDataHandler):
""" Serves all fields occuring in the values of the ProjectsDataHandler
json object.
Loaded through /api/v1/project... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
corto = 10
largo = long(corto)
print type(cor | to) |
print type(largo)
|
.Instance(name=self.INSTANCE_NAME)
klass = self._getTargetClass()
with self.assertRaises(ValueError):
klass.from_pb(instance_pb, client)
def test_name_property(self):
client = _Client(project=self.PROJECT)
instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATIO... | tub = _FakeStub(response_pb)
# Create expected_result.
expected_result = MUT.Operation('create', self.OP_ID, OP_BEGIN,
self.LOCATION_ID, instance=instance)
# Create the mocks.
prep_create_called = []
def mock_prep_create_req(instance):
... | return request_pb
process_operation_called = []
def mock_process_operation(operation_pb):
process_operation_called.append(operation_pb)
return self.OP_ID, self.LOCATION_ID, OP_BEGIN
# Perform the method and check the result.
with _Monkey(MUT,
... |
s, fixtures):
"""Add Awair devices to hass, using specified fixtures for data."""
entry = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG)
with patch("python_awair.AwairClient.query", side_effect=fixtures):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.... | "awair_index": 0.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_illuminance",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}",
"441.7",
{ATTR_UNIT_OF_MEASUREMENT: LIGHT_LUX},
)
# The Mint does not have a CO2 ... | """Test expected sensors on an Awair glow."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GLOW_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = er.async_get(hass)
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENS... |
d_language_code(endpoint, values):
if flask.g.lang_code is not None and \
app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
values.setdefault('lang_code', flask.g.lang_code)
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
... | oute('/bar/', endpoint='bar')
def for_bar():
return flask.request.endpoint
@app.ro | ute('/bar/123', endpoint='123')
def for_bar_foo():
return flask.request.endpoint
with app.test_request_context():
assert flask.url_for('foo') == '/foo/'
assert flask.url_for('bar') == '/bar/'
assert flask.url_for('123') == '/bar/123'
c = app.test... |
"""
WSGI config for project.
It exposes the WSG | I callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployme | nt/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
application = get_wsgi_application()
|
import sys
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drawing Lines")
screen.fill((0, 80, 0))
# draw the line |
color = 100, 255, 200
width = 8
pygame.draw.line(screen, color, (100, 100), (500, 400), width)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type in (QUIT, KEYDOWN):
| sys.exit() |
# Part of django-hookbox
# Copyright 2011, Duane Griffin <duaneg@dghda.com>
from django.conf import settings
from django.dispatch import Signal
from django.http import HttpResponse
from django.template import loader, RequestContext
from django.views.decorators.csrf import csrf_exempt
import json
import logging
import... | elif not oneresult is None:
logger.warn("multiple results returned from %s callback", op)
return result
def whcallback(arg):
'''
Decorator for functions which handle webhoo | k callbacks.
All functions are called with the operation type and user as the first two
arguments. Operations on a channel (i.e. not connect/disconnect) will be
called with a channel name as the third argument, and publish will be
called with the payload as the fourth argument.
If a string argumen... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright © 2014 Daniel Tschan <tschan@puzzle.ch>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foun... | t-Length', str(len(response_body)))
]
start_response(status, response_headers)
return [response_bod | y]
|
import bottl | e
@bottle.route('/')
def home_page():
mythings = ['apple','orange','banana','peach']
return bottle.template('hello_world', username='Todd',things=mythings)
bottle.debug(True)
bottle.run(host='localhost', p | ort=8082)
|
spacing (kwarg, float in [0,1], default=0.2 / cols):
Space between subplot columns.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing (kwarg, float in [0,1], default=0.3 / rows):
Space between subplot rows.
Applies to all rows (use 'specs' subplot-depe... | figure = figur | e_or_data.to_dict()
validated = True
else:
raise exceptions.PlotlyError(
"The `figure_or_data` positional "
"argument must be "
"`dict`-like, `list`-like, or an instance of plotly.graph_objs.Figure"
)
if validate_figure and not validated:
try... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2... | ject.mode | ls import Project
from pootle_statistics.models import Submission
def get_items(request, model, get_last_action, name_func):
items = []
if not check_permission('view', request):
return items
for item in model.objects.iterator():
stats = get_raw_stats(item)
translated_percentage =... |
se");
# 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 WARR... | 00),
]
wide_columns = base_columns + crossed_columns
deep | _columns = [
age,
education_num,
capital_gain,
capital_loss,
hours_per_week,
tf.feature_column.indicator_column(workclass),
tf.feature_column.indicator_column(education),
tf.feature_column.indicator_column(marital_status),
tf.feature_column.indicator_column(relation... |
subclass to be used.
#
# This should allow easy re-use of the IPKernelApp entry point to configure and
# launch kernels other than IPython's own.
# c.IPKernelApp.kernel_class = 'IPython.kernel.zmq.ipkernel.Kernel'
# Run the module as a script.
# c.IPKernelApp.module_to_run = ''
# The date format used by logging form... | ecified by absolute path.
# c.IPKernelApp.connection_file = ''
# If true, IPython will populate the user namespace with numpy, pylab, etc. and
# an ``import *`` is done from numpy and pylab, when using pylab mode.
#
# When False, pylab mode should not import any names into the user namespace.
# c.IPKernelApp.pylab_im... | logging
# configuration (through profiles), history storage, etc. The default is usually
# $HOME/.ipython. This options can also be specified through the environment
# variable IPYTHONDIR.
# c.IPKernelApp.ipython_dir = u''
# Configure matplotlib for interactive use with the default matplotlib backend.
# c.IPKernelApp.... |
import pygame as pg
from i18n import i18n
class BaseScene(object):
"""
Parent class for individual game states to inherit from.
"""
def __init__(self, helpers=None):
self.done = False
self.quit = False
self.sounds = helpers['sounds'] if helpers else None
self.assets = he... | te to state
"""
self.persist = persistent
def get_event(self, event):
"""
Handle a single event passed by the Game object.
"""
pass
def update(self, dt):
"""
Update the state. Called by the Game object once
per frame.
dt: time | since last frame
"""
pass
def draw(self, surface):
"""
Draw everything to the screen.
"""
pass
|
from behave import *
import operator
from django.db.models import Q
use_step_matcher("parse")
@given('Exists album at group "{group_name}" by "{username}"')
def step_impl(context, group_name, username):
from django.contrib.auth.models import User
user = User.objects.get(username=username)
from musicseaapp... | ing the details page for album at group "{group_name}" by "{username}"')
def step_impl(context, group_name, username):
q_list = [Q((attribute, context.table.rows[0][attribute])) for attribute in context.table.headings]
from django.contrib.auth.models import User
q_list.append(Q(('user', User.objects.get(use... | me=username))))
from musicseaapp.models import Group
q_list.append(Q(('group', Group.objects.get(name=group_name))))
from musicseaapp.models import Album
album = Album.objects.filter(reduce(operator.and_, q_list)).get()
assert context.browser.url == context.get_url(album)
@then('There are {count:n}... |
import glob
import sys
import string
import Bio.PDB
def parse_noe(filename):
f = open(filename, 'r')
noe_pairs = []
for line in f.readlines():
res_a = int(string.split(line)[2])
res_b = int(string.split(line)[7])
noe_pair = [res_a, res_b]
if noe_pair n... | noe_file = sys.argv[2]
count_restraints(noe_file)
cmd.load(native_pdb, "native")
cmd.hide("all")
cmd.show("cartoon", "native")
if noe:
for pair in parse_noe(noe_file):
cmd.distance("noe", "native and resi %i and name ca" % (pair[0]),
"native and resi %i and name ca" % (pai... | abels", "noe")
cmd.color("grey", "native")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of HSPlasma.
#
# HSPlasma 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... | rm.UnloadPage(page.location)
if options.checkrepack:
overprint("Comparing "+file+"...")
compareFiles(file, kTmpFile, options.ignorephysics)
if not option | s.keeprepack: os.remove(kTmpFile)
elif file.lower().endswith(".age"):
age = rm.ReadAge(file, True) # readPages=True
for pageNum in range(0, age.getNumPages()):
loc = age.getPageLoc(pageNum, rm.getVer())
page = rm.FindPage(loc)
if (page == N... |
import shlex
import textwrap
from ert_gui.shell.libshell import autoCompleteList, ShellFunction, ShellProperty, widthAsPercentageOfConsoleWidth, getTerminalSize
class ShellCollection(object):
command_help_message | = "The command: '%s' supports the following keywords:"
def __init__(self, name, parent=None, description="No description available"):
super(ShellCollection, self).__init__()
self.__name = name
self.__parent = None |
self.__description = description
if parent is not None:
self.setParent(parent)
parent.addChild(self)
self.__collection = {}
self.__model_tracker = {}
self.__children = []
def setParent(self, parent):
if not hasattr(parent, "shellContext"):
... |
import os
import json
import tempfile
import webbrowser
import designer
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, ConfigParser, StringProperty
from kivy.uix.settings import Settings, InterfaceWithSidebar, MenuSidebar,\
ContentPanel, SettingsPanel
... | '''CodeInput with buildozer.spec text.
Instance of :class:`kivy.config.ObjectProperty` and defaults to None
'''
lbl_error = ObjectProperty(None)
'''(internal) Label to display errors.
Instance of :class:`kivy.config.ObjectProperty` and defaults to None
'''
spec_path = StringProperty( | '')
'''buildozer.spec path.
Instance of :class:`kivy.config.StringProperty` and defaults to ''
'''
__events__ = ('on_change', )
def __init__(self, **kwargs):
super(SpecCodeInput, self).__init__(**kwargs)
self.text_input.lexer = IniLexer()
def load_spec(self, *args):
''... |
from pyramid.view | import view_config
from pyramid.config import Configurator
@view_config(route_name='text', renderer='string')
def text(request):
return 'Hello, World!'
config = Configurator()
config.add_route('text', '/text')
config.scan()
app = config.make_wsgi_app | ()
|
iteral
def __init__ (self, value):
self.value = value
if is_a (value, VAR):
import pdb; pdb.set_trace()
def __repr__ (self):
return 'L%s' % (repr(self.value))
def __cmp__ (self, other):
if is_a (other, literal):
v = self.value
o = other.v... | es1.append ((pats[0].subs + pats[1:], code))
if len (pats[0].subs) != arity:
raise MatchError ("arity mismatch in variant pattern", rules0)
for i in rang | e (len (pats[0].subs)):
sub = pats[0].subs[i]
if not (is_a (sub, variable) and sub.name == '_'):
wild[i] = False
# if every pattern has a wildcard for this arg of the constructor,
# then use '_' rather than the symbol we generated... |
er_corrupt_torrent: This event is emitted when a corrupt .torrent file in the watch folder is found.
The dictionary contains the name of the corrupt torrent file.
- new_version_available: This event is emitted when a new version of Tribler is available.
- tribler_started: An indicator that Tribler has com... | The event contains
the infohash and the dispersy id of the channel which contained the removed torrent.
- torrent_finished: A specific torrent has finished downloading. The event includes the infohash and name of the
torrent that has finished downloading.
- torrent_error: An error has occurred duri... | urred in Tribler. The event includes a readable string of the error.
- market_ask: Tribler learned about a new ask in the market. The event includes information about the ask.
- market_bid: Tribler learned about a new bid in the market. The event includes information about the bid.
- market_ask_timeout: An ... |
"""Tests for the template tests."""
import unittest
from grow.templates import tests
class BuiltinTestsTestCase(unittest.TestCase):
def test_subset_filter(self):
"""Provided value is a subset when has all the required values."""
value = ['banana', 'apple']
test_value = ['banana']
... | def test_subset_filter_none(self):
"""Provided value is a subset when both are blank."""
value = []
test_value = []
self.assertTrue(tests.is_subset_of(value, test_value))
def test_superset_filter(self):
"""Provided value is a superset when missing some of the values."""
... | st_value))
def test_superset_filter_equal(self):
"""Provided value is a superset when equal."""
value = ['banana']
test_value = ['banana']
self.assertTrue(tests.is_superset_of(value, test_value))
def test_superset_filter_not(self):
"""Provided value is not a superset wh... |
import pytest
from cfme.containers.provider import ContainersProvider
from cfme.markers.env_markers.provider import providers
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.providers import ProviderFilter
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.usefixtures... | if node else
pytest.skip("Could not determine node of {}".format(provider.name)))
if cockpit:
appliance.server.browser.refresh()
assert not view.toolbar.web_console.disabled
view.toolbar.web_console.click()
webconsole = node.vm_console
... | assert view.is_displayed
view.flash.assert_no_error()
else:
appliance.server.browser.refresh()
assert view.toolbar.web_console.disabled
|
#!/ | usr/bin/env python
import os
import sys
if __name__ == "__main__":
# testing environment
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blastplus.test_settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sy | s.argv)
|
exec_command --- execute command in a specified directory and
in the modified environment.
find_executable --- locate a command using info from environment
variable PATH. Equivalent to posix `which`
command.
Author: Pearu Peterson <pearu@cens.ioc.ee>
Cr... | entError:
# Return 127, as os.spawn*() and /bin/sh do
return 127, ''
text, err = proc.communicate()
# Another historical oddity
if text[-1:] == '\n':
text = text[:-1]
if use_tee and text:
print(text)
return proc.returncode, text
def _quote_arg(arg):
"" | "
Quote the argument for safe use in a shell command line.
"""
# If there is a quote in the string, assume relevants parts of the
# string are already quoted (e.g. '-I"C:\\Program Files\\..."')
if '"' not in |
ral configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensi... | exin | fo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'EbookLib', u'EbookLib Documentation',
u'Aleksandar Erkalovic', 'Eb... |
#common sets | up the conduit environment
from common import *
#setup test
test = SimpleSyncTest()
#Setup the key to sync
gconf = test.get_dataprovider("GConfTwoWay")
gconf.module.whitelist = ['/apps/metacity/general/num_workspaces']
folder = test.get_dataprovider("TestFolderTwoWay")
test.prepare(gconf, folder)
test.set_two_way_po... |
for i in (1,2,3,4):
if i > 1:
#Now modify the file
f = folder.module.get(
folder.module.get_all()[0]
)
f._set_file_mtime(datetime.datetime(2008,1,i))
a,b = test.sync()
aborted,errored,conflicted = test.get_sync_result()
ok("Sync #%s: Completed w... |
import re
from vogen.voparser import VoParser, VoVariable
class AS3VoParser( VoParser ):
def parse( self, input_string, verbose ):
self.input_string = input_string
self.verbose = verbose
class_names = re.findall(r"class (\w+)", self.input_string );
#Find the class_... | ass_name ):
return_text = self.input_string
#Rename all existing variables
for variable in variables :
return_text = return_text.replace( variable.variable_name, "_"+variable.variable_name )
#Strip the last bracket
return_text = return_text.rstrip('}... | riables :
return_text += "\n\t\t\t" + variable.variable_name + " : " + variable.variable_type + " ,"
return_text = return_text.rstrip(', ')
return_text += "\n\t\t){"
for variable in variables :
return_text += "\n\t\t\tthis._" + variable.variable_name + " = " + variable.va... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from professor.models import Professor, DiaSemana, DisponibilidadeAula
from professor.models import Pro... | :
def adicionaDisponibilida | de(self):
p = Professor.objects.get(id=1)
p.informarDisponibilidade("qua", "14:30")
p = Professor.objects.get(id=1)
result = p.getDisponibilidadeAulas()
self.assertEqual(result[0].hora, "14:30")
self.assertEqual(result[0].diaSemana.nome_curto, "qua")
... |
from pikka_bird_collector.parsers.table import Table as Parser
from .base_port_command import BasePortCommand, Base
class Mysql(BasePortCommand):
"""
Collector for MySQL (https://www.mysql.com/).
The collector is enabled whenever non-empty settings are passed.
Multiple instances r... |
if settings.get('user'):
c.append('--user=%s' % settings['user'])
if settings.get('password'):
c.append('--password=%s' % settings['password'])
return c
def collect_port(self, po | rt, settings):
metrics = {}
o = self.command_output(port, settings, self.CMD_SHOW_STATUS)
parser = Parser(
converter_key=Base.parse_str_setting_key,
converter_value=Mysql.__parse_str_setting_value)
ms = parser.parse(o)
if len(ms):
... |
import itertools
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_allclose
from pvlib import atmosphere
from pvlib import solarposition
latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700
times = pd.date_range(start='20140626', end='20140626', freq='6h', tz=tz)
e... | osphere.pres2alt(100000)
def test_alt2press():
atmosphere.pres2alt(1000)
@pytest.mark.parametrize("model",
['simple', 'kasten1966', 'youngirvine1967', 'kastenyoung1989',
'gueymard1993', 'young1994', 'pickering2002'])
def test_airmass(model):
out = atmosphere.relativeairmass(ephem_data['zenith'], mo... | = atmosphere.relativeairmass(ephem_data['zenith'].values, model)
assert isinstance(out, np.ndarray)
def test_airmass_scalar():
assert not np.isnan(atmosphere.relativeairmass(10))
def test_airmass_scalar_nan():
assert np.isnan(atmosphere.relativeairmass(100))
def test_airmass_invalid():
with pytes... |
import m | atplotlib.pyplot as plt
import numpy as np
def logHist(X, N=30,fig=None, noclear=False, pdf=False, **kyw | ds):
'''
Plot logarithmic histogram or probability density function from
sampled data.
Args:
X (numpy.ndarray): 1-D array of sampled values
N (Optional[int]): Number of bins (default 30)
fig (Optional[int]): Figure number (default None)
noclear (Optioanl[bool]): Clear fi... |
"""
Create quiz TimeSpecialCase for all students in a particular lab/tutorial section.
Usage will be like:
./manage.py special_case_tutorial 2020su-cmpt-120-d1 q1 D101 '2021-10-07T09:30' '2021-10-07T10:30'
"""
import datetime
from django.core.management.base import BaseCommand
from django.db im | port transaction
from iso8601 import iso8601
from coredata.models import CourseOffering, Member
from quizzes.models im | port Quiz, TimeSpecialCase
def parse_datetime(s: str) -> datetime.datetime:
return iso8601.parse_date(s).replace(tzinfo=None)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('offering_slug', type=str, help='CourseOffering slug')
parser.add_argument('activity_... |
# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
from captcha import client
class ReCaptcha(forms.widgets.Widget):
if getattr(settings, "RECAPTCHA_NOCAPTCHA", False):
recaptcha_response_name = 'g-recaptcha-response'
re... | .RECAPTCHA_PUBLIC_KEY
self.use_ssl = use_ssl if use_ssl is not None else getattr(
settings, 'RECAPTCHA_USE_SSL', False)
self.js_attrs = attrs
super(ReCaptcha, self).__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
return mark_safe(u'%s' % client.displ... | lf, data, files, name):
return [
data.get(self.recaptcha_challenge_name, None),
data.get(self.recaptcha_response_name, None)
]
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | f test_fp16_build():
dtype = "float16"
if not tvm.module.enabled("cuda") or not tvm.gpu(0).exist:
print("skip because cuda is not enabled.")
return
ctx = tvm.gpu(0)
| if dtype == "float16" and not have_fp16(ctx.compute_version):
print("skip because gpu does not support fp16")
return
x = relay.var("x", dtype=dtype, shape=(4, 4))
y = relay.var("y", dtype=dtype, shape=(4, 4))
z = x + y
func = relay.Function([x, y], z)
X = tvm.nd.array(np.random.u... |
"""Support for Hangouts."""
import logging
from hangups.auth import GoogleAuthError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.conversation.util import create_matcher
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASS... | TOKEN),
hass.data[DOMAIN][CONF_INTENTS],
| hass.data[DOMAIN][CONF_DEFAULT_CONVERSATIONS],
hass.data[DOMAIN][CONF_ERROR_SUPPRESSED_CONVERSATIONS],
)
hass.data[DOMAIN][CONF_BOT] = bot
except GoogleAuthError as exception:
_LOGGER.error("Hangouts failed to log in: %s", str(exception))
return False
dispatcher.... |
from sys import argv
fo | r line in ope | n(argv[1]):
tweet_id, hashtags, hashtags_count, user_id, created_at, followers_count, score, text = line.replace('\n', '').split('\t')
print ','.join([tweet_id, user_id, created_at, followers_count, score, text])
|
delClass(self):
'''reimplemented from :class:`TaurusBaseWidget`'''
return taurus.core.taurusdevice.TaurusDevice
def onChooseScanDirButtonClicked(self):
ret = Qt.QFileDialog.getExistingDirectory (self, 'Choose directory for saving files', self.ui.pathLE.text())
if ret:
se... | widget'''
self._localConfig = conf
#set the Channel Editor
activeMntGrpName = self._localConfig['ActiveMntGrp'] or ''
if activeMntGrpName in self._localConfig['MntGrpConfigs']:
mgconfig = self._localConfig['MntGrpConfigs'][activeMntGrpName]
self.ui.cha | nnelEditor.getQModel().setDataSource(mgconfig)
#set the measurement group ComboBox
self.ui.activeMntGrpCB.clear()
mntGrpLabels = []
for _, mntGrpConf in self._localConfig['MntGrpConfigs'].items():
# get labels to visualize names with lower and upper case
mntGrpLa... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF | DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/loot_schematic/shared_geonosian_reinforcement_core_schematic.iff"
result.attribute_template_id = -1
result.stfNa | me("craft_weapon_ingredients_n","geonosian_reinforcement_core_schematic")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
from .decorators import Vectorize, GU | Vectorize, vectorize, guvectorize
from ._internal import PyUFunc_None, PyUFunc_Zero, PyUFunc_One
from . import _internal, array_exprs
if hasattr(_internal, 'PyUFunc_ReorderableNone'):
PyUFunc_ReorderableNone | = _internal.PyUFunc_ReorderableNone
del _internal, array_exprs
def _init():
def init_vectorize():
from numba.cuda.vectorizers import CUDAVectorize
return CUDAVectorize
def init_guvectorize():
from numba.cuda.vectorizers import CUDAGUFuncVectorize
return CUDAGUFuncVectorize
... |
tion with
objects of type :class:`.MutableComposite`.
Supporting Pickling
--------------------
As is the case with :class:`.Mutable`, the :class:`.MutableComposite` helper
class uses a ``weakref.WeakKeyDictionary`` available via the
:meth:`MutableBase._parents` attribute which isn't picklable. If we need to
pickl... | stablish a global
ass | ociation.
.. warning::
The listeners established by this method are *global*
to all mappers, and are *not* garbage collected. Only use
:meth:`.as_mutable` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
... |
#!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import messagebird
# ACCESS_KEY = ''
# MESSAGE_ID = ''
try:
ACCESS_KEY
except NameError:
print('You need to set an ACCESS_KEY constant in this file')
sys.exit(1)
try:
MESSAGE_ID
except NameError:
print('Yo... | e object information.
print('\nThe following information was returned as a VoiceMessage object:\n')
print(' id : %s' % vmsg.id)
print(' href : %s' % vmsg.href)
print(' originator : %s' % vmsg.originator)
print(' body : %s' % vmsg.body)
print(' reference ... | sg.language)
print(' voice : %s' % vmsg.voice)
print(' repeat : %s' % vmsg.repeat)
print(' ifMachine : %s' % vmsg.ifMachine)
print(' scheduledDatetime : %s' % vmsg.scheduledDatetime)
print(' createdDatetime : %s' % vmsg.createdDatetime)
print(' recipients : %s\n... |
ormat(user._id, token))
res = res.follow()
assert_equal(res.status_code, 302)
assert_in('dashboard', res.location)
assert_equal(len(mock_mail.call_args_list), 1)
session = Session.find(
Q('data.auth_user_id', 'eq', user._id)
).sort(
'-date_modifi... | //localhost/')
assert_in(login_url, resp.headers.get('location'))
@mock.patch(' | website.project.decorators._kwargs_to_nodes')
@mock.patch('framework.auth.decorators.Auth.from_kwargs')
def test_must_have_permission_true(self, mock_from_kwargs, mock_to_nodes):
project = ProjectFactory()
project.add_permission(project.creator, 'dance')
mock_from_kwargs.return_value = A... |
import json
import etcd
from tendrl | .gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
def start(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'... | utes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))... |
#!/usr/bin/python
#
# Copyright 2013 Google 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 b... | verning permissions and
# limitations under the Lic | ense.
"""This example gets a user team association by the user and team ID.
To determine which teams exist, run get_all_teams.py. To determine which users
exist, run get_all_users.py.
Tags: UserTeamAssociationService.getUserTeamAssociation
"""
__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'
# Locate the client l... |
import re
from ert_gui.ide.keywords.definitions import ArgumentDefinition
class RangeStringArgument(ArgumentDefinition):
NOT_A_VALID_RANGE_STRING = "The input should be of the type: <b><pre>\n\t1,3-5,9,17\n</pre></b>i.e. integer values separated by commas, and dashes to represent ranges."
VALUE_NOT_IN_RANGE ... | ringArgument.VALUE_NOT_IN_RANGE % (self.__max_value - 1))
break
if number_match and self.__max_value is not None:
num = int(number_match.group(1))
if num >= self.__max_value:
validati | on_status.setFailed()
validation_status.addToMessage(RangeStringArgument.VALUE_NOT_IN_RANGE % (self.__max_value - 1))
break
validation_status.setValue(token)
return validation_status
|
seful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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 library; if not, write to the Free ... | ***', repr(newamount), repr(username)
### Buddy Messages
def hearMessage(self,username,message,autoreply):
if autoreply:
message='<AUTO-REPLY>: '+message
self.chat.getConversation(self.getPerson(username)
).showMessage(dehtml(message))
def updateBudd... | lass,away):
if away:
status=AWAY
elif online:
status=ONLINE
else:
status=OFFLINE
self.getPerson(username).setStatusAndIdle(status, idletime)
### Group Chat
def chatJoined(self, roomid, roomname, users):
self.roomID[roomname]=roomid
... |
#!/usr/bin/env python
# -*- coding=utf8 -*-
"""clear the mysql database yjy_archtecture tables in aa.txt"""
import MySQLdb as mdb
db_conn = mdb.connect("localhost","root","HEkgDDZZ","yjy_human") |
cursor = db_conn.cursor()
with open("/root/scripts/clear_human_sql.tables") as f:
tables = f.readlines()
print tables
try:
for table in tables:
tb = table.strip()
print tb
sql = """TRUNCATE TABLE """+ tb
cursor.execute(sql)
data = cursor.fetchall()
print data
sql1 = """select * from """+ tb
... | nt e
db_conn.close()
|
#!/usr/bin/env python3
# Copyright (c) 2017-2020 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 message sending before handshake completion.
Before receiving a VERACK, a node should not send anything but VERSION/VERACK
and feature negotiation messages (WTXIDRELAY, SENDADDRV2).
This test conn | ects to a node and sends it a few messages, trying to entice it
into sending us something it shouldn't."""
import time
from test_framework.messages import (
msg_getaddr,
msg_ping,
msg_version,
)
from test_framework.p2p import (
P2PInterface,
P2P_SUBVERSION,
P2P_SERVICES,
P2P_VERSION_RELAY,... |
#!/usr/bin/python -Wall
# ================================================================
# John Kerl
# kerl.john.r@gmail.com
# 2008-02-06
# ================================================================
from __future__ import division # 1/2 = 0.5, not 0.
import sys
import randc_m # For random complex scalars
impo... | in range(0, n):
for j in range(0, i):
A[i][j] = conj(A[j][i])
return A
# ------- | ---------------------------------------------------------
def randxxt(n):
A = randmatc(n, n)
return A.transpose() * A
|
from django.db import | models
from .user import User
from .post import Post
class Medal(models.Model):
rank = models.IntegerField()
user = models.ForeignKey(User, related_name='medals')
post = models.OneToOneField(Post, on_delete=models.C | ASCADE, related_name='medal')
def __str__(self):
return "%s %s" % (self.post.title, self.rank)
|
.dirpath, self.file])
def __eq__(self, other):
return self.path == other.path
def __lt__(self, other):
return self.path < other.path
@property
def path(self):
return os.path.join(self.dirpath, self.file)
def process(self, command, domain):
"""
... | --keyword=ungettext_lazy:1,2',
'--keyword=pgettext:1c,2',
'--keyword=npgettext:1c,2,3',
'--keyword=pgettext_lazy:1c,2',
| '--keyword=npgettext_lazy:1c,2,3',
'--output=-'
] + command.xgettext_options
args.append(work_file)
else:
return
msgs, errors, status = gettext_popen_wrapper(args)
if errors:
if status != STATUS_OK:
if is_te... |
from steerclear import app
from steerclear.forms import RideForm
from steerclear.models import *
import unittest, flask
"""
RideFormTestCase
----------------
Test class for the RideForm class
"""
class RideFormTestCase(unittest.TestCase):
"""
submit_form
-----------
helper method to submit a RideForm ... | d_payload[u'num_passengers'] = 0
result = self.submit_form(bad_payload)
self.assertFalse(result)
bad_payload[u'num_passengers'] = -1
result = self.submit_form(bad_payload)
self.assertFalse(result)
bad_payload[u'num_passengers'] = -100
result = self.submit_form(b... | ad[u'num_passengers'] = 100
result = self.submit_form(bad_payload)
self.assertFalse(result)
|
'''
urlresolver XBMC Addon
Copyright (C) 2017
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distribu... | ):
print "print UR BitPorno self, host, media_id", self,host, media_id
print "print return", self._default_get_url(host, media_id, template='http:/ | /{host}/?v={media_id}')
return self._default_get_url(host, media_id, template='http://{host}/?v={media_id}')
return "https://www.bitporno.com/?v=FM11XRJLMP"
@classmethod
def _is_enabled(cls):
return True
|
from django.conf.urls import url
from . import views
app_name = 'persons'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^thanks/$', | views.thanks, name='thanks'),
url(r'^upload/$', views.upload_file, name='upload_file'),
url(r' | ^success/$', views.success, name='success'),
url(r'^uploadImage/$', views.uploadImage, name='uploadImage'),
]
|
import cStringIO as StringIO
import pytest
import time
from Connection import ConnectionServer
from Conn | ection import Connection
from File import FileServer
@pytest.mark.usefixtures("resetSettings")
@pytest.mark.usefixtures("resetTempSettings")
class TestFileRequest:
def testGetFile(self, file_server, site):
file_server.ip_incoming = {} # Reset flood protection
client = ConnectionServer("127.0.0.1"... |
connection = client.getConnection("127.0.0.1", 1544)
file_server.sites[site.address] = site
response = connection.request("getFile", {"site": site.address, "inner_path": "content.json", "location": 0})
assert "sign" in response["body"]
# Invalid file
response = connect... |
from gonullu.farm import Farm
f | rom gonullu.docker import Docker
from gonullu.volunteer import Volunt | eer
from gonullu.log import Log
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.