prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
rom unittest import TestCase
class TestChecks(TestCase):
def test_get_noqa_lines(self):
checker = QuoteChecker(None, filename=get_absolute_path('data/no_qa.py'))
self.assertEqual(checker.get_noqa_lines(checker.get_file_contents()), [2])
class TestFlake8Stdin(TestCase):
def test_stdin(self):
... | self.assertEqual(list(singles_checker.get_quotes_errors(singles_checker.get_file_contents())), [
{'col': 24, 'line': 1, 'message': 'Q000 Single quotes found but double quotes preferred'},
{'col': 24, 'line': 2, 'message': 'Q000 Single quotes found but double quotes preferred'},
{'col... | ': 'Q000 Single quotes found but double quotes preferred'},
])
class MultilineTestChecks(TestCase):
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
# TODO: put package requirements... | name='proxme',
version='0.1.0',
description="Serves your proxy auto-config (PAC) content.",
long_description=readme + '\n\n' + history,
author="Nick Bargnesi",
author_email='nick@den-4.com',
url='https://github.com/nbargnesi/proxme',
packages=find_packages(include=['proxme']),
includ... | rs=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python ... |
"""
[2016-11-09] Challenge #291 [Intermediate] Reverse Polish Notation Calculator
https://www.reddit.com/r/dailyprogrammer/comments/5c5jx9/20161109_challenge_291_intermediate_reverse/
A little while back we had a programming
[challenge](https://www.reddit.com/r/dailyprogrammer/comments/2yquvm/20150311_challenge_205_i... | .5 1 2 ! * 2 1 ^ + 10 + *
# Formal output
The output is a single number: the result of the calculation. The output should also indicate if the input is not a
valid RPN expression.
**Sample output:**
7
Explanation: the sample input translates to `0.5 * ((1 * 2!) + (2 ^ 1) + 10)`, w | hich comes out to `7`.
## Challenge 1
**Input:** `1 2 3 4 ! + - / 100 *`
**Output:** `-4`
## Challenge 2
**Input:** `100 807 3 331 * + 2 2 1 + 2 + * 5 ^ * 23 10 558 * 10 * + + *`
# Finally...
Hope you enjoyed today's challenge! Have a fun problem or challenge of your own? Drop by /r/dailyprogrammer_ideas and
share it ... |
ature",
native_unit_of_measurement=TEMP_CELSIUS,
value_getter=lambda api: api.getOutsideTemperature(),
device_class=DEVICE_CLASS_TEMPERATURE,
),
ViCareSensorEntityDescription(
key=SENSOR_RETURN_TEMPERATURE,
name="Return Temperature", |
native_unit_of_measurement=TEMP_CELSIUS,
value_getter=lambda api: api.getReturnTemperature(),
device_class=DEVICE_CLASS_TEMPERATURE,
),
ViCareSensorEntityDescription(
key=SENSOR_BOILER_TEMPERATURE,
name="Boiler Temperature",
native_unit_of_measurement=TEMP_CELSIU... | getter=lambda api: api.getBoilerTemperature(),
device_class=DEVICE_CLASS_TEMPERATURE,
),
ViCareSensorEntityDescription(
key=SENSOR_DHW_GAS_CONSUMPTION_TODAY,
name="Hot water gas consumption today",
native_unit_of_measurement=ENERGY_KILO_WATT_HOUR,
value_getter=lambda api:... |
#!/usr/bin/env python
'''
Generate the main window for the pi-gui program. The interface show the last played
item with cover, title and supllemental informations that is interactive
and two buttons for show up the library screen and exit the porgram itself.
'''
#@author: Philipp Sehnert
#@contact: philipp.sehnert[a... | os[0] <= 205 and 190 <= click_ | pos[1] <= 230:
self.funcs['Select Book']()
# exit gui
if 265 <= click_pos[0] <= 315 and 190 <= click_pos[1] <= 230:
self.interface.exit_interface(self.screen)
def run(self):
'''run method for drawing the screen to dispay'''
mainloop = True
# use infin... |
ITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ... | def new_init(self, *args, **kwargs):
ancien_init(self, *args, **kwargs)
self.set_version(cls, cls._version)
cls.__init__ = new_init
else:
cls._version = None
cls._nom = None
INIT, CONSTRUIT = 0, 1
class BaseObj(metaclass=MetaBaseObj):
""... | la classe doit être enregistré,
l'hériter de BaseObj.
"""
importeur = None
enregistrer = False
_nom = "base_obj"
_version = 1
def __init__(self):
"""Instancie un simple statut"""
self._statut = INIT
# On initialise le dictionnaire des versions de l'objet
sel... |
# Copyright (c) 2007 Enough Project.
# See LICENSE for details.
## /* Copyright 2007, Eyal Lotem, Noam Lewis, enoughmail@googlegroups.com */
## /*
## This file is part of Enough.
## Enough is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as pu... | ol.ProcessProtocol):
"""
This class wraps a L{Protocol} instance in a L{ProcessProtocol} instance.
"""
def __init__(self, proto):
self.proto = proto
def connectionMade(self):
self.proto.connectionMade()
def outReceived(self, data):
self.proto.dataReceived(data) |
def errReceived(self, data):
import sys
sys.stderr.write(data)
sys.stderr.flush()
def processEnded(self, reason):
self.proto.connectionLost(reason)
class _DotProtocol(LineReceiver):
delimiter = '\n'
def __init__(self):
self._waiting = None
self._curre... |
is None:
timestamp_format = lambda: int(time.time())
def alert(*params):
formatted_msg = msg_type + "\t" + msg_template % params
timestamped_msg = prepend_timestamp(formatted_msg, timestamp_format)
print >> warnfile, timestamped_msg
return alert
def build_alert_hooks(patterns_... | ite the lastlines file for this source path
# Probably just want to write the last 1-3 lines.
write_lastlines_file(lastlines_dirpath, path, data)
for line in data.splitlines():
lines.append('[%s]\t%s\n' % (path, line))
return lines, bad_pipes
def snuff(subprocs):
... | bprocesses.
Args:
subprocs: list; [subprocess.Popen, ...]
"""
for proc in subprocs:
if proc.poll() is None:
os.kill(proc.pid, signal.SIGKILL)
proc.wait()
def follow_files(follow_paths, outstream, lastlines_dirpath=None, waitsecs=5):
"""Launch tail on a set of fil... |
import ast
import base64
import itertools
from functools import lru_cache
import cpapilib
from flask import session
from app import app
OBJECTS_DICTIONARY = None
@lru_cache(maxsize=5000)
def uid_name(uid_obj):
for obj in OBJECTS_DICTIONARY:
if uid_obj == obj['uid']:
return obj['name']
... | '],
'response': asciiresp
}
else:
taskresponse = {
'target': target,
'status': response['tasks'][0]['status'],
'response': 'Not Available'
}
else:
app.logger.wa... | te within 30 seconds.',
'response': 'Unavailable.'
}
return taskresponse
def show_object(self, objuid):
show_obj_response = self.show('object', uid=objuid)
payload = {
'uid': objuid,
'details-level': 'full'
}
type_obj_respo... |
)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path {0!r} does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_che... | ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
contin | ue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsd... |
# Copyright 2016 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
# This plugin subclasses CurrencyProviderPlugin to provide additional curre... | urrencies provider'
AUTHOR = "Virgil Dupras"
def register_currencies(self):
self.register_currency(
'ATS', 'Austrian schilling',
start_date=date(1998, 1, 2), start_rate=0.1123, stop_date=date(2001, 12, 31), latest_rate=0.10309)
self.register_currency(
'BEF', ... | 1, 2), start_rate=0.03832, stop_date=date(2001, 12, 31), latest_rate=0.03516)
self.register_currency(
'DEM', 'German deutsche mark',
start_date=date(1998, 1, 2), start_rate=0.7904, stop_date=date(2001, 12, 31), latest_rate=0.7253)
self.register_currency(
'ESP', 'Span... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj... | es = 3
self.assertEqual(3, obj.method.cherries)
def test_functions_can_have_inner_functions(self):
function2.get_fruit = function
self.assertEqual('pineapple', function2.get_fruit())
def test_inner_functions_are_unbound(self):
function2.get_fruit = function
try:
... | lf.assertMatch('object has no attribute', ex[0])
# ------------------------------------------------------------------
class BoundClass(object):
def __get__(self, obj, cls):
return (self, obj, cls)
binding = BoundClass()
def test_get_descriptor_resolves_attribute_binding(self):
... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _ | types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GL_SGIX_shadow'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GL,'GL_SGIX_shadow',error_checker=_errors._error_... | PARE_OPERATOR_SGIX=_C('GL_TEXTURE_COMPARE_OPERATOR_SGIX',0x819B)
GL_TEXTURE_COMPARE_SGIX=_C('GL_TEXTURE_COMPARE_SGIX',0x819A)
GL_TEXTURE_GEQUAL_R_SGIX=_C('GL_TEXTURE_GEQUAL_R_SGIX',0x819D)
GL_TEXTURE_LEQUAL_R_SGIX=_C('GL_TEXTURE_LEQUAL_R_SGIX',0x819C)
|
#!/usr/bin/env python
import csv
import sys
from EPPs.common import StepEPP
class GenerateHamiltonInputUPL(StepEPP):
"""Generate a CSV containing the necessary information to batch up to 9 User Prepared Library receipt plates into
one DCT plate. The Hamilton requires input and output plate containers and well... | e outputs found for an input %s. This step is not compatible with replicates.' % artifact.name)
sys.exit(1)
# build a list of the unique input containers for checking that no more than 9 are present (this is due
# to a deck limit on the Hamilton) and for sorting the ... | ner.name)
unique_output_containers.add(output[0].container.name)
# assemble each line of the Hamilton input file in the correct structure for the Hamilton
csv_line = [artifact.container.name, artifact.location[1], output[0].container.name, output[0].location[1],
... |
from collections import Counter as C
i,s=lambda:C(input()),lambda t:sum(t.values());a,b,c=i(),i(),i();a,b,N=a&c,b&c,s(c);print('NO'if any((a+b)[k]<v for k,v in c.i | tems())|(s(a)*2<N)|(s(b)*2<N)else'Y | ES')
|
"""Add search tokens.
Revision ID: 482338e7a7d6
Revises: 41a7e825d108
Create Date: 2014-03-18 00:16:49.525732
"""
# revision identifiers, used by Alembic.
revision = '482338e7a7d6'
down_revision = 'adc646e1f11'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
| 'searchtoken',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('token', sa.String(length=255), nullable=True),
sa.Column('source', sa.Enum('name', 'email_address'), nullab | le=True),
sa.Column('contact_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['contact_id'], ['contact.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('searchtoken')
|
+
self.fee.to_bytes(8, byteorder='big', signed=False) +
self.symbol +
self.name +
self.owner +
self._data.token.decimals.to_bytes(8, byteorder='big', signed=False))
for initial_balance in self._data.to... | statedb and node mempool.
def validate_extended(self, addr_from_state: AddressState, addr_from_pk_state: AddressState):
if not self.validate_slave(addr_from_state, addr_from_pk_state):
return False
tx_balance = addr_from_state.balance
if not AddressState.address_is_valid(self.a... | : %s', bin2hstr(self.addr_from))
return False
if not AddressState.address_is_valid(self.owner):
logger.warning('Invalid address owner_addr: %s', bin2hstr(self.owner))
return False
for address_balance in self.initial_balances:
if not AddressState.address_... |
#!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Action to fingerprint files on the client."""
import hashlib
from grr.parsers import fingerprint
from grr.client import vfs
from grr.client.client_actions import standard
from grr.lib import rdfvalue
class FingerprintFile(standard.ReadBuffe... | if res:
response.matching_types.append(finger.fp_type)
else:
raise RuntimeError("Encountered unknown fingerprint type. %s" %
finger.fp_type)
# Structure of the results is a list of dicts, each containing the
# name of the hashing method, hashes for... | esults = fingerprinter.HashIt()
self.SendReply(response)
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mat", type=str, help="mat file with observations X and side info", required=True)
parser.add_argument("--epochs", type=int, help="number of epochs", default = 2000)
parser.add_argument("--hsize", type=int, help="size of the hidden layer", ... | ain.shape[0], batch_size):
if start + batch_size > Ytrain.shape[0]:
break
idx = rIdx[start : start + batch_size]
by_coord, by_values, by_shape = select_y(Ytrain, idx)
sess.run(train_op, feed_dict={x_u: Fu[idx,:],
x_v: Fv,
... | tb_ratio: Ytrain.shape[0] / float(len(idx)),#Ytrain.nnz / float(by_values.shape[0]),
learning_rate: lrate,
bsize: batch_size
})
## TODO: check from here
## epoch's Ytest e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('historias', '0006_auto_20150413_0001'),
]
operations = [
migrations.AlterField(
model_name='hist... | field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'),
preserve_defa | ult=True,
),
migrations.AlterField(
model_name='ubicaciones',
name='sala',
field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'), (b'SALA 2', b'SALA 2'), (b'SALA 3', b'SALA 3'), (b'SALA 4', b'SALA 4'), (b'SALA 5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'), ... |
__author__ = 'oskyar'
from django.db import models
from django.utils.translation import ugettext as _
from s3direct.fields import S3DirectField
from smart_selects.db_fields import ChainedManyToManyField
# Manager de Asignatura
class SubjectManager(models.Manager):
def owner(self, pk_subject):
return self... | meField(blank=True, null=False)
# pos_image = models.CharField(blank=True, null=True, max_length=250)
objects = SubjectManager()
class Meta:
permissions = (
('view_subject', 'View detail Subject'),
('register | _subject', 'Student registers of subject'),
('unregister_subject', 'Student unregisters of subject')
)
def __str__(self):
return self.name + " (" + self.category + ")"
|
__author_ | _ = 'in | g'
|
# -*- | coding: utf-8 -*-
from src.constant import *
import unittest
from src.game import Game
class TestPlayers(unittest.TestCase):
# Init a player
def test_initPlayer(self):
game = Game()
player = game.cre | atePlayer()
self.assertEqual(player._id, 0)
# Get a valid player
def test_getPlayer(self):
game = Game()
player0 = game.createPlayer()
player1 = game.createPlayer()
self.assertEqual(player0._id, 0)
self.assertEqual(player1._id, 1)
playerN = game.getPlayer... |
# Copyright 2019 The TensorFlow Authors. 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 applica... | rializable(package='Text')
def hard_swish(features):
"""Computes a hard version of the swish function.
This operation can be used to reduce computational cost and improve
quantization for edge devices.
| Args:
features: A `Tensor` representing preactivation values.
Returns:
The activation value.
"""
features = tf.convert_to_tensor(features)
return features * tf.nn.relu6(features + tf.constant(3.)) * (1. / 6.)
@tf.keras.utils.register_keras_serializable(package='Text')
def identity(features):
"""C... |
__ve | rsion__ = "0.1 | .dev0"
|
import unittest
import socket
import os
from shapy.framework.netlink.constants import *
from shapy.framework.netlink.message import *
from shapy.framework.netlink.tc import *
from shapy.framework.netlink.htb import *
from shapy.framework.netlink.connection import Connection
from tests import TCTestCase
class TestClas... | ()+data[36+8+4+48:])
init = Attr(TCA_HTB_INIT,
HTBParms(rate, rate).pack() +
RTab(rate, mtu).pack() + CTab(rate, mtu).pack())
tcm = tcmsg(socket.AF_UNSPEC, self.interface.if_index, handle, self.qhandle, 0,
[Attr(TCA_KIND, 'htb\... | _NEWTCLASS,
flags=NLM_F_EXCL | NLM_F_CREATE | NLM_F_REQUEST | NLM_F_ACK,
service_template=tcm)
self.conn.send(msg)
self.check_ack(self.conn.recv())
self.delete_root_qdisc()
def add_htb_qdisc(self):
tcm = tcmsg(socket.AF_UNSPE... |
from django.apps import | AppConfig
class PagesConfig(AppConfig):
name = 'precision.pages'
verbose_n | ame = "Pages"
|
# coding: utf-8
from sqlalchemy import Column, Float, Integer, Numeric, String, Table, Text
from geoalchemy2.types import Geometry
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class EgoDemandFederalstate(Base):
__tablename__ = 'ego_demand_federalstate... | Float(53)),
Column('sector_consumption_agricultural', Float(53)),
Column('sector_consumption_sum', Float(53)),
Column('sector_peakload_retail', Float(53)),
Column('sector_peakload_residential', Float(53)),
Column('sector_peakload_industrial', Float(53)),
Column('sector_peakload_agricultural', Fl... | n('geom_centroid', Geometry('POINT', 3035)),
Column('geom_surfacepoint', Geometry('POINT', 3035)),
Column('geom_centre', Geometry('POINT', 3035)),
Column('geom', Geometry('POLYGON', 3035), index=True),
schema='demand'
)
t_ego_dp_loadarea_v0_4_5_mview = Table(
'ego_dp_loadarea_v0_4_5_mview', metada... |
#! /usr/bin/env python
# This file is part of the dvbobjects library.
#
# Copyright © 2005-2013 Lorenzo Pallara l.pallara@avalpa.com
#
# 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 ve... | rogram 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 PARTICULA | R PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from math import floor
def MJD_convert(y... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import os
import pytest
from cryptography.ha... | _nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-cbc.txt"],
lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv))
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
... |
),
skip_message="Does not support IDEA OFB",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeOFB(object):
test_OFB = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-ofb.txt"],
lambda key, **kwarg... |
fro | m django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
| from django.utils.translation import ugettext_lazy as _
class RegistrationForm(UserCreationForm):
email = forms.EmailField(help_text='Enter a valid email address')
address = forms.CharField()
website = forms.URLField()
def clean_email(self):
email = self.cleaned_data['email']
try:
... |
# -*- coding:utf-8 -*-
import operator
import string
import operator
import itertools
import snowballstemmer
from textblob import TextBlob, Word
LOWER_MAP = {
'tr': {
ord('I'): u'ı'
}
}
STEMMERS = {
'en': snowballstemmer.stemmer('english'),
'tr': snowballstemmer.stemmer('turkish'),
}
def no... | ist, language, stem=True)
for wordlist in wordlists)
pure = (
tokenize(wordlist, language, stem=False)
for wordlist in wordlists)
return itertools.chain(tokenized, pure)
def is_subsequence(sequence, pa | rent):
for i in xrange(1 + len(parent) - len(sequence)):
if sequence == parent[i:i + len(sequence)]:
return True
return False
|
#!/usr/bin | /python
file = open('prog.txt | ','r')
s = ""
for b in file.read():
s+="%d," % ord(b)
print(s[:-1])
|
from flask import Flask
from flask.ext.quik import FlaskQuik
from flask.ext.quik import render_template
app = Flask(__name__)
quik = | FlaskQuik(app)
@app.route('/', methods=['GET', 'POST'] )
def hello_quik():
return render_te | mplate('hello.html', name='quik')
app.run(host='0.0.0.0', debug=True, port=5000)
|
# -*- coding=utf-8 -*-
"""Test LinkedList for random inputs."""
import pytest
def | test_linkedlist_tail_default():
"""Test LinkedList contstructor for functionality."""
from linked_list import LinkedList
assert LinkedList.tail is None
def test_linkedlist_construct_empty_list():
"""Test LinkedList insert command works with empty list."""
from linked_list import LinkedList
inp... | h empty list."""
from linked_list import LinkedList
input_ = 5
linked_list_instance = LinkedList(input_)
assert linked_list_instance.tail.value == 5
def test_linkedlist_constructor_list_isnode():
"""Test LinkedList contstructor for functionality."""
from linked_list import LinkedList, Node
... |
active_extensions = []
class Extension(object):
def register(self):
pass
def dispatch(event, *args, **kwargs):
for extension in active_extens | ions:
if not hasattr(extension, event):
continue
getattr(extension, event)(*args, **kwargs)
def register(extension):
instance = extension()
activ | e_extensions.append(instance)
instance.register()
|
import asyncio
import demjson
from bot import user_steps, sender, get, downloader
from message import Message
client_id = ''#YOUR CLIENT ID
async def search(query):
global guest_client_id
search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c... | ext("*Not Found*",
reply_to_message_id=message['message_id'], reply_markup=hide_keyboard,
parse_mode="markdown")]
return [Message(chat_id).set_text("Select One Of these :", reply_to_message_id=message['message_id'],
... | reply_markup=show_keyboard)]
elif step == 1:
try:
hide_keyboard = {'hide_keyboard': True, "selective": True}
await sender(Message(chat_id).set_text("*Please Wait*\nLet me Save this Music For You",
reply_to_... |
from __future__ import absolute_import
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.util import *
from autograd import grad
npr.seed(1)
def test_real_type():
fun = lambda x: np.sum(np.real(x))
df = grad(fun)
assert type(df(1.0)) == float
assert type(df(1.0j)) == complex... | un = lambda x: np.sum(np.imag(x))
df = grad(fun)
assert base_class(type(df(1.0 ))) == float
assert base_class(type(df(1.0j))) == complex
# TODO: real times imag
def test_angle_real():
fun = lambda x : to_scalar(np.angle(x))
d_fun = lambda x: to_scalar(grad(fun | )(x))
check_grads(fun, npr.rand())
check_grads(d_fun, npr.rand())
def test_angle_complex():
fun = lambda x : to_scalar(np.angle(x))
d_fun = lambda x: to_scalar(grad(fun)(x))
check_grads(fun, npr.rand() + 1j*npr.rand())
check_grads(d_fun, npr.rand() + 1j*npr.rand())
def test_abs_real():
fun... |
= api.LocalLB.Monitor.get_template_type(template_names=[monitor])[0]
parent2 = api.LocalLB.Monitor.get_parent_template(template_names=[monitor])[0]
if ttype == TEMPLATE_TYPE and parent == parent2:
result = True
else:
module.fail_json(msg='Monitor already exists, but has ... | = type
# end monitor specific stuff
api = bigip_api(server, user, password)
monitor_exists = check_monitor_exists(module, api, monitor, parent)
# ipport is a special setting
if monitor_exists: # make sure to not update current settings if not asked
cur_ipport = get_ipport(api, monitor)
... | rt']
else: # use API defaults if not defined to create it
if interval is None:
interval = 5
if timeout is None:
timeout = 16
if ip is None:
ip = '0.0.0.0'
if port is None:
port = 0
if s... |
from __future__ import print_function
import os.path
import re
import imp
import sys
from shutil import copyfile
import PythonAPI as api
class ValidateFilename(api.PythonAPIRule):
def __init__(self, config):
super(ValidateFilename, self).__init__(config)
def run(self, inputFile, outputFile, encoding):
# NOTE:... | = os.path.basename(self.config["importConfig"]["file"])
prog = re.compile(self.config["regex"], re.UNICODE)
if prog.match(filename) is None:
self.error(filename + " does not match the regular expression " + self.config["regex"])
# Copy the file to the output for | the next rule
copyfile(inputFile, outputFile)
api.process(ValidateFilename)
|
ion values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolu... | rentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (s... | ntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of buil... |
'lo1_address': 'TCPIP0::10.20.61.59::inst0::INSTR',
'lo1_timeout': 5000, 'rf_switch_address': '10.20.61.224',
'use_rf_switch': True,
'pxi_chassis_id': 0,
'hdawg_address': 'hdawg-dev8108',
'awg_tek_address': 'TCP... | mark out 1 for sequencer
self.hdawg.set_marker_out(channel=np.int(2 * sequencer + 1),
| source=7) # set marker 2 to awg mark out 2 for sequencer
for channel in range(8):
self.hdawg.set_amplitude(channel=channel, amplitude=self.pulsed_settings['hdawg_ch%d_amplitude'%channel])
self.hdawg.set_offset(channel=channel, offset=0 * 1.0)
self.hdawg.set_dig... |
import sys
def check_args(argv):
if le | n(argv) != 2:
print ("Help:\n"
"%s fi | lename.log\n"
"filename.log = name of logfile") % argv[0]
sys.exit(1)
|
# -*- coding: UTF-8 -*-
import haystack
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
|
from conference import models
from conference.templatetags.conference import fare_blob
from collections import defaultdict
from datetime import datetime
from xml.sax.saxutils import escape
class Command(BaseCommand):
"""
"""
@transaction.commit_on_success
| def handle(self, *args, **options):
try:
conference = args[0]
except IndexError:
raise CommandError('conference missing')
partner_events = defaultdict(list)
for f in models.Fare.objects.available(conference=conference).filter(ticket_type='partner'):
t... |
from djang | o.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
from squeezemail.tasks import run | _steps
run_steps.delay()
|
import json
from urllib2 import urlopen, HTTPError
from urllib import urlencode
import logging
class HTTPClient(object):
def __init__(self, host='localhost', port=90):
self.host = host
self.port = port
def get_serv_addr (self):
| return 'http://%s:%s/' % ( self.host, self.port, )
def call_handler(self, handler, *args, **kwargs):
url = '%s%s/' % (self.get_serv_addr(), handler)
try: postdata = kwargs.pop('postdata')
except: postdata=None
for arg in args:
url += '%s/' %... | params = urlencode(kwargs)
url = '%s?%s'% (url, params)
logging.debug("Request url: %s" % url)
try: response = urlopen(url, postdata)
except HTTPError as err:
raise(err)
except:
return None
## Reading data:
try:
... |
#
# 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... | icable 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 limitations
# under the License.
"""This module is deprecat... | mport GKEHook
warnings.warn(
"This module is deprecated. Please use `airflow.providers.google.cloud.hooks.kubernetes_engine`",
DeprecationWarning,
stacklevel=2,
)
class GKEClusterHook(GKEHook):
"""This class is deprecated. Please use `airflow.providers.google.cloud.hooks.container.GKEHook`."""
d... |
t Image
from io import BytesIO
from werkzeug.utils import secure_filename
from ..tf2.models import all_classes, TF2BodyGroup, TF2EquipRegion
from ..mods.models import ModClassModel, ModImage
from ..models import get_or_create
from app import db, sentry
def list_from_vdf_dict(dictionary):
return_list = []
for ... | owed_extracts = ['game', 'materials', 'models']
if '..' in infile or infile.startswith('/'):
flash("Error", "danger")
return
if ntpath.dirname(infile).split(ntpath.sep)[0] in allowed_extracts:
to_extract.append(infile)
# How many to extrac... | ecure_filename(name)
folder_name = "{mod_id}".format(mod_id=mod_id)
os.path.altsep = '\\'
zip_open.extractall(os.path.join(output_folder, folder_name), to_extract)
if icon:
# Load the icon into a byte stream
print "Reading TGA image."
try:
... |
# =============================================================================
# 2013+ Copyright (c) Kirill Smorodinnikov <shaitkir@gmail.com>
# All rights reserved.
#
# 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 Fre... | exceptions_policy', tuple(exceptions_p | olicy) + (
elliptics.exceptions_policy.throw_at_start |
elliptics.exceptions_policy.throw_at_wait,
elliptics.exceptions_policy.throw_at_start |
elliptics.exceptions_policy.throw_at_wait |
elliptics.exceptions_policy.throw_at_get |
elliptics.... |
"
datestxt = np.loadtxt(filename, dtype=str)
dates = []
for i in datestxt:
dates.append(dt.datetime.strptime(i, "%m/%d/%Y"))
return pd.TimeSeries(index=dates, data=dates)
GTS_DATES = _cache_dates()
def getMonthNames():
return(['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT',... | tions expire then
if friday in tr | ade_days:
month_close = first + dt.timedelta(days=dif)
else:
month_close = friday
#if day is past the day after that
if month_close < day:
return_date = getNextOptionClose(day, trade_days, offset=1)
else:
return_date = month_close
return(return_date)
def getLastOptio... |
'''Custom models for the block_comment app.'''
import difflib
from django.contrib.comments.models import Comment
from django.db import models
from django.utils.translation import ugettext as _
from block_comment.diff_match_patch import diff_match_patch
class BlockComment(Comment):
'''
``BlockComment`` exten... | else:
| # We've got multiple options, let's narrow them down with
# a smarter matching algorithm.
matcher = diff_match_patch()
for i in tuple(matches):
if matcher.match_main(blocks[i], needle, self.index) < 0:
# No match, d... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 07:54:05 2014
@author: charleslelosq
Carnegie Institution for Science
"""
import sys
sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/")
import csv
import numpy as np
import scipy
import matplotlib
import matplotlib.gridspec as gridspec
from pylab ... | is None:
return (model - data)
return (model - data)/eps
##### CORE OF THE CALCULATION BELOW
#### CALLING THE DATA NAMES
tkMessageBox.showinfo(
"Open file",
"Please open the list of spectra")
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
fi... | en(filename) as inputfile:
results = list(csv.reader(inputfile)) # we read the data list
#### LOOP FOR BEING ABLE TO TREAT MULTIPLE DATA
#### WARNING: OUTPUT ARE AUTOMATICALLY GENERATED IN A DIRECTORY CALLED "DECONV"
#### (see end) THAT SHOULD BE PRESENT !!!!!!!!!!
for lg in range(len(results)):
name = str(res... |
s nn
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from .helpers import build_model_with_cfg
from .layers import SelectiveKernel, ConvBnAct, create_attn
from .registry import register_model
from .resnet import ResNet
def _cfg(url='', **kwargs):
return {
'url': url,
'num_classe... | et50d': _cfg(
first_conv='conv1.0'),
'skresnext50_32x4d': _cfg(
url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/skresnext50_ra-f40e40bf.pth'),
}
class SelectiveKernelBasic(nn.Module):
expansion = 1
| def __init__(self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64,
sk_kwargs=None, reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU,
norm_layer=nn.BatchNorm2d, attn_layer=None, aa_layer=None, drop_block=None, drop_path=None):
sup... |
from gitbarry.reasons impor | t start, finish, switch # , switch, publish
REASONS = {
'start': start,
'finish': fini | sh,
'switch': switch,
# 'publish': publish,
}
|
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/lazylibrarian/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 ... | consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk"
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'https://api.t | witter.com/oauth/authorize'
SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'
def notify_snatch(self, title):
if lazylibrarian.TWITTER_NOTIFY_ONSNATCH:
self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title)
def notify_download(self, title):
... |
import urllib
import urllib2
from bs4 import BeautifulSoup
textToSearch = 'g | orillaz'
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
for vid in soup.findAll(attrs={'class':'yt-uix | -tile-link'}):
print 'https://www.youtube.com' + vid['href']
|
itch_fault(self, *args):
"""
Set switch down (Deletes the OVS switch bridge)
Args:
index: Index of the switch dpid to take out
"""
index = args[0]
dpid = self.dpids[index]
switch_name = self.topo.switches_by_id[index]
switch = next((switch for ... | r of link and switch events available"""
f | uncs = []
for _ in self.topo_watcher.get_eligable_link_events():
funcs.append(self.random_dp_link_fault)
for _ in self.topo_watcher.get_eligable_switch_events():
funcs.append(self.random_switch_fault)
i = self.rng.randrange(len(funcs))
funcs[i]()
def create_r... |
:
self._loadPage("formPage")
inputElement = self.driver.find_element_by_xpath("//input[@id='notWorking']")
self.assertFalse(inputElement.is_enabled())
inputElement = self.driver.find_element_by_xpath("//input[@id='working']")
self.assertTrue(inputElement.is_enabled())
def t... | one.get_attribute("selected"))
self.assertTrue(two.get_attribute("selected") is None)
def testShouldReturnValueOfClassAttributeOfAnElement(self):
self._loadPage("xhtmlTest")
heading = self.driver.find_element_by_xpath("//h1")
classname = heading.get_attribute("class")
self.... | e to issues with Frames
#def testShouldReturnValueOfClassAttributeOfAnElementAfterSwitchingIFrame(self):
# self._loadPage("iframes")
# self.driver.switch_to.frame("iframe1")
#
# wallace = self.driver.find_element_by_xpath("//div[@id='wallace']")
# classname = wallace.get_attribute("c... |
"""Lists VPC offerings"""
from baseCmd import *
from baseResponse import *
class listVPCOfferingsCmd (baseCmd):
typeInfo = {}
def __init__(self):
self.isAsync = "false"
"""list VPC offerings by display text"""
self.displaytext = None
self.typeInfo['displaytext'] = 'string'
... | esize'] = 'integer'
"""list VPC offerings by state"""
se | lf.state = None
self.typeInfo['state'] = 'string'
"""list VPC offerings supporting certain services"""
self.supportedservices = []
self.typeInfo['supportedservices'] = 'list'
self.required = []
class listVPCOfferingsResponse (baseResponse):
typeInfo = {}
def __init__(s... |
from managers import sl2gen
from utils.ssh import SSH
from paramiko import SSHException
import sys
import logging
log | = logging.getLogger("sl2.ion")
def launch_ion(tsuite):
"""Launch ION daemons.
Args:
tsuite: tsuite runtime."""
gdbcmd_path = tsuite.conf["slash2"]["ion_gdb"]
sl2gen.launch_gdb_sl(tsuite, "ion", tsuite.sl2objects["ion"], "sliod", gdbcmd_path)
def create_ion(tsuite):
"""Create ION file systems.
Args:... | dirs, **tsuite.build_dirs)
repl_dict = dict(repl_dict, **ion)
#Create remote connection to server
try:
user, host = tsuite.user, ion["host"]
log.debug("Connecting to {0}@{1}".format(user, host))
ssh = SSH(user, host, '')
cmd = """
mkdir -p {datadir}
mkdir -p {fsroot}
... |
correct name and colour.
self.assertEqual(class_details(CLASS_DEATH_KNIGHT),
{'colour': 0xC41F3B, 'name': 'Death Knight'})
def test_for_shaman_class(self):
# Makes sure that when the id for the Shaman class is passed we get the
# correct name and colour.
self.assertEqual(cl... | we get the
# correct name and colour.
self.assertEqual(class_details(CLASS_MAGE),
{'colour': 0x69CCF0, 'name': 'Mage'})
def test_for_warlock_class(self):
# Makes sure that when the id for the Warlock class is passed we get the
# correct name and colour.
self.assertE... | the id for the Monk class is passed we get the
# correct name and colour.
self.assertEqual(class_details(CLASS_MONK),
{'colour': 0x00FF96, 'name': 'Monk'})
def test_for_druid_class(self):
# Makes sure that when the id for the Druid class is passed we get the
# correct name ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | sync(version=None):
db_version()
repo_path = _find_migrate_repo()
return versioning_api.upgrade(FLAGS.sql_connection, repo_path, version)
def db_version():
repo_path = _find_migrate_repo()
try:
return versioning_api.db_version(FLAGS.sql_connection, repo_path)
except versioning_exceptio... | control, check for that
# and set up version_control appropriately
meta = sqlalchemy.MetaData()
engine = sqlalchemy.create_engine(FLAGS.sql_connection, echo=False)
meta.reflect(bind=engine)
try:
for table in ('auth_tokens', 'zones', 'export_devices',
... |
ClosePane(self, pane_info):
"""
Destroys or hides the pane depending on its flags.
:param `pane_info`: a L{AuiPaneInfo} instance.
"""
# if we were maximized, restore
if pane_info.IsMaximized():
self.RestorePane(pane_info)
if pane_info.frame:
... | this style, all tabs have the same width
``AUI_NB_SCROLL_BUTTONS`` With this style, left and right scroll buttons are displayed
``AUI_NB_WINDOWLIST_BUTTON`` With this style, a drop-down list of windows is available
``AUI_NB_CLOSE_BUTTON`` With this style, a clo... | lose button is available on the active tab
``AUI_NB_CLOSE_ON_ALL_TABS`` With this style, a close button is available on all tabs
``AUI_NB_MIDDLE_CLICK_CLOSE`` Al |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 15:52:33 2014
@author: raffaelerainone
"""
from time import clock
from math import sqrt
def is_prime(n):
check=True
i=2
while check and i<=sqrt(n):
if n%i==0:
check=False
i+=1
return check
start = clock()
lim=50*(10**6)... | nt(lim**(0.5))) if is_prime(i)]
prime_3 = [i for i in prime_ | 2 if i<(int(lim**(0.34)))]
prime_4 = [i for i in prime_3 if i<(int(lim**(0.25)))]
for i in prime_2:
for j in prime_3:
for k in prime_4:
x=(i**2)+(j**3)+(k**4)
if x<lim:
A.append(x)
print len(set(A))
print clock() - start |
# This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .int64 import Int64
from .transaction_result_ext import TransactionResultExt
from .transaction_result_result import TransactionResul... | unpacker = Unpacker(xdr)
return cls.unpack(unpacker)
def to_xdr(self) -> str:
xdr_bytes = self.to_xdr_bytes()
return base64.b64encode(xdr_bytes).decode()
@classmethod
def from_xdr(cls, xdr: str) -> "TransactionResult":
xdr_bytes = base64.b64decode(xdr.encode())
ret... | self.fee_charged == other.fee_charged
and self.result == other.result
and self.ext == other.ext
)
def __str__(self):
out = [
f"fee_charged={self.fee_charged}",
f"result={self.result}",
f"ext={self.ext}",
]
return f"<Transa... |
import os
from .ruby impor | t RubyExecutor
class Executor(RubyExecutor):
name = 'RUBY19'
def get_nproc(self):
return [-1, 1][os.name == 'nt']
def get_security(self):
from cptbox.syscalls import sys_write
sec = super( | Executor, self).get_security()
sec[sys_write] = lambda debugger: debugger.arg0 in (1, 2, 4)
return sec
initialize = Executor.initialize
|
import pytest
from gosa.comm | on import Environment
from gosa.common.components import PluginRegistry, ObjectRegistry
import os
def pytest_unconfigure(config):
PluginRegistry.getInstance('HTTPService').srv.stop()
PluginRegistry.shutdown()
|
@pytest.fixture(scope="session", autouse=True)
def use_test_config():
oreg = ObjectRegistry.getInstance() # @UnusedVariable
pr = PluginRegistry() # @UnusedVariable
cr = PluginRegistry.getInstance("CommandRegistry") # @UnusedVariable
|
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# Gestión de parámetros de configuración - xbmc
#------------------------------------------------------------
# tvalacarta
# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/
#--------------------------------------------------------... | d_path)
try:
os.mkdir(download_path)
except:
pass
# Create download_list_path if not exists
if not download_list_path.lower().startswith("smb") and not os.path.exists(download_list_path):
| logger.debug("Creating download_list_path "+download_list_path)
try:
os.mkdir(download_list_path)
except:
pass
# Create bookmark_path if not exists
if not bookmark_path.lower().startswith("smb") and not os.path.exists(bookmark_path):
logger.debug("Creating bo... |
impor | t plog.plog as plg
PLOG = plg.PLOG
plog_color = plg.plog_color
plog = plg.plog
def perr(*msg, delim=" "):
plog(* | msg, type=PLOG.err, delim=delim)
def pwrn(*msg, delim=" "):
plog(*msg, type=PLOG.warn, delim=delim)
__all__ = ["PLOG", "plog_color", "plog", "perr", "pwrn"]
|
lass RegressionTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
def tearDown(self):
self.con.close()
def CheckPragmaUserVersion(self):
# This used to crash pysqlite because this pragma command returns NULL for the column name
cur = s... | lCheck(self):
"""
Verifies | that connection methods check whether base class __init__ was
called.
"""
class Connection(sqlite.Connection):
def __init__(self, name):
pass
con = Connection(":memory:")
try:
cur = con.cursor()
self.fail("should have... |
.ext.viewcode',
'sphinx.ext.intersphinx', 'sphinx.ext.autosummary']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master to... | ntry, description, category)
texinfo_documents = [
('index', 'Kurt', u'Kurt Documentation',
u'Tim Radvan', 'Kurt', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_ind... | ---------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'Kurt'
epub_author = u'Tim Radvan'
epub_publisher = u'Tim Radvan'
epub_copyright = u'2013, Tim Radvan'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
#... |
# coding: utf-8
try:
from django.conf.urls import patterns, url, include
e | xcept ImportError:
from django.conf.urls.defaults import patterns, url, include
from django.http import HttpResponse
def dummy(request):
return HttpResponse()
urlpatterns = patterns('',
url('^api/.+/$', dummy, name='dummy'),
url('', include('django. | contrib.auth.urls', app_name='auth', namespace='auth'))
)
|
#
# usage: python k44.py {file | name} {number}
#
import sys
import pydot
from k41 import *
from k42 import get_relation_pairs
if __name__ == '__main__':
fn, nos = sys.argv[1], int(sys.argv[2])
sl = load_cabocha(fn)
| pl = get_relation_pairs([sl[nos-1]])
g = pydot.graph_from_edges(pl)
g.write_png('result.png', prog='dot')
|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from pants.option.option_types import DictOption
from pants.option.subsystem import Subsystem
DEFAULT_SCALA_VERSION = "2.13.6"
_logger... | r_resolve = DictOption[str](
"--version-for-resolve",
help=(
"A dictionary mapping the name of a resolve to the Scala version to use for all Scala "
"targets c | onsuming that resolve.\n\n"
'All Scala-compiled jars on a resolve\'s classpath must be "compatible" with one another and '
"with all Scala-compiled first-party sources from `scala_sources` (and other Scala target types) "
"using that resolve. The option sets the Scala version that wi... |
" | ""
File Allocation Table (FAT) / 12 bit version
Used primarily for diskettes
"""
| |
0x02: ('CALC', 1),
0x03: ('FIFO_I', 1),
0x04: ('FIFO_II', 1),
0x05: ('FIFO_DATA', 1),
0x06: ('ID_DATA', 1),
0x07: ('RC_OSC_I', 1),
0x08: ('RC_OSC_II', 1),
0x09: ('RC_OSC_III', 1),
0x0a: ('CKO_PIN', 1),
0x0b: ('GPIO1_PIN_I... | , 1),
0x13: ('PLL_V', 1),
0x14: ('TX_I', 1),
0x15: ('TX_II', 1),
0x16: ('DELAY_I', 1),
0x17: ('DELAY_II', 1),
0x | 18: ('RX', 1),
0x19: ('RX_GAIN_I', 1),
0x1a: ('RX_GAIN_II', 1),
0x1b: ('RX_GAIN_III', 1),
0x1c: ('RX_GAIN_IV', 1),
0x1d: ('RSSI_THRES', 1),
0x1e: ('ADC', 1),
0x1f: ('CODE_I', 1),
0x20: ('CODE_II', 1),
0x21: ('CODE_III', ... |
#This script is for produsing a new list of sites extracted from alexa top site list
import re
p | refix = 'http://'
#suffix = '</td><td></td></tr><tr><td>waitForPageToLoad</td><td></td><td>3000</td></tr>'
with open('top100_alexa.txt','r') as f:
newlines = []
for line i | n f.readlines():
found=re.sub(r'\d+', '', line)
line=found
newlines.append(line.replace(',', ''))
with open('urls.txt', 'w') as f:
for line in newlines:
#f.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))
f.write('%s%s\n' % (prefix, line.rstrip('\n'))) |
__author__ = "Konstantin Osipov <kostja.osipov@gmail.com>"
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... | = '\n'
class AdminConnection(TarantoolConnection):
def execute_no_reconnect(self, command, silent):
if not command:
return
if not silent:
sys.stdout.write(command + ADMIN_SEPARATOR)
| cmd = command.replace('\n', ' ') + ADMIN_SEPARATOR
self.socket.sendall(cmd)
bufsiz = 4096
res = ""
while True:
buf = self.socket.recv(bufsiz)
if not buf:
break
res = res + buf
if (res.rfind("\n...\n") >= 0 or res.rfind("\... |
import lms_code.lib.rep2 as rep2
from lms_code.analysis.run_bem import bemify, boundary_conditions,\
assemble, constrain, solve, evaluate_surface_disp
from lms_code.analysis.simplified_bem import create_surface_mesh, \
set_params
from codim1.core import simple_line_mesh, combine_meshes, ray_mesh
def create_fau... | top = d['intersection_pt']
joint = [4.20012e5 + 1.6, -2.006e4 - 5]
bottom = [3.09134e5 + 1.1, -2.3376e4 - 3]
detach = simple_line_mesh(d['fault_elements'], bottom, joint)
d['fault_mesh'] = detach
if __name__ == "__main__":
d = dict()
set_params(d)
create_fault_mesh(d)
create_surface_me... | solve(d)
evaluate_surface_disp(d)
rep2.save("bem_just_detach", d)
|
y of the corresponding losses. ``returns`` is built up
in a similar way, containing just the unprocessed results of one
``session.run`` call (effectively of one batch).
Labels and decodings are converted to text before splicing them into their
corresponding results_tuple lists. In the case of decodings,... | self.id = new_id()
self.index = index
self.num_jobs = num_jobs
self.set_name = set_name
self.report = report
self.wer = -1
self.loss = -1
self.mean_edit_distance = -1
self.jobs_open = []
self.jobs_running = []
| self.jobs_done = []
self.samples = []
for i in range(self.num_jobs):
self.jobs_open.append(WorkerJob(self.id, self.index, self.set_name, FLAGS.iters_per_worker, self.report))
def name(self):
'''Gets a printable name for this epoch.
Returns:
str. printa... |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 you... | -
class HasNoLatOrLon(Rule):
"""Rul | e that checks if Latitude or Longitude are not given"""
labels = []
name = _('Places with no latitude or longitude given')
description = _("Matches places with empty latitude or longitude")
category = _('Position filters')
def apply(self,db,place):
if place.get_latitude().strip and place.... |
import os
import numpy as np
import nibabel as nb
import nighresjava
from ..io import load_volume, save_volume
from ..utils import _output_dir_4saving, _fname_4saving
def levelset_curvature(levelset_image, distance=1.0,
save_data=False, overwrite=False, output_dir=None,
... | (initialheap=mem['init'], maxheap=mem['max'])
except ValueError:
pass
# create algorithm instance
algori | thm = nighresjava.LevelsetCurvature()
# set parameters
algorithm.setMaxDistance(distance)
# load images and set dimensions and resolution
input_image = load_volume(levelset_image)
data = input_image.get_data()
affine = input_image.get_affine()
header = input_image.get_header()
resoluti... |
# based on killer algo found here:
# http://codereview.stackexchange.com/questions/12922/inversion-count-using-merge-sort
import sy | s, bisect
input_list = map(int,open(sys.argv[1]))
sorted_list = sorted(input_list)
inversions = 0
# we compare the unsorted list to the sorted list
# to compute inversion count, neat!
for d in input_list:
#locate insertion point in sorted_list for d
| p = bisect.bisect_left(sorted_list,d)
inversions += p
input_list.pop(p)
print inversions
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class UnitDialogue:
"""
Unit dialogue model
"""
def __init__(self, **kwargs):
self.db = kwargs["db"]
self.dialogue = {}
def _get_unit_dialogue_map(self, dialogue):
unit_dialogue_map = {}
for unit_dialogue in dialogue... | self):
"""
Get unit dialogue IDs. Those will be queried
against the dialogue collection to get the rest
of the dialogue information
"""
cursor = self.db.cursor()
cursor.execute("""SELECT
ud.id,
ud.id AS dialogue... | ud.dialogue,
ud.context
FROM spiffyrpg_unit_dialogue ud
LEFT JOIN spiffyrpg_units u ON u.id = ud.unit_id""")
tmp_dialogue = cursor.fetchall()
cursor.close()
dialogue = []
if tmp_dialogue:
... |
from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... |
# Preprocess sex to ensure it's a valid value
sex = fields['sex'][0].upper() if fields.get('sex', None) else None
if sex not in ['M', 'F']:
sex = ''
appointment = Appointment(
user=user,
action=action,
c... | date=date,
time=time,
# Optional fields...
first_name=fields.get('first_name',''),
last_name=fields.get('last_name',''),
nationality = fields.get('nationality',''),
sex=sex,
# See if this works witho... |
except ValueError:
return False
#end def is_float
def is_float(var):
try:
float(var)
return True
except ValueError:
return False
#end def is_float
def is_array(var,type,delim=None):
try:
if isinstance(var,str):
array(var.split(delim),type)
els... | :
if l.strip()!='':
sr+=l + '\n'
#end if
#end for
return sr
#end def remove_empty_lines
def contains_any(str, set):
for c in set:
if c in str: return 1;
return 0;
#end def contains_any
def contains_all(str, set):
for c in set:
if c not in str: return 0;... | rn 1;
#end def contains_all
invalid_variable_name_chars=set('!"#$%&\'()*+,-./:;<=>?@[\\]^`{|}-\n\t ')
def valid_variable_name(s):
return not contains_any(s,invalid_variable_name_chars)
#end def valid_variable_name
def split_delims(s,delims=['.','-','_']):
sp = s
for d in delims:
sp = sp.replace(... |
if out_of_date(code_path, img.filename(format)):
all_exists = False
break
img.formats.append(format)
# assume that if we have one, we have them all
if not all_exists:
all_exists = (j > 0)
break
... | ttings.env.config
nofigs = options.has_key('nofigs')
options.setdefault('include-source', config.plot_include_source)
context = options.has_key('context')
rst_file = document.attributes['source']
rst_dir = os.path.dirname(rst_file)
if len(arguments):
if not config.plot_basedir:
... | directives.uri(arguments[0]))
else:
source_file_name = os.path.join(setup.confdir, config.plot_basedir,
directives.uri(arguments[0]))
# If there is content, it will be passed as a caption.
caption = '\n'.join... |
FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import inspect
import six
from collections import defaultdict, deque
import logging
logger = logging.getLogger(__name__)
def first_non_none_response(responses, default=None):
"""Find first non None response in a ... | dlers = _PrefixTrie()
def emit(self, event_name, **kwargs):
responses = []
# Invoke the event handlers from most specific
# to least specific, each time stripping off a dot.
logger.debug('emit: %s' % event_name)
if event_name in self._lookup_cache:
handlers_to_ca... | self._lookup_cache[event_name] = handlers_to_call
kwargs['event_name'] = event_name
responses = []
for handler in handlers_to_call:
logger.debug('emit: calling %s' % handler)
response = handler(**kwargs)
responses.append((handler, response))
return... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from nltk import download
TOKENIZER_MODEL = "punkt"
POS_TAGGER = "maxent_treebank_pos_tagger"
def downloadDependencies():
download(TOKENIZER_MODEL)
downl | oad(POS | _TAGGER)
if __name__ == '__main__':
downloadDependencies()
|
# Copyright 2019 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | pters import (
CephRelationAdapter,
)
from charms_openstack.plugins.classes import (
BaseOpenStackCephCharm,
CephCharm,
PolicydOverridePlugin,
)
from charms_openstack.plugins.trilio import (
TrilioVaultCharm,
TrilioVaultSubordinateCharm,
TrilioVaultCharmGhostAction,
)
__all__ = (
"BaseO... | "TrilioVaultCharm",
"TrilioVaultSubordinateCharm",
"TrilioVaultCharmGhostAction",
)
|
import numpy as np
import warnings
from scipy._lib._util import check_random_state
def rvs_ratio_uniforms(pdf, umax, vmin, vmax, size=1, c=0, random_state=None):
"""
Generate random samples from a probability density function using the
ratio-of-uniforms method.
Parameters
----------
pdf : cal... | U, V)` uniformly on `R` and return
`V/U + c` if `(U, V)` are also in `A` which can be directly
verified.
Intuitively, the method works well if `A` fills up most of the
enclosing rectangle such that the probability is high that `(U, V)`
| lies in `A` whenever it lies in `R` as the number of required
iterations becomes too large otherwise. To be more precise, note that
the expected number of iterations to draw `(U, V)` uniformly
distributed on `R` such that `(U, V)` is also in `A` is given by
the ratio ``area(R) / area(A) = 2 * umax * (vm... |
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Thumb Joystick (http://www.seeedstudio.com/wiki/Grove_-_Thumb_Joystick)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask... | which is why the GrovePi shares Arduino pins between adjacent ports
# If the sensor has a pin definition SIG,NC,VCC,GND, the second (white) pin is not connected to anything
# If you wish to connect two joysticks, use ports A0 and A2 (skip A1)
# Uses two pins - one for the X axis and one for the Y axis
# This configur... | Mode(yPin,"INPUT")
# The Grove Thumb Joystick is an analog device that outputs analog signal ranging from 0 to 1023
# The X and Y axes are two ~10k potentiometers and a momentary push button which shorts the x axis
# My joystick produces slightly different results to the specifications found on the url above
# I've l... |
# Copyright 2017 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 a... | paths:
assert src.startswith(strip_prefix)
js = subprocess.check_output([html2js, src, '--module', module_name],
env={})
template_name = prepend_prefix + src[len(strip_prefix):]
js = js.replace(src, template_name)
| result.append(js)
result.append("{} = angular.module('{}');".format(goog_provide, module_name))
print '\n'.join(result)
if __name__ == '__main__':
main(sys.argv)
|
from amitools.vamos.astructs import LibraryStruct
from amitools.vamos.atypes import Library, NodeType
from amitools.fd import read_lib_fd, generate_fd
from .vlib import VLib
from .stub import LibStubGen
from .patch import LibPatcherMultiTrap
from .impl import LibImplScanner
class LibCreator(object):
"""create a vam... | stub = self.stub_gen.gen_fake_stub(name, fd, ctx, profile)
struct = Libr | aryStruct
else:
stub = self.stub_gen.gen_stub(scan, ctx, profile)
struct = impl.get_struct_def()
# adjust info pos/neg size
if info.pos_size == 0:
info.pos_size = struct.get_size()
if info.neg_size == 0:
info.neg_size = fd.get_neg_size()
# allocate and init lib
library = ... |
#!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | s', interpolation='nearest')
plt.show()
def recordAndEncode(stream, soundEncoder):
window = np.blackman(CHANNELS*CHUNK)
sdrs = []
print "---recording---"
for _ in range(0, (RATE/CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
transformedData = transformData(data, window)
sdr = soundEncoder... | 300
w = 31
minval = 20
maxval = 10000
soundEncoder = SoundEncoder(n, w, RATE, CHUNK, minval, maxval)
stream = getAudioStream()
sdrs = recordAndEncode(stream, soundEncoder)
visualizeSDRs(sdrs)
|
"""Integration tests for client-server interaction."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from multiprocessing import Process
import os
import shutil
import tempfile
import time
import unittest
from filetracker.client import Client, Filetracke... | with open(src_file, 'wb') as sf:
sf.write(b'version 3 (1)')
self.client.put_file('/older.txt@1', src_file)
f, _ = self.client.get_stream('/older.txt')
self.assertEqual(f.read(), b'version 2')
with self.assertRaises(FiletrackerError):
self.client.get_strea... | onexistent.txt')
def test_delete_nonexistent_should_404(self):
with self.assertRaisesRegexp(FiletrackerError, "404"):
self.client.delete_file('/nonexistent.txt')
def test_delete_should_remove_file_and_dir(self):
src_file = os.path.join(self.temp_dir, 'del.txt')
with open(s... |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import sqlalchemy as sa
from buildbot.test.util i... | on.MigrateTestMixin, unittest.TestCase):
def setUp(self):
return self.setUpMigrateTest()
def tearDown(self):
return self.tearDownMigrateTest()
cols = [
'buildrequests.id',
'builds.id',
'buildsets.id',
'changes.changeid',
'patches.id',
'sourc... |
# 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... | .qnn.op.quantize(a_var, s_var, z_var, axis=axis, out_dtype=out_dtype)
with tvm.transform.PassContext(opt_level=3):
lib = | relay.build(tvm.IRModule.from_expr(real_q_op), target=target)
# Get real qnn quantize output.
m = graph_executor.GraphModule(lib["default"](dev))
m.set_input("a", a_np)
m.run()
real_q_out = m.get_output(0)
# Compile the simulated quantize function.
with tvm.tar... |
"""Tests for registry module - datasets method"""
import vcr
from pygbif import registry
@vcr.use_cassette("test/vcr_cassettes/test_datasets.yaml")
def test_datasets():
"registry.datasets - basic test"
res = registry.datasets()
assert dict == res.__class__
@vcr.use_cassette("t | est/vcr_cassettes/test_datasets_limit.yaml")
def test_datasets_limit():
"registry.datasets - limit param"
res = registry.datasets(limit=1)
assert dict == res.__class__
assert 1 == len(res["results"])
res = registry.datasets(limit=3)
assert dict == res.__class__
assert 3 == len(res["results"... | vv = [x["type"] for x in res["results"]]
assert dict == res.__class__
assert 100 == len(res["results"])
assert "OCCURRENCE" == list(set(vv))[0]
|
See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__... | /buildbot.sourceforge.net/"
c['buildbotURL'] = "http://localhost:8010/"
"""
# Template for master configuration just before worker renaming.
sample_0_9_0b5 = """\
from buildbot.plugins import *
c = BuildmasterConfig = {}
c['slaves'] = [buildslave.BuildSlave("example-slave", "pass")]
c['protocols'] = {'pb': {'port':... | //github.com/buildbot/hello-world.git',
workdir='gitpoller-workdir', branch='master',
pollinterval=300))
c['schedulers'] = []
c['schedulers'].append(schedulers.SingleBranchScheduler(
name="all",
change_filter=util.ChangeFilter(branch='master'),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.