prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-10-27 09:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('images', '0002_alter_fields'),
]
operations = [
migrations.AlterField(
model_name='image',
name='description',
field=models.TextField(blank=True, default=''),
| ),
]
|
chive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QRectF
from qgis.PyQt.QtGui import QColor
from qgis.core import (QgsLayoutItemLegend,
QgsLayoutItemMap,
QgsLayout,
QgsMapSettings,
QgsVectorLayer,
... | oint_layer = QgsVectorLayer(point_path, 'points', 'ogr')
QgsProject.instance | ().addMapLayers([point_layer])
s = QgsMapSettings()
s.setLayers([point_layer])
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
... |
import unittest
from coval.es import *
class CodeValidatorEsTestCase(unittest.TestCase):
def setUp(self):
pass
def test_cif(self):
self.assertTrue(cif('A58818501'))
self.assertTrue(cif('B00000000'))
self.assertTrue(cif('C0000000J'))
self.assertTrue(cif('D00000000'))
... | se(ssn('309221363823'))
self.assertFalse(ssn('313221363822'))
def test_postcode(self):
self.assertTrue(postcode('28080'))
self.assertTrue(postcode('355 | 00'))
self.assertFalse(postcode('59000'))
self.assertTrue(postcode('12012'))
self.assertTrue(postcode('25120'))
self.assertFalse(postcode('10'))
self.assertFalse(postcode('X123'))
if __name__ == '__main__':
unittest.main()
|
from django.shortcuts import ren | der
from django.http import Http404
def index(request):
return render(request, 'map/index.ht | ml')
|
# You will need maestro.py from https://github.com/FRC4564/Maestro
#
# This is also just a place holder, it has not be tested with an actual
# bot.
import sys
import time
try:
import hardware/maestro
except ImportError:
print "You are missing the maestro.py file from the hardware subdirectory."
print "Plea... | et(0, 6000)
servo.setTarget(1, 6000)
def move(args):
direction = args['command' | ]
if direction == 'F':
servo.setTarget(0, 12000)
servo.setTarget(1, 12000)
time.sleep(straightDelay)
servo.setTarget(0, 6000)
servo.setTarget(1, 6000)
elif direction == 'B':
servo.setTarget(0, 0)
servo.setTarget(1, 0)
time.sleep(straightDe... |
# -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (), name='announcements_feed'),
url(r'^course/(?P<course_slug>[-\w]+)/clone-activity/$', 'clone_activity', name='course_clone_activity'),
# Teacher's course administration
url(r'^course/(?P<course_slug>[-\w]+)/teacheradmin/',
include('moocng.teacheradmin.urls')),
| )
|
zone_file = '/etc/bind/zones/db.circulos | podemos.in | fo'
|
# -*- coding: utf-8 -*-
"""
Display network speed and bandwidth usage.
Configuration parameters:
cache_timeout: refresh interval for this module (default 2)
format: display format for this module
*(default '{nic} [\?color=down LAN(Kb): {down}↓ {up}↑]
[\?color=total T(Mb): {download}↓ {upload}↑ ... | own}↓ {up}↑] ' + \
u'[\?color=total T(Mb): {download}↓ {upload}↑ {total}↕]'
nic = None
thresholds = {
'down': [(0, 'bad'), (30, 'degraded'), (60, 'good')],
'total': [(0, 'good'), (400, 'degraded'), (700, 'bad')]
}
class Meta:
def deprecate_function(config):
r... | (0, 'bad'),
(config.get('low_speed', 30), 'degraded'),
(config.get('med_speed', 60), 'good')
],
'total': [
(0, 'good'),
(config.get('low_traffic', 400), 'degraded'),
... |
from django.core.management import BaseCommand
from newsfeed.models import Entry
from premises.m | odels import Contention
class Command(BaseCommand):
def handle(self, *args, **options):
for contention in Contention.objects.all():
Entry.objects.create(
object_id=contention.id,
news_ty | pe=contention.get_newsfeed_type(),
sender=contention.get_actor(),
related_object=contention.get_newsfeed_bundle(),
date_creation=contention.date_creation
)
|
import codecs
detectlanguage.configuration.api_key = "d6ed8c76914a9809b58c2e11904fbaa3"
class Analyzer:
def __init__(self, passwd):
self.evaluation = {}
self._passwd = passwd
self.upperCount = 0
self.lowerCount = 0
self.specialCount = 0
self.entropy = 0
self.... | if char1 in value:
char1Pos = [2, secondKeyboardRow.index(value)+1]
elif char2 in value:
char2Pos = [2, secondKeyboardRow.index(value)+1]
for value in thirdKeyboardRow:
if char1 in value:
char1Pos = [3, thirdKeyboardRow.index(va... | elif char2 in value:
char2Pos = [3, thirdKeyboardRow.index(value)+1]
for value in fourthKeyboarRow:
if char1 in value:
char1Pos = [4, fourthKeyboarRow.index(value)+1]
elif char2 in value:
char2Pos = [4, fourthKeyboarRow.index(value)+1]... |
" | ""Top-level module for releng- | sop."""
|
"""
Created on 16 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Note: time shall always be stored as UTC, then localized on retrieval.
"""
from scs_core.data.rtc_datetime import RTCDatetime
from scs_host.bus.i2c import I2C
from scs_host.lock.lock import Lock
# -------------------------------... | I2C.Sensors.start_tx(cls.__ADDR)
value = I2C.Sensors.read_cmd(addr, 1)
finally:
I2C.Sensors.end_tx()
return value
@classmethod
def __write_reg_decimal(cls, addr, value):
return cls.__write_reg(addr, cls.__as_bcd(value))
@classmethod
def __write_re... | ADDR)
I2C.Sensors.write(addr, value)
finally:
I2C.Sensors.end_tx()
# ----------------------------------------------------------------------------------------------------------------
@classmethod
def obtain_lock(cls):
Lock.acquire(cls.__lock_name(), DS1338.__LOCK_TI... |
# -*- coding: utf-8 -*-
"""Module providing views for the site navigation root"""
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.ZCatalog.interfaces import ICatalogBrain
from plone import api
from plone.app.contentlisting.interfaces import IContentListing
from plone.app.con... | item = api.content.get(UID=uuid)
t | emplate = item.restrictedTraverse('@@card-news-item')()
return template
def section_preview(self, section):
info = {}
if section.startswith('/'):
target = section
else:
target = '/{0}'.format(section)
item = api.content.get(path=target)
if ite... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from view.analysis_widget import AnalysisWidget
# noinspection PyPep8Naming
class TemporalAnalysisWidget(AnalysisWidget):
# noinspection PyArgumentList
def __init__(self, mplCanvas):
"""
Construct the Temporal Analys... | lCanvas`` will be shown on this page.
|
:param mplCanvas: The ``ScatterPlot.mplCanvas`` widget.
"""
super().__init__()
upperLabel = QtWidgets.QLabel("Temporal Distribution &Graph:")
upperLabel.setMargin(1)
upperLabel.setBuddy(mplCanvas)
lowerLabel = QtWidgets.QLabel("Temporal Correlation &Quotient:"... |
from discord.ext import commands
import discord.utils
def is_owner_check(ctx):
author = str(ctx.message.author)
owner = ctx.bot.config['master']
return author == owner
def is_owner():
return commands.check(is_owner_check)
def check_permissions(ctx, perms):
#if is_owner_check(ctx):
# return... | raidset(ctx):
if ctx.message.server is None:
return False
server = ctx.message.server
try:
| return ctx.bot.server_dict[server]['raidset']
except KeyError:
return False
def check_wildset(ctx):
if ctx.message.server is None:
return False
server = ctx.message.server
try:
return ctx.bot.server_dict[server]['wildset']
except KeyError:
return False
def check_w... |
# -*- coding: utf-8 -*-
# libavg - Media Playback Engine.
# Copyright (C) 2003-2011 Ulrich von Zadow
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, o... | _onVThumbMove(self, thumbPos):
self.__scrollPane.contentpos = (self.__scrollPane.contentpos.x, thumbPos)
self.notifySubscribers(self.CONTENT_POS_CHANGED, [sel | f.__scrollPane.contentpos])
def __onDragStart(self):
self.__dragStartPos = self.__scrollPane.contentpos
self.notifySubscribers(self.PRESSED, [])
def __onDragMove(self, offset):
contentpos = self.__dragStartPos - offset
self.__scrollPane.contentpos = contentpos
self.__po... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreement | s. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you 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... | w.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 permissions and
#... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
| """
if not head: return None
p = head
listLen = 0 # calcu | late list length
while p:
p = p.next
listLen += 1
k = k % listLen # now k < listLen
if k == 0:
return head
p1 = head; p2 = head
for _ in xrange(k):
p2 = p2.next
assert p2
while p2.next:
p1 = p1.next
p2 = p2.next
newHead = p1.next
p1.next = None
p2.next = head
re... |
#!/usr/bin/env python
#
# Copyright 2015-2021 Flavio Garcia
#
# 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... | ress or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from firenado.util.sqlalchemy_util import Base, base_to_dict
from sqlalchemy import Column, String
from sqlalchemy.types import Integer, DateTime
from sqlalchemy.sql import text
import unittest
cla... | :
__tablename__ = "test"
id = Column("id", Integer, primary_key=True)
username = Column("username", String(150), nullable=False)
first_name = Column("first_name", String(150), nullable=False)
last_name = Column("last_name", String(150), nullable=False)
password = Column("password", String(150)... |
# Lint as: python3
# Copyright 2020 The Bazel Authors. All rights reserv | ed.
#
# 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
# distr | ibuted 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 permissions and
# limitations under the License.
"""The core data types ctexplain manipulates."""
from typing import Mapping
from... |
import logging
from .base import SdoBase
from .constants import *
from .exceptions import *
logger = logging.getLogger(__name__)
class SdoServer(SdoBase):
"""Creates an SDO server."""
def __init__(self, rx_cobid, tx_cobid, node):
"""
:param int rx_cobid:
COB-ID that the server r... | with code 0x{:08X}".format(abort_code))
def upload(self, index: int, subindex: int) -> bytes:
"""May be called to make a rea | d operation without an Object Dictionary.
:param index:
Index of object to read.
:param subindex:
Sub-index of object to read.
:return: A data object.
:raises canopen.SdoAbortedError:
When node responds with an error.
"""
return self... |
import wx
import eos.db
import gui.mainFrame
from gui import globalEvents as GE
from gui.fitCommands.calc.module.projectedAdd import CalcAddProjectedModuleCommand
from gui.fitCommands.helpers import InternalCommandHistory, ModuleInfo
from service.fit import Fit
class GuiAddProjectedModuleCommand(wx.Command):
de... | lcAddProjectedModuleCommand(fitID=self.fitID, modInfo=ModuleInfo(itemID=self.itemID))
success = self.internalHistory.submit(cmd)
sFit = Fit.getInstance()
if cmd.needsGuiRecalc:
eos.db.flush()
sFit.recalc(self.fitID)
sFit.fill(self.fitID)
eos.db.commit()
... | ef Undo(self):
success = self.internalHistory.undoAll()
eos.db.flush()
sFit = Fit.getInstance()
sFit.recalc(self.fitID)
sFit.fill(self.fitID)
eos.db.commit()
wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)))
return su... |
on.one)
assert W_out.ensure_validity(alter=False)
assert np.array_equal(W_out.t, W_in.t)
assert np.array_equal(W_out.frame, W_in.frame)
assert np.array_equal(W_out.data, W_in.data)
assert np.array_equal(W_out.LM, W_in.LM)
assert W_out.ell_min == W_in.ell_min
assert W_out.ell_max == W_in.ell_... | ert W_out.num != W_in.num
@pytest.mark.parametrize("w", [linear_waveform, constant_waveform, random_waveform])
def test_rotation_invariants(w):
# A random rotation should leave everything but data and frame the
# same (except num, of course)
W_in = w()
W_out = w()
np.random.seed(hash("test_rotatio... | W_out.rotate_decomposition_basis(np.quaternion(*np.random.uniform(-1, 1, 4)).normalized())
assert W_in.ensure_validity(alter=False)
assert W_out.ensure_validity(alter=False)
assert np.array_equal(W_out.t, W_in.t)
assert not np.array_equal(W_out.frame, W_in.frame) # This SHOULD change
assert not... |
# -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, ... |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | e(name='publish', label='Publish', description= | 'Publish a content')
superdesk.privilege(name='kill', label='Kill', description='Kill a published content')
superdesk.privilege(name='correct', label='Correction', description='Correction to a published content')
superdesk.privilege(name='publish_queue', label='Publish Queue', description='User can update p... |
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | tributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tf_agents.networks.categorical_q_network."""
from __future__ import absolute_import
from __future_... | -version-import
from tf_agents.networks import categorical_q_network
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.utils import test_utils
class CategoricalQNetworkTest(test_utils.TestCase):
def tearDown(self):
gin.clear_config()
super(Categorica... |
#coding:utf-8
'''
Timeou | ts超时设置
requests.g | et('http://github.com', timeout=2)
'''
|
# 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... | kvstore.init(key, grad)
idx = grad.indices
kvstore.push(key, grad)
kvstore.row_sparse_pull(key, out=grad, row_ids=idx)
assert_almost_equal(grad.asnumpy(), copy.asnumpy())
def test_rsp_push_pull_large_rowid():
num_rows = 793470
val = mx.nd.ones((num_rows, 1)).tostype('row_sparse').c | opyto(mx.gpu())
kv = mx.kv.create('device')
kv.init('a', val)
out = mx.nd.zeros((num_rows,1), stype='row_sparse').copyto(mx.gpu())
kv.push('a', val)
kv.row_sparse_pull('a', out=out, row_ids=mx.nd.arange(0, num_rows, dtype='int64'))
assert(out.indices.shape[0] == num_rows)
if __name__ == '__main... |
# -*- coding: utf-8 -*-
"""Unit and functional test suite for tg2express."""
from os import getcwd, path
from paste.deploy import loadapp
from webtest import TestApp
from gearbox.commands.setup_app import SetupAppCommand
from tg import config
from tg.util import Bunch
from tg2express import model
__all__ = ['setup... | descendants) has authentication dis | abled, so that developers can
test the protected areas independently of the :mod:`repoze.who` plugins
used initially. This way, authentication can be tested once and separately.
Check tg2express.tests.functional.test_authentication for the repoze.who
integration tests.
This is the officially suppo... |
be read, or the dialog was cancelled, the return result will be None
"""
self.script_name = Qt.QFileDialog.getOpenFileName(
None, 'Open Script File', '', 'Script (*.cfg)')
if self.script_name == '': # cancel returns empty string
return None
s... | if 'bridgeCorrection' in thiscell.keys():
presetDict['bridgeCorrection'] = thiscell['bridgeCorrection']
else:
presetDict['bridgeCorrection'] = None
dh = self.dataManager().manager.dirHandle(fullpath)
| if not self.loadFile([dh], analyze=False, bridge=presetDict['bridgeCorrection']): # note: must pass a list of dh; don't let analyisis run at end
print('Failed to load requested file: ', fullpath)
continue # skip bad sets of records...
if 'datamode' in th... |
import requests
headers = {
'foo': 'bar',
}
resp | onse | = requests.get('http://example.com/', headers=headers)
|
# Generated by Django 2.0 on 2018-02-08 11:45
from django.db import migrations
def forwards(apps, schema_editor):
"""
Change all DancePiece objects into Work objects, and their associated
data into WorkRole and WorkSelection models, then delete the DancePiece.
"""
DancePiece = apps.get_model("spe... | title_sort=dp.title_sort
)
for role in dp.roles.all():
WorkRole.objects.create(
| creator=role.creator,
work=work,
role_name=role.role_name,
role_order=role.role_order,
)
for selection in dp.events.all():
WorkSelection.objects.create(
event=selection.event, work=work, order=selection.order
... |
#!/usr/bin/env py | thon
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social_news_site.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.arg | v)
|
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
im... |
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_COPY:
raise ValueError('Rule for source %s must use REPLICATION_TYPE_COPY.' %
rule.source_path)
else:
raise NotImplementedError('Replicate not implemented for file type %s' %
rule.fi... | onfig_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields.')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destination_fields.paths:
raise ValueError(
... |
import mock
from nose.tools import eq_, ok_, assert_raises
from funfactory.urlresolvers import reverse
from .base import ManageTestCase
class TestErrorTrigger(ManageTestCase):
def test_trigger_error(self):
url = reverse('manage:error_trigger')
response = self.client.get(url)
assert self... | )
@mock.patch('airmozilla.manage.views.errors.Client')
def test_trigger_error_with_raven(self, mocked_client):
url = reverse('manage:error_trigger')
assert self.user.is_superuser
raven_config = {
'dsn': 'fake123'
}
with self.settings(RAVEN_CONFIG=raven_conf... | essage',
'capture_with_raven': True
})
eq_(response.status_code, 302)
mocked_client().captureException.assert_called_with()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-18 09:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order_reminder', '0001_initial'),
]
operations = [
migrations.AddField(
... | length=200, null=True, unique=True),
),
migrations.AlterField(
model_name='orders',
name='order_id',
field=models.CharField(max_length=200, null=True, unique=True, verbose_name=b'Company Name'),
),
| ]
|
import sys
import os
brief = "create a test for controller"
def usage(argv0):
print("Usage: {} generate test controller CONTROLLER_NAME METHOD [METHOD] [...]".format(argv0))
sys.exit(1)
aliases = ['c']
def execute(argv, argv0, engine):
import lib, inflection
os.environ.setdefault("AIOWEB_SETTINGS... | controller_file_name = inflection.underscore(argv[0]) + ".py"
methods = argv[1:]
dest_file = os.path.join(lib.dirs(settings, format=["tests_controllers"]), controller_file_name)
os.makedirs(os.path.dirname(de | st_file), exist_ok=True)
template = lib.get_template("tests/controller.py", settings)
if os.path.exists(dest_file):
if lib.ask("{} already exists!\nDo you wanna replace it?".format(dest_file)) == 'n':
print("Generation was aborted!")
return
print("creating {}".format(dest_f... |
'''build RoboFont Extension'''
import os
from AppKit import NSCommandKeyMask, NSAlternateKeyMask, NSShiftKeyMask
from mojo.extensions import ExtensionBundle
# get current folder
basePath = os.path.dirname(__file__)
# source folder for all extension files
sourcePath = os.path.join(basePath, 'source')
# folder with p... | the extension
B.version = '0.2.6'
# should the extension be launched at start-up?
B.launchAtStartUp = True
# script to be exec | uted when RF starts
B.mainScript = 'hello.py'
# does the extension contain html help files?
B.html = True
# minimum RoboFont version required for this extension
B.requiresVersionMajor = '4'
B.requiresVersionMinor = '0'
# scripts which should appear in Extensions menu
B.addToMenu = [
{
'path': 'd... |
#!/usr/bin/python
#coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
#
# This module 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 optio... | w'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: tower_host
version_added: "2.3"
short_description: create, update, or destroy Ansible Tower host.
description:
- Create, update, or destroy Ansible Tower hosts. See
U(https://www.ansibl... | :
- The description to use for the host.
required: False
default: null
inventory:
description:
- Inventory the host should be made a member of.
required: True
enabled:
description:
- If the host should be enabled.
required: False
default: True
... |
"""Tests for account creation"""
def setUp(self):
super(TestActivateAccount, self).setUp()
self.username = "jack"
self.email = "jack@fake.edx.org"
self.password = "test-password"
self.user = UserFactory.create(
username=self.username, email=self.email, passw... | gistration page displays success/error/info messages
about account activation.
"""
login_page_url = "{login_url}?next={redirect_url}".format(
login_url=reverse('signin_user'),
redirect_url=reverse('dashboard'),
)
# Access activation link, message should sa... | .activation_key]), follow=True)
self.assertRedirects(response, login_page_url)
self.assertContains(response, 'Success! You have activated your account.')
# Access activation link again, message should say that account is already active.
response = self.client.get(reverse('activate', arg... |
#!/usr/bin/env python
# This file provided by Facebook is for non-commercial testing and evaluation
# purposes only. Facebook reserves all rights not expressly granted.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... | ')
def main():
args = parse_args()
scenarios = []
sources = []
if args.scenarios:
scenarios = args.scenarios
else:
scenarios = TESTS
if args.sources:
sources = args.sources
else:
sources = TEST_SOURCES
insta | ll_apks(args.cpu)
for scenario_name in scenarios:
for source_name in sources:
if valid_scenario(scenario_name, source_name):
print()
print('Testing {} {}'.format(scenario_name, source_name))
print(get_test_name(scenario_name, source_name))
... |
#!/usr/bin/env python
ergodoxian = (
("KEY_DeleteBackspace","1x2"),
("KEY_DeleteForward","1x2"),
('KEY_ReturnEnter', '1x2'),
('KEY_Spacebar', '1x2'),
('SPECIAL_Fn', '1x2'),
('KEY_Shift', '1.5x1'),
('KEY_Shift', '1.5x1'),
("KEY_Dash_Underscore", "1.5x1"),
("KEY_Equal_Plus", "1.5x1"),
('KEY_ReturnEnter', '1.5x1'),
("KEY... | eForward","1x2"),
('KEY_ReturnEnter', '1x2'),
('KEY_Space | bar', '1x2'),
('SPECIAL_Fn', '1x2'),
('KEY_Shift', '1.5x1'),
('KEY_Shift', '1.5x1'),
("KEY_Dash_Underscore", "1.5x1"),
("KEY_Equal_Plus", "1.5x1"),
('KEY_ReturnEnter', '1.5x1'),
("KEY_Escape", "1.5x1"),
("KEY_DeleteForward","1.5x1"),
('SPECIAL_Fn', '1x1.5'),
("KEY_LeftBracket_LeftBrace", "1x1.5"),
("KEY_RightBracket_Ri... |
)
all_children = ((x for x in soup.children if x != '\n')
for soup in soups)
for childs in zip(*all_children):
# assume that the 1st file is the "master file" that everything
# compares to.
child = childs[0]
... | if isinstance(child, bs4.element.Tag):
new_parent = self.tree.AppendItem(parent, child.name)
self._build_element_tree_recursively(new_parent, childs)
@logged
def _highlight_item_and_parents(self, item):
""" highlights an item row and parents """
self.d... | parent in get_parents(self.tree, item):
self.tree.SetItemBackgroundColour(parent, HIGHLIGHT2)
@logged
def _set_log_level(level_str):
"""
Sets the global logging level
Parmeters:
----------
level_str : string
String representation of logging.level. Accpeted values ... |
l_viewer 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. l_viewer is distributed in the hope that it will be useful, but
WITHOUT ANY WARRAN... | d(column=0, row=2,
| columnspan=2, sticky=tk.W + tk.E)
self.zoom_out_button.grid(column=2, row=2,
columnspan=2, sticky=tk.W + tk.E)
self.up_button.grid(column=1, row=3,
columnspan=2, sticky=tk.W + tk.E)
self.left_button.grid(column=0, row... |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008 Zsolt Foldvari
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) ... | tuple, or even another L{Styled | TextTagType}
instance.
"""
self.name = StyledTextTagType(name)
self.value = value
if ranges is None:
self.ranges = []
else:
# Current use of StyledTextTag is such that a shallow copy suffices.
self.ranges = ranges
def seri... |
'task': self.html_id(),
'update': 'lr_graph',
'data': data,
},
namespace='/jobs',
room=self.job_id,
)
def save_val_output(self, *args):
"""
Save output to self.val_... | d[name] = NetworkOutput(kind, [])
epoch_len = len(d['epoch'].data)
name_len = len(d[name].data)
# save to back of d[name]
if name_len > epoch_len:
raise Exception('Received a new output without being told the new epoch')
elif name_len == epoch_len:
| # already exists
if isinstance(d[name].data[-1], list):
d[name].data[-1].append(value)
else:
d[name].data[-1] = [d[name].data[-1], value]
elif name_len == epoch_len - 1:
# expected case
d[name].data.append(value)
el... |
#!/usr/bin/env python
import unittest
import importlib
import random
from mock import patch
vis_map = importlib.import_module('ciftify.bin.cifti_vis_map')
class TestUserSettings(unittest.TestCase):
temp = '/tmp/fake_temp_dir'
palette = 'PALETTE-NAME'
def test_snap_set_to_none_when_in_index_mode(self):
... | ocmd')
def test_snap_is_nifti_converted_to_cifti_in_nifti_snaps_mode(self,
mock_docmd):
args = self.get_default_arguments()
args['nifti-snaps'] = True
args['<map.nii>'] = '/some/path/my_map.nii'
cifti = vis_map.UserSettings(args, self.tem | p).snap
# Expect only ciftify-a-nifti needs to be run
assert mock_docmd.call_count == 1
# Extract first (only) call, then arguments to call, then command list.
assert 'ciftify-a-nifti' in mock_docmd.call_args_list[0][0][0]
@patch('ciftify.utilities.docmd')
def test_palette_chan... |
# -*- coding: utf-8 -*-
from odoo import http
from odoo.addons.website_sale_delivery.controllers.main import WebsiteSaleDelivery
from odoo.http import request
class WebsiteSaleCouponDelivery(WebsiteSaleDelivery):
@http.route()
def update_eshop_carrier(self, **post):
Monetary = request.env['ir.qweb.fi... | ue)
free_shipping_lines = order._get_free_shipping_lines()
# Avoid computing carrier price delivery is free (coupon). It means if
# the carrier has error (eg 'delivery only for Belgium') it will show
# Free until the user clicks on it.
if free_shipping_lines:
return {... | livery': Monetary.value_to_html(0.0, {'display_currency': order.currency_id}),
'error_message': None,
}
return super(WebsiteSaleCouponDelivery, self).cart_carrier_rate_shipment(carrier_id, **kw)
|
# 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)
class VersionTestDependencyPreferred(AutotoolsPackage):
"""Dependency of version-test-pkg, which has a multi-valued
variant with two default values (a very low priority optimization
criterion for clingo is to maximize their number)
"""
homepage = "http://www.spack.org"
url = "http://www... | rg/downloads/xz-1.0.tar.gz"
version('5.2.5', sha256='5117f930900b341493827d63aa910ff5e011e0b994197c3b71c08a20228a42df')
variant('libs', default='shared,static', values=('shared', 'static'),
multi=True, description='Build shared libs, static libs or both')
|
import deep_architect.searchers.common as se
import numpy as np
# NOTE: this searcher does not do any budget adjustment and needs to be
# combined with an evaluator that does.
class SuccessiveNarrowing(se.Searcher):
def __init__(self, search_space_fn, num_initial_samples, reduction_factor,
reset... | xt round of architectures by keeping the best ones.
if self.num_remaining == 0:
num_samples = int(self.reduction_factor * len(self.queue))
assert num_samples > 0
top_idxs = np.argsort(self.vals)[::-1][:num_samples]
self.queue = [self.queue[idx] for idx in top_idxs... |
# run simple successive narrowing on a single machine.
def run_successive_narrowing(search_space_fn, num_initial_samples,
initial_budget, get_evaluator, extract_val_fn,
num_samples_reduction_factor,
budget_increase_factor, num_rou... |
import logging
import os
import ctypes
import ctypes.util
log = logging.getLogger("lrrbot. | systemd")
try:
libsystemd = ctypes.CDLL(ctypes.util.find_library("systemd"))
libsystemd.sd_notify.argtypes = [ctypes.c_int, ctypes.c_char_p]
def notify(status):
libsystemd.sd_notify(0, status.encode('utf-8'))
except OSError as e:
log.warning("failed to load libsystemd: {}", | e)
def notify(status):
pass
class Service:
def __init__(self, loop):
self.loop = loop
timeout_usec = os.environ.get("WATCHDOG_USEC")
if timeout_usec is not None:
self.timeout = (int(timeout_usec) * 1e-6) / 2
self.watchdog_handle = self.loop.call_later(self.timeout, self.watchdog)
self.subsystems ... |
"""
Small event module
=======================
"""
import numpy as np
import logging
logger = logging.getLogger(__name__)
from ...utils.decorators import face_lookup
from ...geometry.sheet_geometry import SheetGeometry
from ...topology.sheet_topology import cell_division
from .actions import (
exchange,
r... | oc[face, "area"] < contraction_spec["critical_area"]) or (
sheet.face_df.loc[face, contraction_spec["contraction_column"]]
> contraction_spec["max_contractility"]
):
return
increase(
sheet,
"face",
face,
contraction_spec["contractile_increase"],
co... | m": SheetGeometry,
}
@face_lookup
def type1_transition(sheet, manager, **kwargs):
"""Custom type 1 transition event that tests if
the the shorter edge of the face is smaller than
the critical length.
"""
type1_transition_spec = default_type1_transition_spec
type1_transition_spec.update(**kwarg... |
# 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... | nvCombo.GetStringSelection() |
self.drawScatter(envName)
def on_save_plot(self, event):
fileChoices = "PNG (*.png)|*.png"
dlg = wx.FileDialog(self,message="Save risk scatter",defaultDir=os.getcwd(),defaultFile="scatter.png",wildcard=fileChoices,style=wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
se... |
from course import Cou | rse
from course_offering | import CourseOffering
from distributive_requirement import DistributiveRequirement
from instructor import Instructor
from course_median import CourseMedian
from review import Review
from vote import Vote
from student import Student
|
"""Elmax integration common classes and utilities."""
from __future__ import annotations
from datetime import timedelta
import logging
from logging import Logger
import async_timeout
from elmax_api.exceptions import (
ElmaxApiError,
ElmaxBadLoginError,
ElmaxBadPinError,
ElmaxNetworkError,
)
from elmax... | rsion: str,
coordinator: ElmaxCoordinator,
) -> None:
"""Construct the object."""
| super().__init__(coordinator=coordinator)
self._panel = panel
self._device = elmax_device
self._panel_version = panel_version
self._client = coordinator.http_client
@property
def panel_id(self) -> str:
"""Retrieve the panel id."""
return self._panel.hash
... |
"""
Transform 2019: Integrating Striplog and GemPy
==============================================
"""
# %%
# ! pip install welly striplog
# %%
# Authors: M. de la Varga, Evan Bianco, Brian Burnham and Dieter Werthmüller
# Importing GemPy
import gempy as gp
# Importing auxiliary libraries
import numpy as np
import... | open(file) as f:
text = f.read()
striplog = Striplog.from_csv(text=text)
my_striplogs.append(striplog)
striplog_dict = {'alpha': my_striplogs[1],
'beta': my_striplogs[2],
'gamma': my_striplogs[3],
'epsilon': my_striplogs[0]}
striplog_dict['al... | g_dict.items()):
log[1].plot(ax=a[e], legend=None)
f.tight_layout()
plt.show()
# %%
# Striplog to pandas df of bottoms
rows = []
for wellname in striplog_dict.keys():
for i, interval in enumerate(striplog_dict[wellname]):
surface_name = interval.primary.lith
surface_base = interval.base.middle
... |
import time
from goose import Goose
def load_jezebel():
with open('resources/additional_html/jezebel1.txt') as f:
data = f.read()
return data
def bench(iterations=100):
data = load_jezebel()
goose = Goose()
times = []
for _ in xrange(iterations):
t1 = time.ti | me()
goose.extract(raw_html=data)
t2 = time.time()
iteration_time = t2 - t1
times.append(iteration_time)
return (sum(times) / float(len(times)))
if __name__ == '__main__':
start = time.time()
print bench()
end = time.time()
| total_len = end - start
print "total test length: %f" % total_len
|
'''
Created on 2014-8-1
@author: xiajie
'''
import numpy as np
def fmax(a, b):
if a >= b:
return a
else:
return b
def fmin(a, b):
if a <= b:
return a
else:
return b
def radia_kernel(x1, x2):
return np.transpose(x1).dot(x2)
def kernel(x1, x2):
d = x1 -... | tmp = alphas[i]
alphas[i] = v
N = len(Y)
w = | np.sum(alphas)
s = 0.
for i in range(N):
for j in range(N):
s += Y[i]*Y[j]*radia_kernel(X[i],X[j])*alphas[i]*alphas[j]
w = w - 0.5*s
alphas[i] = tmp
return w
def takestep(Y, X, alphas, i1, i2, b, E, C=10):
N = len(alphas)
if i1 == i2:
return 0
alpha1 = alpha... |
from ..models import models
class RasterModel( | models.Model):
rast = models.RasterField('A Verbose Raster Name', null=True, srid=4326, spatial_index=True, blank=True)
class Meta:
required_db_features = ['supports_raster']
def __str__(self):
return str(se | lf.id)
|
"""
super simple utitities to display tabular data
columns is a list of tuples:
- name: header name for the column
- f: a function which takes one argument *row* and returns the value to
display for a cell. the function which be called for each of the rows
supplied
"""
import sys
import csv
def... | row in rows:
for name, f in columns:
lengths[name] = max(lengths[name], len(str(f(row)))+1)
fmt = ' '.join(['{:<%s}' % lengths[x] for x, _ in columns])
print fmt.form | at(*[x for x, _ in columns])
for row in sorted(rows, key=key):
print fmt.format(*[f(row) for _, f in columns])
|
#!/usr/bin/env python
#
# Copyright 2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
... | options, args) = | parser.parse_args ()
if len(args) != 1:
parser.print_help()
raise SystemExit, 1
if options.freq is None:
parser.print_help()
sys.stderr.write('You must specify the frequency with -f FREQ\n');
raise SystemExit, 1
return (options, args[0])
if __name__ == '__... |
import support
from heat.engine import translation
class RandomString(resource.Resource):
"""A resource which generates a random string.
This is useful for configuring passwords and secrets on services. Random
string can be generated from specified character sequences, which means
that all character... | CHARACTER_SEQUENCES_MIN},
required=True),
CHARACTER_SEQUENCES_MIN: properties.Schema(
properties.Schema.INTEGER,
_('The minimum number of characters from this '
'sequence that will be in the generated ... | ]
)
}
)
),
SALT: properties.Schema(
properties.Schema.STRING,
_('Value which can be set or changed on stack update to trigger '
'the resource for replacement with a new random string. The '
'salt value it... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.envir | on.setdefault("DJANGO_SETTING | S_MODULE", "vgid.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
ssertTrue(user.check_password('password9'))
with self.assertRaises(ValueError):
UserProfile.objects.return_new_user_object(
username=None,
)
def test_create_user(self):
"""
Create user
"""
user = UserProfile.objects.create_user(
... | rue(user.check_password('password9'))
self.assertTrue(user.is_active)
self.assertEqual({
'user_id': 1,
'total_cash': format | ted(config.STARTING_CASH),
'portfolio_value': formatted(0),
'reputation': '100%',
}, user.statistics_dict)
user2 = UserProfile.objects.create_user(
username='j_smith',
email='j_smith@example.com',
)
self.assertIsInstance(user2, HttpRespons... |
Error
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable
from ansible.executor import action_write_locks
from ansible.executor.process.worker import WorkerProcess
from ansible.executor.task_result import TaskResult
from ansible.inventory.host import... | ('is_skipped', 'skipped'),
)
# We don't know the host yet, copy the previous states, for lookup after we proc | ess new results
prev_host_states = iterator._host_states.copy()
results = func(self, iterator, one_pass=one_pass, max_passes=max_passes)
_processed_results = []
for result in results:
task = result._task
host = result._host
_queued_task_args = self._... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# namedtuple is needed for find_mod_objs so it can have a non-local module
from collections import namedtuple
from unittest import mock
import pytest
import yaml
from astropy.utils import introspection
from astropy.utils.introspection import (find_curre... | e)
assert 'namedtuple' not in lnms
assert 'collections.namedtuple' not in fqns
assert namedtuple no | t in objs
def test_minversion():
import numpy
good_versions = ['1.16', '1.16.1', '1.16.0.dev', '1.16dev']
bad_versions = ['100000', '100000.2rc1']
for version in good_versions:
assert minversion(numpy, version)
assert minversion("numpy", version)
for version in bad_versions:
... |
"""Class for storing shared keys."""
from utils.cryptomath import *
from utils.compat import *
from mathtls import *
from Session import Session
from BaseDB import BaseDB
class SharedKeyDB(BaseDB):
"""This class represent an in-memory or on-disk database of shared
keys.
A SharedKeyDB can be passed to a s... | rn session
def __setitem__(self, username, sharedKey):
"""Add a shared key to the database.
@type username: str
@param username: The username to associate the shared key with.
Must be less than or equal to 16 characters in length, and must
not already be in the database.
... | characters in length.
"""
BaseDB.__setitem__(self, username, sharedKey)
def _setItem(self, username, value):
if len(username)>16:
raise ValueError("username too long")
if len(value)>=48:
raise ValueError("shared key too long")
return value
def _... |
# -*- coding: utf-8 -*-
#
# Copyright © 2011 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""IPython v0.11+ Plugin"""
from spyderlib.qt.QtGui import QHBoxLayout
# Local imports
from spyderlib.widgets.ipython import create_widget
from spyde | rlib.plugins import SpyderPluginWidget
class IPythonPlugin(SpyderPluginWidget):
"""Find in files DockWidget"""
CONF_SECTION = 'ipython'
def __init__(self, parent, args, kernel_widget, kernel_name):
super(IPythonPlugin, self).__init__(parent)
self.kernel_widget = kernel_widget
... | t()
layout.addWidget(self.ipython_widget)
self.setLayout(layout)
# Initialize plugin
self.initialize_plugin()
def toggle(self, state):
"""Toggle widget visibility"""
if self.dockwidget:
self.dockwidget.setVisible(state)
... |
; 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 Software Foundation, Inc., Fran... | ntable character for punctuation
# marks.
#
if keyboardEvent.event_string == keyboardEvent.keyval_name \
and len(keyboardEvent.eve | nt_string) > 1:
keyval = Gdk.keyval_from_name(keyboardEvent.keyval_name)
if 0 < keyval < 256:
keyboardEvent.event_string = chr(keyval)
def onCaretMoved(self, event):
# Java's SpinButtons are the most caret movement happy thing
# I've seen to date. If you Up ... |
d | efault_app_config = 'mtr.sync.apps.MtrSyncConfig | '
|
#!/bin/python3
import argparse
import code
import readline
import signal
import sys
import capstone
from load import ELF
def SigHandler_SIGINT(signum, frame):
print()
sys.exit(0)
class Argparser(object):
def __init__(self):
parser = argparse.ArgumentParser()
| parser.add_argument("--arglist", nargs="+", type=str, help="list of args")
parser.add_argument("--hex", action="store_true", help="generate hex(string) code, otherwise generate int", default=False)
self.args = parser.parse_args()
self.code = {}
class Call_Rewriter(object):
def __init__(s... | #self.md = Cs(CS_ARCG_X86, CS_MODE_64)
self.md = Cs(arch, mode)
def run():
for i in md.disasm(self.obj_code, 0x0):
print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))
class Global_Rewriter(object):
def __init__(self):
pass
# Main is here
def premain():
signal.... |
import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider( | object):
def __init__(self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grace(self):
import time
time.sleep(self._vk_delay)
def get_news(self, s | ources, amount=10):
# entry for Alex Anlysis tool
result = []
for source in sources:
try:
data = self._vk_api.wall.get(domain=source, count=amount, extended=1, fields='name')
self._vk_grace()
except:
return {}
... |
hout limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all c... | dialect)
else:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS | $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
... |
import gc
import os
import argparse
os.environ['TF_CP | P_MIN_LOG_LEVEL'] = '2'
from util import generate_features
def get_arguments():
parser = argparse.ArgumentParser(description='Generate features using a previously trained model')
parser.add_argument('data', type=str, help='File containing the input smiles matrices')
parser.add_argument('model', type=st | r, help='The model file')
parser.add_argument('features', type=str, help='Output file that will contain the generated features')
parser.add_argument('--batch_size', type=int, default=100, help='Size of the batches (default: 100)')
return parser.parse_args()
args = get_arguments()
generate_features.generat... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_richness_ascii.py
----------------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
**************... | *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. ... | |
import pyaudio
import wave
#CHUNK = 1024
CHUNK = 1
FORMAT = pyaudio.paInt16
#CHANNELS = 2
CHANNELS = 1
#RATE = 44100
RATE = 10 | 025
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording, C | HUNK=%d" % CHUNK)
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
print('data=%s, len=%d' % (str(data), len(data)))
# print(str(data))
# print('%d' % ord(data))
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
|
ag=vlan_tag,
gateway_mac=gateway_mac,
dst_mac=dst_mac,
dst_port=dst_port)
(dp, ofp, ofpp) = self._get_dp()
expected = [
call._send_msg(ofpp.OFPFlowMod(dp,
cook... |
call._send_msg(ofpp.OFPFlowMod(dp,
cookie=self.stamp,
instructions=[
ofpp.OFPInstructionGotoTable(table_id=60),
],
match=ofpp.OFPMatch(
eth_type=self.ether_types.ETH_TYPE_IPV6,
icmpv6... | to=self.in_proto.IPPROTO_ICMPV6,
ipv6_nd_target='fdf8:f53b:82e4::1',
in_port=8888,
),
priority=2,
table_id=24)),
call._send_msg(ofpp.OFPFlowMod(dp,
cookie=self.stamp,
instructions=[
... |
import re
import transaction
from ..models import DBSession
SQL_TABLE = """
SELECT c.oid, n.nspna | me, c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = :table_name
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 2, 3
"""
SQL_TABLE_SCHEMA = """
SELEC | T c.oid, n.nspname, c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = :table_name
AND n.nspname = :schema
ORDER BY 2, 3
"""
SQL_FIELDS = """
SELECT a.attname,
pg_catalog.format_type(a.atttypid, a.atttypmod),
(SELECT substring(pg_catalog... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ProjectBadge.awardLevel'
db.add_column(u'badges_projectbadge', 'awardLevel',
... | e': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': | 'True'})
}
}
complete_apps = ['badges'] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-19 18:40
from __future__ import unicode_literals
from django.db import migrations
class M | igration(migrations.Migration):
dependencies = [
('mqtt_logger', '0002_mqttsubscription_active'),
]
operations = [
migrations.AlterModelOptions(
name='mqttmessage',
options={'verbose_name': 'MQTT message', 'verbose_name_plural': 'MQTT messages'},
),
... | rbose_name_plural': 'MQTT subscriptions'},
),
]
|
# Hack, hide DataLossWarnings
# Based on html5 | lib code namespaceHTMLElements=False should do it, but nope ...
# Also it doesn't seem to be available in older version from html5lib, removing it
import warnings
from typing import IO, Union
from bs4 import BeautifulSoup
fro | m html5lib.constants import DataLossWarning
warnings.simplefilter('ignore', DataLossWarning)
def get_soup(obj: Union[str, IO, bytes], parser: str = 'html5lib') -> BeautifulSoup:
return BeautifulSoup(obj, parser)
|
import requests
LRS = "http://cygnus.ic.uva.nl:8000/XAPI/statements"
u = raw_input("LRS username: ")
p = raw_input("LRS password: ")
r = | requests.get(LRS,headers={"X-Experience-API-Version":"1.0"},auth=(u,p));
if r.status_code == 200:
print " | Success"
else:
print "Server returns",r.status_code
|
import pytest
from plenum.test.helper import perf_monitor_disabled
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.view_change_with_delays.helper import \
do_view_change_with_propagate_primary_on_one_delayed_node
# This is needed only with current view change implement... | that monitor won't start view change unexpectedly
"""
with perf_monitor_disabled(tconf):
yield tconf
def test_view_change_with_propagate_primary_on_one_delayed_node(
txnPoolNodeSet, looper, sdk_pool_handle, sdk_wallet_client, tconf):
"""
Perform view change on all the nodes except for... | ow
node in the old view and by the other nodes in the new view. After that
verify that all the nodes have the same ledgers and state.
"""
do_view_change_with_propagate_primary_on_one_delayed_node(
txnPoolNodeSet[-1], txnPoolNodeSet, looper, sdk_pool_handle, sdk_wallet_client)
ensure_all_nod... |
"""
Defines the Sumatra version control interface for Git.
Classes
-------
GitWorkingCopy
GitRepository
:copyright: Copyright 2006-2015 by the Sumatra team, see doc/authors.txt
:license: BSD 2-clause, see LICENSE for details.
"""
from __future__ import print_function
from __future__ import absolute_import
from __fu... | ()
import logging
import git
import os
import s | ys
import shutil
from distutils.version import LooseVersion
from configparser import NoSectionError, NoOptionError
try:
from git.errors import InvalidGitRepositoryError, NoSuchPathError
except:
from git.exc import InvalidGitRepositoryError, NoSuchPathError
from .base import Repository, WorkingCopy, VersionContr... |
# Copyright 2013-2020 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)
from spack import *
class Claw(CMakePackage):
"""CLAW Compiler targets perfo | rmance portability problem in climate and
weather application written in Fortran. From a single source code, it
generates architecture specific code decorated with OpenMP or OpenACC"""
homepage = 'h | ttps://claw-project.github.io/'
git = 'https://github.com/claw-project/claw-compiler.git'
maintainers = ['clementval']
version('2.0.2', commit='8c012d58484d8caf79a4fe45597dc74b4367421c', submodules=True)
version('2.0.1', commit='f5acc929df74ce66a328aa4eda9cc9664f699b91', submodules=True)
versi... |
from __future__ import division
from sys import stdin, | stdout
from collections import deque
def solve(n, edges, s):
def build_graph(n, edges):
graph = [[] for _ in range(n)]
for (a, b) in edges:
a, b = a - 1, b - 1
graph[a].append(b)
graph[b].append(a)
return graph
graph = build_graph(n, edges)
dis ... | adj] = dis[node] + 6
que.append(adj)
del dis[s]
return dis
if __name__ == '__main__':
t = int(stdin.readline())
for _ in range(t):
edges = []
n, m = map(int, stdin.readline().strip().split())
for _ in range(m):
a, b = map(int, stdin.readline().strip... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-04-16 16:39
from __future__ import unicode_literals
import base.models.learning_unit_year
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
... | ose_name='code'),
),
migrations.AlterField(
model_name='learningunityear',
name='internship_subtype',
field=models.CharField(blank=True, choices=[('TEACHING_INTERNSHIP', 'TEACHING_INTERNSHIP'), (' | CLINICAL_INTERNSHIP', 'CLINICAL_INTERNSHIP'), ('PROFESSIONAL_INTERNSHIP', 'PROFESSIONAL_INTERNSHIP'), ('RESEARCH_INTERNSHIP', 'RESEARCH_INTERNSHIP')], max_length=250, null=True, verbose_name='internship_subtype'),
),
migrations.AlterField(
model_name='learningunityear',
name='qua... |
from api_linked_rpc impo | rt * #@U | nusedWildImport
|
puts(green("installing MidoNet cli on %s" % env.host_string))
args = {}
Puppet.apply('midonet::midonet_ | cli', args, metadata)
run("""
cat >/root/.midonetrc <<EOF
[cli]
api_url = http | ://%s:8080/midonet-api
username = admin
password = admin
project_id = admin
tenant = admin
EOF
""" % metadata.servers[metadata.roles['midonet_api'][0]]['ip'])
|
import unittest
from bolt.core.plugin import Plugin
from bolt import interval
from bolt import Bot
import yaml
class TestIntervalPlugin(Plugin):
@interval(60)
def intervaltest(self):
pass
class TestInterval(unittest.TestCase):
def setUp(self):
self.config_file = "/tmp/bolt-test-config.y... | /"
}
with open(self.config_file, "w") as tempconfig:
tempconfig.write(yaml.dump(fake_config))
def test_interval_decos(self):
bot = Bot(self.config_file)
plugin = TestIntervalPlugin(bot)
plugin.load()
self.assertTrue(len(plugin.intervals) > 0)
def t... | in.intervals[0].ready())
|
"""
Django settings for pennapps project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pat... | he project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in pr... | h debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'AI_chat',
)
MID... |
# coding=utf-8
import unittest
from text import grep
from text import string_utils
import text_test
class GrepTest(unittest.TestCase):
def test_grep(self):
log_list = text_test.read_log()
linux_syslog_head = '(\S+\s+\d+)\s+(\d+:\d+:\d+)\s+(\S+)\s+'
group_data = grep.grep... | data = grep.grep(log_list, 'pam', False, 's')
self.assertEqual(len(group_data), 6)
group_data = grep.grep(log_list, 'pam', True, 's')
self.assertEqual(len(group_data), 6)
self.assertTrue(string_utils.startswith(group_data[0], '1'))
self.assertTrue(string_utils.startswith... | ith(group_data[4], '12'))
self.assertTrue(string_utils.startswith(group_data[5], '19'))
group_data = grep.grep(log_list, None, True, 'e')
self.assertEqual(len(group_data), 19)
group_data = grep.grep(log_list, grep_action, True, 'a')
self.assertEqual(len(group_da... |
# Copyright (C) 2013 Andrew Okin
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribu... | ad URL type modules.
import shortenedurl
impor | t pastebinurl
# FIXME: This is a pretty stupid way of loading things.
typemodules = [ pastebinurl, shortenedurl ]
for typemod in typemodules:
try:
url_types += typemod.get_url_types_provided()
except AttributeError:
# If get_url_types_provided doesn't exist, this isn't a proper type module we can load URL type... |
import pprint
import sys
from xml.dom import xmlbuilder, expatbuilder, Node
from xml.dom.NodeFilter import NodeFilter
class Filter(xmlbuilder.DOMBuilderFilter):
whatToShow = NodeFilter.SHOW_ELEMENT
def startContainer(self, node):
assert node.nodeType == Node.ELEMENT_NODE
if node.tagName == "s... | t nested indirectly wit | hin another skipped element
checkResult('''\
<doc>Text.
<skipthis>Nested text.
<nested-element>
<skipthis>Nested text in skipthis element.</skipthis>
More nested text.
</nested-element>
More text.
</skipthis>Outer text.</doc>
''')
checkResult("<doc><rejectbefore/></doc>")
checkResult("<doc... |
# fundamental types
if atom == Type.type_bool (): return self.get_bool ()
elif atom == Type.type_char (): return self.get_char ()
elif atom == Type.type_uchar (): return self.get_uchar ()
elif atom == Type.type_int (): return self.get_int ()
... | ########################################### | ##
# Prototypes #
###############################################
_lib.myelin_value_new.argtypes = None
_lib.myelin_value_new.restype = ctypes.c_void_p
_lib.myelin_value_ref.argtypes = [Value]
_lib.myelin_value_ref.restype = ctypes.c_void_p
_lib.myelin_value_unref.argtypes = [Value... |
ers are listed
self.assertTrue('_namespace' in attr_list)
self.assertTrue('_version' in attr_list)
# test that there are no duplicates returned
self.assertEqual(len(attr_list), len(set(attr_list)))
def test_ptrarray(self):
# transfer container
result = Everything.te... | ue)
self.assertEqual(result['string'], 'some text')
self.assertEqual(result['strings'], ['first', 'second', 'third'])
self.assertEqual(result['flags'], Everything.TestFlags.FLAG1 | Everything.T | estFlags.FLAG3)
self.assertEqual(result['enum'], Everything.TestEnum.VALUE2)
result = None
def test_hash_in(self):
# specifying a simple string array for "strings" does not work due to
# https://bugzilla.gnome.org/show_bug.cgi?id=666636
# workaround by explicitly building a ... |
"""
Unit tests for the red2d (3-7-column) reader
"""
import warnings
warnings.simplefilter("ignore")
import unittest
from sas.sascalc.dataloader.loader import Loader
import os.path
class abs_reader(unittest.TestCase):
def setUp(self):
self.loader = Loader()
def test_checkdata(self):
""... | at")[0]
# The length of the data is 10
self.assertEqual(len(f.qx_data), 36864)
self.assertEqual(f.qx_data[0],-0.03573497)
self.assertEqual(f.qx_data[36863],0.2908819)
self.assertEqual(f.Q_unit, '1/A')
| self.assertEqual(f.I_unit, '1/cm')
self.assertEqual(f.meta_data['loader'],"IGOR/DAT 2D Q_map")
if __name__ == '__main__':
unittest.main()
|
#
# Copyright 2013 Red Hat, | Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma | y 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 ... |
resource, maxfixes)
pymodule = fixer.get_pymodule()
pyname = fixer.pyname_at(offset)
if pyname is None:
return None
pyobject = pyn | ame.get_object()
return PyDocExtractor().get_calltip(pyobject, ignore_unknown, remove_self)
def get_definition_location(project, source_code, offset,
resource=None, maxfixes=1):
"""Return the definition lo | cation of the python name at `offset`
Return a (`rope.base.resources.Resource`, lineno) tuple. If no
`resource` is given and the definition is inside the same module,
the first element of the returned tuple would be `None`. If the
location cannot be determined ``(None, None)`` is returned.
"""
... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import shutil
import... | _keys[0]
else:
sorted_cache_keys = sorted(cache_keys) # For commutativity.
combined_id = ','.join([cache_key.id for cache_key in sorted_cache_keys])
combined_hash = ','.join([cache_key.hash for cache_key in sorted_cache_keys])
combined_num_sources = reduce(lambda x, y: x + y,
... | he_key.num_sources for cache_key in sorted_cache_keys], 0)
return CacheKey(combined_id, combined_hash, combined_num_sources)
def key_for_target(self, target, sources=None, transitive=False, fingerprint_strategy=None):
return CacheKey(target.id, target.id, target.num_chunking_units)
def key_for(self, tid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.