prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
u" "
in_leaf = Leaf(token.NAME, u"in")
in_leaf.prefix = u" "
inner_args = [for_leaf, fp, in_leaf, it]
if test:
test.prefix = u" "
if_leaf = Leaf(token.NAME, u"if")
if_leaf.prefix = u" "
inner_args.append(Node(syms.comp_if, [if_leaf, test]))
inner = Node(syms.listmake... | 'sorted'
trailer< '(' arglist<node=any any*> ')' >
any*
>
" | ""
pats_built = False
def in_special_context(node):
""" Returns true if node is in an environment where all that is required
of it is being itterable (ie, it doesn't matter if it returns a list
or an itterator).
See test_map_nochange in test_fixers.py for some examples and tests.
"""... |
ould be placed in. Defaults to ``ALL``.
task_class (class): Optional. The class to use for instantiating
tasks. Defaults to ``Task``.
backend_class (class): Optional. The class to use for
instantiating the backend. Defaults to ``None`` (DSN
detecti... | `Client`` instance
"""
backend_name, _ = conn_string.split(":", 1)
backend_path = "alligator.backends.{}_backend".format(backe | nd_name)
client_class = import_attr(backend_path, "Client")
return client_class(conn_string)
def len(self):
"""
Returns the number of remaining queued tasks.
Returns:
int: A count of the remaining tasks
"""
return self.backend.len(self.queue_name... |
from temboo.Library.Utilities.XML.GetValuesFromXML import Get | ValuesFromXML, GetValuesFromXMLInputSet, GetValuesFromXMLResultSet, GetValuesFromXMLChoreographyExecution
from temboo.Library.Utilities.XML.RunXPathQuery import RunXPathQuery, RunXPathQueryInputSet, RunXPathQueryResultSet, RunXPathQueryChoreo | graphyExecution
|
# Copyright 2015 Andrea Frittoli <andrea.frittoli@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | :
flask_restful.abort(404, message=str(snfe))
@handle_validate
def post(self, topic, username):
# Subscribe to a topic
try:
manager.create_subscription(topic=topic, username=username)
return '', 200
except eowyn_exc.SubscriptionAlreadyExistsException:... | lete(self, topic, username):
# Unsubscribe from a topic
try:
manager.delete_subscription(topic=topic, username=username)
return '', 200
except eowyn_exc.SubscriptionNotFoundException as snfe:
flask_restful.abort(404, message=str(snfe))
class Message(flask_re... |
"""
@author:
"""
import bottle
# this variable MUST be used as the name for the cookie used by this application
COOKIE_NAME = 'sessionid'
def check_login(db, usernick, password):
"""returns True if password matches stored"""
def generate_session(db, usernick):
"""create a new session and add a cookie to t... | on(db, usernick):
"""remove all session table entries for this user"""
def session_user | (db):
"""try to
retrieve the user from the sessions table
return usernick or None if no valid session is present"""
|
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
import sys
from textwrap import dedent
from twitter.common.contextutil import pushd
from pex.testing import temporary_content
def assert_entry_points(entry_... | s.path.join(project_dir, 'dist', 'my_app-0.0.0.pex')],
stdout=subprocess.PIPE)
stdout, _ = process.communicate()
assert 0 == process.returncode
assert stdout == b'hello world!\n'
def test_entry_points_dict():
assert_entry_points({'console_scripts': ['my_app = my_ap... | t("""
[console_scripts]
my_app=my_app:do_something
"""))
|
# -*- coding: utf-8 -*-
"""This module defines functions generally useful in scikit-ci."""
import os
from .constants import SERVICES, SERVICES_ENV_VAR
def current_service():
for service, env_var in SERVICES_ENV_VAR.items():
if os.environ.get(env_var, 'false').lower() == 'true':
return servi... | if predicate is None:
def predicate(line):
return line.strip()
def prefixed_lines():
for line in text.splitlines(True):
| yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
|
"""Example shows how to send requests and get responses."""
import asyncio
from obswsrc import OBSWS
from obswsrc.requests import ResponseStatus, StartStreamingRequest
from obswsrc.types import Stream, StreamSettings
async def main():
async with OBSWS('localhost', 4444, "password") as obsws:
# We can ... |
)
stream = Stream(
settings=stream_settings,
type= | "rtmp_custom",
)
# Now let's actually perform a request
response = await obsws.require(StartStreamingRequest(stream=stream))
# Check if everything is OK
if response.status == ResponseStatus.OK:
print("Streaming has started")
else:
print("Couldn't... |
from json import loads
import codecs
import environ
FIXTURE_PATH = (environ.Path(__file__) - 1).path('fixtures')
def read_json(fpath):
with codecs.open(fpath, 'rb', encoding='utf-8') as fp:
| return loads(fp.read())
def read_fixtu | re(*subpath):
fixture_file = str(FIXTURE_PATH.path(*subpath))
return read_json(fixture_file)
|
from typing import Callable, List, Dict, Optional
import numpy as np
from typeguard import check_argument_types
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder,
SearchStepOutput)
from ne... | token_id = evaluated_bs.token_ids[time][hyp_index]
token = self._vocabulary.index_to_word[token_id]
output_tokens.append(token)
hyp_index = evaluated_bs.parent_ids[time][hyp_index]
output_tokens.reverse()
before_eos_tokens = [] # type: List[str]
for tok ... | s not None:
decoded_tokens = self._postprocess([before_eos_tokens])
else:
decoded_tokens = [before_eos_tokens]
self.result = ExecutionResult(
outputs=decoded_tokens,
losses=[bs_score],
scalar_summaries=None,
histogram_summaries=Non... |
class MyStuff(object):
| def __init__(self):
self.tangerine = "And now a thousand y | ears between"
def apple(self):
print "I am classy apples!"
|
Fixture(
net_helpers.OVSPortFixture(self.br, self.dst_namespace)).port
# wait to add IPs until after anti-spoof rules to ensure ARP doesn't
# happen before
def collect_flows_and_ports(self, exc_info):
nicevif = lambda x: ['%s=%s' % (k, getattr(x, k))
... | , count=2)
def test_arp_spoof_icmpv6_neigh_advt_allowed_address_pairs(self):
self.src_addr = '2000::1'
self.dst_addr = '2000::2'
self._setup_arp_spoof_for_port(self.dst_p.name, ['2000::3',
self.dst_addr])
self.src_p.addr.add('... | ddr.add('%s/64' % self.dst_addr)
# make sure the IPv6 addresses are ready before pinging
self.src_p.addr.wait_until_address_ready(self.src_addr)
self.dst_p.addr.wait_until_address_ready(self.dst_addr)
net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)
def test_arp_s... |
from app.app_and_db import app
from flask import Blueprint, jsonify, render_template
import datetime
import random
import requests
dashboard = Blueprint('dashboard', __name__)
cumtd_endpoint = 'https://develope | r.cumtd.com/api/{0}/{1}/{2}'
cumtd_endpoint = cumtd_endpoint.format('v2.2', 'json', 'GetDeparturesByStop')
wunderground_endpoint = 'http://api.wunderground.com/api/{0}/hourly/q/{1}/{2}.json'
wunderground_endpoint = wunderground_endpoint.format(app.config['WUNDERGROUND_API_KEY'], 'IL', 'Champaign')
@dashbo | ard.route('/')
def index():
time=datetime.datetime.now().time().strftime('%I:%M').lstrip('0')
return render_template('pages/dashboard.html', image_number=random.randrange(1, 9), time=time)
#Query no more than once a minute
@dashboard.route('/bus')
def bus_schedule():
params = {'key' : app.config['CUMTD_API_KEY']... |
me = 'Segment %s content %d' % (segment_label, contentid)
command_finish = 'Started %s segment with content %d and port %d at %s' % (segment_label, contentid, segment_port, segment_dir)
runcommands(commands, thread_name, command_finish)
@staticmethod
def getRole(contentid):
if contentid... | segment_contentid = segconfig.content
segment_dir = segconfig.fselocation
if segment_contentid == GpSegmentConfiguration.MASTER_CONTENT_ID:
segment_type = 'master'
elif segconfig.preferred_role == GpSegmentConfiguration.ROLE_PRIMARY:
segment_type = 'primary'
else... | ment_type = 'mirror'
commands.append("pg_ctl -D %s stop" % segment_dir)
thread_name = 'Segment %s content %d' % (segment_type, segment_contentid)
command_finish = 'Stopped %s segment at %s' % (segment_type, segment_dir)
runcommands(commands, thread_name, command_finish)
def run(se... |
# This file is part of the dionaea honeypot
#
# SPDX-FileCopyrightText: 2009 Paul Baecher & Markus Koetter & Mark Schloesser
#
# SPDX-License-Identifier: GPL-2.0-or-later
from dionaea.core import connection
class echo(connection):
def __init__ (self, proto=None):
print("echo init")
connection.__ini... | outed!\n")
return False
def handle_disconnect(self):
self.send("disconnecting you!\n")
def handle_io_in(self,data):
print('py_io_in\n')
self.send(data[::-1][1:] + b' | \n')
return len(data)
#
#e = echo(proto='tcp')
#e.bind('0.0.0.0',4713,'')
#e.listen()
|
from __future__ import absolute_import
from sqlalchemy import types
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql.base import ischema_names, PGTypeCompiler
from sqlalchemy.sql import expression
from ..primitives import Ltree
from .scalar_coercible import ScalarCoercible
class ... | or details.
"""
__visit_name__ = 'LTXTQUERY'
ischema_names['ltree'] = LtreeType
ischema_names['lquery'] = LQUERY
ische | ma_names['ltxtquery'] = LTXTQUERY
def visit_LTREE(self, type_, **kw):
return 'LTREE'
def visit_LQUERY(self, type_, **kw):
return 'LQUERY'
def visit_LTXTQUERY(self, type_, **kw):
return 'LTXTQUERY'
PGTypeCompiler.visit_LTREE = visit_LTREE
PGTypeCompiler.visit_LQUERY = visit_LQUERY
PGTypeCompiler.visi... |
from django.conf.urls import patterns, url
from django.views.generic impo | rt TemplateView
from django.contrib.auth.decorators import login_required, user_passes_test
urlpatterns = patterns('',
url(r'^$', 'website.views.index', name='website_index'),
url(r'^termos/$',TemplateView.as_view(template_name='website/termos_de_uso.html'), name='website_termos'),
url(r'^sobre/$', Templa... | name='website_relatorios'),
)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-17 09:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("impart", "0004_auto_20170117_0916")]
operations = [
| migrations.AlterField(
| model_name="contact",
name="artist",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="impart.Artist",
),
)
]
|
from django.conf import settings
import factory
from pgallery.models import Gallery, Photo
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: "user_%d" % n)
email = factory.Sequence(lambda n: "user_%d@example.com" % n)
class Meta:
model = settings.AUTH_U... | ctory.dja | ngo.ImageField(width=1024, height=768)
class Meta:
model = Photo
|
from utils import *
import sys
def clean_rec(d):
kwhs, kwhs_oriflag = d["kwhs"]
temps, temps_oriflag = d["temps"]
for i in range(len(temps_oriflag)):
t = temps[i]
if t < -60:
temps_oriflag[i] = False #Ain't no way that reading's real
temps[i] = 0
for i in range... | kwhs_oriflag)
if __name__ == "__main__":
args = sys.argv
if len(args) > | 1:
the_year = int(args[1])
brecs, desc = qload("state_b_records_" + str(the_year) + "_updated_with_temps.pkl")
for d in brecs:
clean_rec(d)
qdump((brecs, desc + "(Plus we cleaned out curiously low values (noise))"),
"state_b_records_" + str(the_year) + "_with_temps_cleaned.pk... |
# Copyright 2020 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... | under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, ei | ther express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Core TensorFlow types."""
from __future__ import absolute_import
from __future__ import division
from __fut... |
ns__(self, name):
return name in self.__dict__
def __repr__(self):
return "Event({0})".format(self.__dict__)
def to_series(self, index=None):
return pd.Series(self.__dict__, index=index)
class Order(Event):
pass
class Portfolio(object):
def __init__(self):
self.cap... |
# This is the cache that is used for returns. This will have a different
# structure than the other history cache as this is always daily.
_returns_cache_dt = None
_returns_cache = None
# The last dt that we needed to cache the number of minutes.
_minute_bar_cache_dt = None
# If we are in... | d with computing
# the number of minutes that we need to pass to the bar count of history.
# This will remain constant for a given bar and day count.
# This maps days to number of minutes.
_minute_bar_cache = {}
def __init__(self, sid, initial_values=None):
self._sid = sid
self._fr... |
import alsaaudio
from math import pi, sin, pow
import getch
SAMPLE_RATE = 44100
FORMAT = alsaaudio.PCM_FORMAT_U8
PERIOD_SIZE = 512
N_SAMPLES = 1024
notes = "abcdefg"
frequencies = {}
for i, note in enumerate(notes):
frequencies[note] = 440 * pow(pow(2, 1/2), i)
# Generate the sine wave, centered at y=128 with 10... | buf = bytearray(w)
elif char == '4':
w = [x//2 + 128 for x in make_wave(triangle_wave, 440)]
buf = bytearray(w)
elif char == '5':
buf = bytearray(w_half)
dev.write(buf)
dev.write(buf)
dev.write(buf)
last... | ar
char = getch.getch()
return 0
#def load_buf(buf, frequency):
# step = N_SAMPLES * frequency // SAMPLE_RATE
# for i in range(0, PERIOD_SIZE):
# buf[i] = wave[(step * i * N_SAMPLES // PERIOD_SIZE) % N_SAMPLES]
# return buf
def make_wave(wave, frequency):
step = N_SAMPLES * frequency ... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='check_iftraffic_nrpe',
version='0.12.1',
description='Nagios NRPE plugin to check Linux network traffic' | ,
scripts = ['check_iftraffic_nrpe.py'],
author='Samuel Krieg',
author_email='samuel.krieg+github@gmail.com',
url='https://github.com/SamK/check_iftraffic_nrpe.py',
download_url = 'https://github.com/SamK/check_iftraffic_nrpe.py/tarball/0.12.1',
keywords = ['nagios', 't | raffic', 'nrpe', 'monitoring']
)
|
#!/usr/bin/env python2
from dbutil import *
def createTables():
""" Populate the array | with names of sql DDL files """
for sqlFileName in ["Address.sql", "Electricity.sql", "CodeViolationsReport.sql",
"FireRescueEMSResponse.sql", "NaturalGasReport.sql",
"WaterReport.sql"]:
try:
runSqlFile("create/" + sqlFileName)
print ... | plit(".sql")[0])
except Exception as e:
pass
createTables()
|
.dot(x, x) - Delta**2
if c > 0:
raise ValueError("`x` is not within the trust region.")
d = np.sqrt(b*b - a*c) # Root from one fourth of the discriminant.
# Computations below avoid loss of significance, see "Numerical Recipes".
q = -(b + copysign(d, b))
t1 = q / a
t2 = c / q
if ... | nctions.
def build_quadratic_1d(J, g, s, diag=None, s0=None):
"""Parameterize | a multivariate quadratic function along a line.
The resulting univariate quadratic function is given as follows:
::
f(t) = 0.5 * (s0 + s*t).T * (J.T*J + diag) * (s0 + s*t) +
g.T * (s0 + s*t)
Parameters
----------
J : ndarray, sparse matrix or LinearOperator shape (m,... |
view': 'modelview <selection>',
'upgrade': 'upgrade [store-dir] ...',
'addref': 'addref [store-dir] ... <filename> ...',
'qc': 'qc [store-dir]',
'report': 'report <subcommand> <arguments>... [options]'
}
subcommands = subcommand_descriptions.keys()
program_name = 'fo... | am_name, options.loglevel)
def cl_parse(command, args, setup=None, details=None):
usage = subcommand_usages[command]
descr = subcommand_descriptions[command]
if isinstance(usage, str):
usage = [usage]
|
susage = '%s %s' % (program_name, usage[0])
for s in usage[1:]:
susage += '\n%s%s %s' % (' '*7, program_name, s)
description = descr[0].upper() + descr[1:] + '.'
if details:
description = description + ' %s' % details
parser = OptionParser(usage=susage, description=description)
... |
import logging
from logging import config
import paramiko
import os
from read_config import *
class FileDownloader(object):
ip = None
port = None
user = None
password = None
local_file_path = None
remote_file_path = None
abs_file_list = []
ssh = None
logger = None... | ef download(self):
sftp = self.ssh.open_sftp()
self.list_remote_file(self.remote_file_path)
for remote_file in self.abs_file_list:
sub_path_name = | remote_file[remote_file.index(self.remote_file_path) + len(self.remote_file_path):]
local_file = self.local_file_path + sub_path_name
dir_name = os.path.dirname(local_file)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
sftp.get(remote_file, ... |
,
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
... | 'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'rule': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [],... | 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
})
},
'sentry.groupseen': {
'Meta': {
'unique_together': "(('user', 'group'),)",
'object_name': 'GroupSeen'
},
'group':... |
"""
사이트 관리 도구 어드민 페이지 설정.
"""
|
from django.contrib import admin
from modeltranslation.admin import TranslationAdmin
from .models import Category, GroupServicePermissio | n, Service, TopBanner
class CategoryAdmin(TranslationAdmin):
"""
:class:`Category` 모델에 대한 커스텀 어드민.
`django-modeltranlation` 에서 제공하는 :class:`TranslationAdmin` 을 상속받아
다국어 처리를 사용자 친화적으로 변경하였습니다.
"""
pass
class ServiceAdmin(TranslationAdmin):
"""
`Service` 모델에 대한 커스텀 어드민.
`django-... |
from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
loaded_data = datasets.load_boston()
data_X = loaded_data.data
data_y = loaded_data.target
model = LinearRegression()
model.fit(data_X, data_y)
print(model.pre | dict(data_X[:4,:]))
print(data_y[:4])
print(model.coef_)
print(model.intercept_)
print(model.score(data_X, data_y))
#X, y = datasets.make_regression(n_samples=100, n_features=1, n_targets=1, n | oise=20)
#plt.scatter(X,y)
#plt.show() |
"""
Django settings for web project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import... | BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
U | SE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
|
from invoke import task, Collection
from invocations.checks import blacken
from invocations.packaging import release
from invocations import docs, pytest as pytests, travis
@task
def coverage(c, html=True):
"""
Run coverage with coverage.py.
"""
# NOTE: this MUST use coverage itself, and not pytest-co... | ",
x=False,
k=None,
module=None,
):
"""
Run pytest with given options.
Wraps ``invocations.pytests.test``. See its docs for details.
"""
# TODO: could invert this & have our entire test suite manually _enable_
# our own plugin, but given pytest's options around plugin setup, this
... | er and simpler.
opts += " -p no:relaxed"
pytests.test(
c,
verbose=verbose,
color=color,
capture=capture,
opts=opts,
x=x,
k=k,
module=module,
)
ns = Collection(blacken, coverage, docs, test, travis, release)
ns.configure({"blacken": {"find_opt... |
neth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity 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.
#
# Duplicity is di... | system directory.
tempbase | - The temp root directory, or None to use system
default (recommended).
"""
self.__dir = tempfile.mkdtemp("-tempdir", "duplicity-", temproot)
log.Info(_("Using temporary directory %s") % util.ufn(self.__dir))
# number of mktemp()/mkstemp() calls served so far
self.__tem... |
else:
# newer zfcp sysfs interface with auto port scan
raise ValueError, _("WWPN %(wwpn)s not found at zFCP device "
"%(devnum)s.") % {'wwpn': self.wwpn,
'devnum': self.devnum}
else:
... | ineSCSIDevice()
except IOError as e:
raise ValueError, _("Could not correctly delete SCSI device of "
"zFCP %(devnum)s %(wwpn)s %(fcplun)s "
"(%(e)s).") \
% {'devnum': self.devnum, 'wwpn': self.wwpn,
... | ror, _("Could not remove LUN %(fcplun)s at WWPN "
"%(wwpn)s on zFCP device %(devnum)s "
"(%(e)s).") \
% {'fcplun': self.fcplun, 'wwpn': self.wwpn,
'devnum': self.devnum, 'e': e}
if os.... |
import sys
sys.path.insert(1, "../../")
import h2o
def vec_show(i | p,port):
# Connect to h2o
h2o.init(ip,port)
iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader.csv"))
print "iris:"
iris.show()
###################################################################
res = 2 - iris
res2 = res[0]
print "res2:"
res2.show()
res... | w()
if __name__ == "__main__":
h2o.run_test(sys.argv, vec_show)
|
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Axel Tillequin (bdcht3@gmail.com)
# This code is part of Masr
# published under GPLv2 license
import gtk
from grandalf.graphs import Vertex,Edge,Graph
from grandalf.layouts import SugiyamaLayout
from grandalf.routing import *
from grandalf.utils import median_wh,Dot
f... | or edot in edgelist:
v1 = V[edot.n1.name]
v2 = V[edot.n2.name]
e = Edge(v1,v2)
e.view = Edge_basic(v1.view,v2.view,head=True)
e.view.set_properties(line_width = 2)
E.append(e)
return Graph(V.values(),E)
def dotnode(seq):
_start = Vertex(seq)
v = _start.view = Node_codeblock(_start.data.re... | ---------------------------------------------------------
# CGraph is simply a SugiyamaLayout extended with adding nodes and edges views
# on the current canvas and dealing with mouse/keyboard events.
class CGraph(SugiyamaLayout):
def __init__(self,c,g):
self.parent = c
SugiyamaLayout.__init__(self,g)
se... |
p, remote = self.socket.recvfrom(1500)
p = DNS(raw(p))
# check received packet for correctness
assert(p is not None)
assert(p[DNS].qr == 0)
assert(p[DNS].opcode == 0)
# has two queries
assert(p[DNS].qdcount == TEST_QDCOUNT)
... | ame=TEST_NAME, qtype=DNS_RR_TYPE_A)),
an=(DNSRR(rrname=TEST_NAME, type=DNS_RR_TYPE_AAAA,
| rdlen=DNS_RR_TYPE_AAAA_DLEN,
rdata=TEST_AAAA_DATA) /
DNSRR(rrname=TEST_NAME, type=DNS_RR_TYPE_A,
rdlen=DNS_RR_TYPE_A_DLEN, rdata=TEST_A_DATA))))
assert(not successful_dns_request(child, TEST_NAME, ... |
import time
fr | om datetime impo | rt datetime
class pyTemperature(object):
def __init__(self, date = datetime.now(), temp=None,pressure=None,humidity=None):
self.date = date
self.temperature = temp
self.pressure = pressure
self.humidity = humidity
def printTemperature(self):
print(self.date)
pr... |
from core.himesis import Himesis, HimesisPostConditionPattern
import cPickle as pickle
from uuid import UUID
class HReconnectMatchElementsRHS(HimesisPostConditionPattern):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HReconnectMatchElementsRHS.
"""
... | #===============================================================================
return attr_value
"""
self.vs[1]["GUID__"] = UUID('7e5e306f-cb65-40df-9e60-63b9fe83b79b')
self.vs[2]["mm__"] = """MT_post__MatchModel"""
self.vs[2]["MT_label__"] = """1"""
self.vs[2]["GUID__"] = UUID('3c85b... | tchElementsLHS()
def action(self, PostNode, graph):
"""
Executable constraint code.
@param PostNode: Function taking an integer as parameter
and returns the node corresponding to that label.
"""
#=====================================... |
"""
=====================================
Sensor spac | e least squares regression
=====================================
Predict single trial activity from a continuous variable.
A single-trial regression is performed in each sensor and timepoint
individually, resulting in an Evoked object which contains the
regression coefficient (beta value) for each combination of senso... | cant effect.
(See Hauk et al. (2006). The time course of visual word recognition as
revealed by linear regression analysis of ERP data. Neuroimage.)
"""
# Authors: Tal Linzen <linzen@nyu.edu>
# Denis A. Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.da... |
from gitmostwanted.app import celery, db
from gitmostwanted.lib.github.api import user_starred, user_starred_star
from gitmostwanted.models.repo import Repo
from gitmostwanted.models.user import UserAttitude
@celery.task()
def repo_starred_star(user_id: int, access_token: str):
starred, code = user_starred(access... | [x for x in starred if x['full_name'] == r.repo.full_name]]
return len(lst_out), len(list(filter(None, lst_in)))
def repo_like(repo_name: str | , uid: int):
repo = Repo.get_one_by_full_name(repo_name)
if not repo:
return None
db.session.merge(UserAttitude.like(uid, repo.id))
db.session.commit()
return repo.id
|
object for example Account or Opportunity..
about_kind = ndb.StringProperty()
about_item = ndb.StringProperty()
# a key reference to the account's organization
# Should be required
discussionKind = ndb.StringProperty()
discussionId = ndb.StringProperty()
organization = ndb.KeyProperty()
cl... | url,
photo=note.author.photo
)
about = None
edge_list = Edge.list(start_node=note.key, kind='parents')
fo | r edge in edge_list['items']:
about_kind = edge.end_node.kind()
parent = edge.end_node.get()
if parent:
if about_kind == 'Contact' or about_kind == 'Lead':
if parent.lastname and parent.firstname:
about_name = parent.firstna... |
from bson import ObjectId
from . import repeating_schedule
from state_change import StateChange
class StateChangeRepeating(StateChange):
def __init__(self, seconds_into_week, AC_target, heater_target, fan, id=None):
self.id = id
self.seconds_into_week = seconds_into_week
self.AC_target =... | }
]).next()
return cls.from_dictionary(result)
def save(self):
delayed_state_change = {
"week_time": self.seconds_into_week,
"state": {"AC_target": self.AC_target, "heater_target": self.heater_target, "fan": self.fan}
}
if self.id is | not None:
delayed_state_change["_id"] = self.id
return repeating_schedule.save(delayed_state_change)
def to_dictionary(self):
return {"week_time": self.seconds_into_week,
"_id": str(self.id),
"state": {"AC_target": self.AC_target,
... |
# 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
# d... | miss(messages.ERROR))
self.as | sertFalse(users_page.is_user_present(self.USER_NAME))
|
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class TimeStampedModel(models.Model):
" | ""
An abstract base class model that provides self-updating "created" and "modified" fields.
"""
created = models.DateTi | meField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True |
import errno
import glob
import platform
import re
import sys
import tempfile
import zipfile
from contextlib import contextmanager
from distutils.version import StrictVersion
import os
import requests
from xml.etree import ElementTree
IS_64_BIT = sys.maxsize > 2**32
IS_LINUX = platform.system().lower() == 'linux'
I... | m.group(1) # version
p = m.group(2) # platform
b = m.group(3) # bit
if v not in self.versions:
self.versions[v] = {}
if p not in self.versions[v]:
self.versions[v][p] = {}
self.versions[v][p][b] ... | elif IS_MAC:
return 'mac'
else:
raise RuntimeError('Unable to detect current platform')
def binary_path(self):
if self._bin_path:
return self._bin_path
if self.version and self.version not in self.versions:
raise RuntimeError('Chromedrive... |
status=UserGroupStatus.PENDING.value)
resp = utils.test_request(self, "GET", path, headers=self.json_headers, cookies=self.cookies)
body = utils.check_response_basic_info(resp, 200, expected_method="GET")
... | ntEqual(body["group_names"], pending_members + active_members)
# validate that pending user can be viewed in the edit group page
path = "/ui/groups/{}/default".format(group_with_terms_name)
resp = utils.test_request(self, "GET", path)
body = utils.check_u... | s_in("{} [pending]".format(self.test_user_name), body)
# validate that pending group membership can be viewed in the edit user page
path = "/ui/users/{}/default".format(self.test_user_name)
resp = utils.test_request(self, "GET", path)
body = utils.check_u... |
vision, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import codecs
import os
import re
from pkg_resources import resource_string
from pygments.formatters.html import HtmlFormatter
from pygments.styles import get_al | l_styles
from pants.backend.docgen.targets.doc import Page
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.base.generator import Generator
from pants.base.workunit import WorkUnitLabel
from pants.binaries import binary_util
from pants.build_graph.address im... | l.dirutil import safe_mkdir
def util():
"""Indirection function so we can lazy-import our utils.
It's an expensive import that invokes re.compile a lot (via markdown and pygments),
so we don't want to incur that cost unless we must.
"""
from pants.backend.docgen.tasks import markdown_to_html_utils
return... |
r = http('--print=B', '--pretty=colors',
'GET', httpbin.url + '/get', 'a=b',
env=env)
# Tests that the JSON data isn't formatted.
assert not r.strip().count('\n')
assert COLOR in r
def test_format_option(self, httpbin):
env = MockEnvironment(col... | 2', {'foo': {'bar': 2}}),
({'foo': {'bar': True}}, 'foo.bar:false', {'foo': {'bar': False}}),
({'foo': {'bar': 'a'}}, 'foo.bar:b', {'foo': {'bar': 'b'}}),
# @formatter:on
]
)
def test_parse_format_options(self, defaults, options_string, expected):
actual = par... | options(s=options_string, defaults=defaults)
assert expected == actual
@pytest.mark.parametrize(
'options_string, expected_error',
[
('foo:2', 'invalid option'),
('foo.baz:2', 'invalid key'),
('foo.bar:false', 'expected int got bool'),
]
)
... |
"""
Tests of student.roles
"""
import ddt
from django.test import TestCase
from courseware.tests.factories import UserFactory, StaffFactory, InstructorFactory
from student.tests.factories import AnonymousUserFactory
from student.roles import (
GlobalStaff, CourseRole, CourseStaffRole, CourseInstructorRole,
Or... | _org_role(self):
"""
Test that giving a user an org role enables access appropriately
| """
self.assertFalse(
OrgStaffRole(self.course_key.org).has_user(self.student),
"Student has premature access to {}".format(self.course_key.org)
)
OrgStaffRole(self.course_key.org).add_users(self.student)
self.assertTrue(
OrgStaffRole(self.cour... |
impor | t pigpio
import time
class LeftEncoder:
def __init__(self, pin=24):
self.pi = pigpio.pi()
self.pin = pin
self.pi.set_mode(pin, pigpio.INPUT)
self.pi.set_pull_up_down(pin, pigpio.PUD_UP)
cb1 = self.pi.callback(pin, pigpio.EITHER_EDGE, self.cbf)
self.tick = 0
de... | time.sleep(.01) |
"""SCons.Tool.latex
Tool-specific initialization for LaTeX.
Generates .dvi files from .latex or .ltx files
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2017 The SCons Foundation
#... | tter('.ltx', SCons.Tool.tex.tex_eps_emitter)
| bld.add_emitter('.latex', SCons.Tool.tex.tex_eps_emitter)
SCons.Tool.tex.generate_common(env)
def exists(env):
SCons.Tool.tex.generate_darwin(env)
return env.Detect('latex')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
-------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# ... | sponse.get('proxyHeader') != request.get('proxyHeader'):
proxy_header_update(module, request, response)
if response.get('service') != request.get('service'):
service_update(module, request, res | ponse)
def proxy_header_update(module, request, response):
auth = GcpSession(module, 'compute')
auth.post(
''.join(["https://www.googleapis.c |
cted window caption."""
RV_WIN_NAME = "Remote Viewer"
"""Expected window caption."""
RV_WM_CLASS = "remote-viewer"
class RVSessionError(Exception):
"""Exception for remote-viewer session. Root exception for the RV Sessiov.
"""
def __init__(self, test, *args, **kwargs):
super(RVSessionError, self)... | rl(vmi)
act.str_input(vmi, url)
act.rv_auth(vmi)
@reg.add_action(req=[ios.ILinux])
def rv_connect_file(vmi, ssn, env):
cmd = utils.Cmd(vmi.cfg.rv_binary)
vv_file_host = act.gen_ | vv_file(vmi)
with open(vv_file_host, 'r') as rvfile:
file_contents = rvfile.read()
act.info(vmi, "RV file contents:\n%s", file_contents)
vv_file_client = act.cp_file(vmi, vv_file_host)
cmd.append(vv_file_client)
utils.set_ticket(vmi.test)
cmd = utils.combine(cmd, "2>&1")
act.info... |
of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more detail... | te_qty(cr, uid, production.product_uom.id, production.produc | t_qty, production.bom_id.product_uom.id)
qty1 = sub_product.product_qty
qty2 = production.product_uos and production.product_uos_qty or False
product_uos_factor = 0.0
if qty2 and production.bom_id.product_uos.id:
product_uos_factor = pr... |
"""
WSGI config for yaco project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` set... | ron["DJANGO_SETTINGS_MODULE"] = "yaco.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yaco.settings")
| # This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi impor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | Migration(migrations.Migration):
dependencies = [
('forum', '0004_topic_update_index_date'),
]
database_operations = [
migrations.AlterModelTable('TopicFollowed', 'notification_topicfollowed')
]
st | ate_operations = [
migrations.DeleteModel('TopicFollowed')
]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=database_operations,
state_operations=state_operations)
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutSets(Koan):
def test_sets_make_keep_lists_unique(self):
highlanders = ['MacLeod', 'Ramirez', 'MacLeod', 'Matunas',
'MacLeod', 'Malcolm', 'MacLeod']
there_can_only_be_only_one = set(highlanders)
... | as'])
self.assertEqual(set([ | 'Willie']), scotsmen - warriors)
self.assertEqual(set(['MacLeod', 'Wallace', 'Willie', 'Leonidas']), scotsmen | warriors)
self.assertEqual(set(['MacLeod', 'Wallace']), scotsmen & warriors)
self.assertEqual(set(['Willie', 'Leonidas']), scotsmen ^ warriors)
# ---------------------------------... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MOD | ULE", "logger.settings | ")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
"""
WSGI config for my | _doku_application project.
It exposes the WSGI callable as a module-level variable named ``application``.
For mor | e information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_doku_application.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Python header conversion
# Copyright (c) 2013,2014 Dave Hughes <dave@waveform.org.uk>
#
# Original headers
# Copyright (c) 2012, Broadcom Europe Ltd
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitte... | = ct.CDLL('libbcm_host.so')
# bcm_host.h #################################################################
bcm_host_init = _lib.bcm_host_init
bcm_host_init.argtypes = []
bcm_host_init.restype = None
bcm_host_deinit = _lib.bcm_host_deinit
bcm_host_deinit.argtypes = []
bcm_ho | st_deinit.restype = None
graphics_get_display_size = _lib.graphics_get_display_size
graphics_get_display_size.argtypes = [ct.c_uint16, ct.POINTER(ct.c_uint32), ct.POINTER(ct.c_uint32)]
graphics_get_display_size.restype = ct.c_int32
|
"""
simple alignment baselines
"""
# TODO:
# - better implementions
from daeso.pair import Pair
def greedy_align_equal_words(corpus):
for graph_pair in corpus:
graph_pair.clear()
graphs = graph_pair.get_graphs()
target_nodes = graphs.target.terminals(with_punct=False,
... | ]
for sn in graphs.source:
if ( graphs.source.node_ | is_punct(sn) or
graphs.source.node_is_empty(sn) ):
continue
sw = graphs.source.get_node_token_string(sn).lower()
sr = graphs.source.node[sn].get("_lc_roots")
try:
j = target_words.index(sw)
... |
__version__ = '0.4'
__author__ = 'Martin Natano <natano@natano.net>'
_repository = None
_branch = 'git-orm'
_remote = 'origin'
class GitError(Exception): pass
def set_repository(value):
f | rom pygit2 import discover_repository, Repository
global _repository
if value is None:
_repository = None
return
try:
path = discover_repository(value)
except KeyError:
raise GitError('no repository found in "{}"'.format(value))
_repository = Reposit | ory(path)
def get_repository():
return _repository
def set_branch(value):
global _branch
_branch = value
def get_branch():
return _branch
def set_remote(value):
global _remote
_remote = value
def get_remote():
return _remote
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | ect to retrieve for the degraded
query pattern
shape [pattern_size,]
target_idx (int): The index into the list of unique patterns for the target
| patterns: List of np arrays, all unique patterns
"""
patterns = []
for _ in range(num_patterns):
pattern = np.random.choice([-1, 1], size=(pattern_size,), p=[.5, .5])
patterns.append(pattern)
# Choose one pattern to degrade
target_idx = random.choice(range(num_patterns))
target = patterns[target_... |
t, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
import CTK
import Handler
import Cherokee
import Balancer
import validations
from util import *
from consts import *
URL_APPLY = '/plugin/proxy/apply'
HELPS = [('modules_handlers_proxy', N_("Reverse Proxy"))]
NOTE_REUSE_MAX = N_("Maximum number of connection... | : 'noauto'})
add_bu | tton = CTK.SubmitterButton(_('Add'))
table = CTK.Table()
table.set_header(1)
table += [CTK.RawHTML (_('Hide Header'))]
table += [new_hide, add_button]
submit = CTK.Submitter (URL_APPLY)
submit += CTK.Indenter (table)
submit += CTK.Hidden ('tmp!new!%s!key'%(key_e... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2020] EMBL-European Bioinformatics Institute
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... | ntral_pipeli | ne.databases import data
from rnacentral_pipeline.databases.intact import parser
from rnacentral_pipeline.databases.helpers import publications as pubs
@pytest.fixture(scope="module")
def sample():
with open("data/intact/sample.txt", "r") as raw:
return list(parser.parse(raw, os.environ["PGDATABASE"]))
... |
# codin | g=utf-8
# Run a test server.
from app import app
im | port sys
reload(sys)
sys.setdefaultencoding('utf-8')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7000, debug=True)
|
# Copyright 2016 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... | p in the session.
Args:
supervisor: `tf.train.Supervisor` to run the training services.
train_step_fn: Callable to execute one training step. Called
repeatedly as `train_step_fn(session, *args **kwargs)`.
args: Optional positional arguments passed to `train_step_fn`.
kwargs | : Optional keyword arguments passed to `train_step_fn`.
master: Master to use to create the training session. Defaults to
`""` which causes the session to be created in the local process.
"""
if args is None:
args = []
if kwargs is None:
kwargs = {}
should_retry = True
while should_retry:
... |
#!/usr/bin/env python
# -*- | coding: utf-8 -*-
"""module that copies from | another module"""
from task_01.peanut import BUTTER
JELLY = BUTTER
|
from __future__ import absolute_import, division
import time
import os
try:
unicode
except NameError:
unicode = str
from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked
class SQLiteLockFile(LockBase):
"Demonstrate SQL-based locking."
testdb = None
def __init__(self, path, t... | " where unique_name = ?",
(self.unique_name,))
rows = cursor.fetchall()
if len(rows) > 1:
# Nope. Someone else got there. Remove our lock.
curso | r.execute("delete from locks"
" where unique_name = ?",
(self.unique_name,))
self.connection.commit()
else:
# Yup. We're done, so go home.
return
else:
... |
from django import db
from django.conf import settings
from django.core.management.base import NoArgsCommand
from data.models import FCNASpending
import csv
# National Priorities Project Data Repository
# imp | ort_fcna_spending.py
# Updated 7/23/2010, Joshua Ruihley, Sunlight Foundation
# Imports Federal Child Nutrition Act Spending Data
# source info: http://nces.ed.gov/ccd/bat/index.asp (accurate as of 7/23/2010)
# npp csv: http://assets.nationalpriorities.org/raw_data/education/fcna_spending.csv (updated 7/23/2010)
# des... | vert source file to .csv with same formatting as npp csv
# 3) change SOURCE_FILE variable to the the path of the source file you just created
# 4) change 'amount' column in data_FCNASpending table to type 'bigint'
# 5) Run as Django management command from your project path "python manage.py import_fcna_spending"
SOUR... |
# -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo 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 v... | # You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its statu... | Zenodo Support."""
from __future__ import absolute_import, print_function
#: Maximum size of attachment in contact form.
SUPPORT_ATTACHMENT_MAX_SIZE = 1000 * 1000 * 10 # 10 MB
#: Description maximum length.
SUPPORT_DESCRIPTION_MAX_LENGTH = 5000
#: Description minimum length.
SUPPORT_DESCRIPTION_MIN_LENGTH = 20
#:... |
# -*- coding: utf-8 -*-
""" Tablib - JSON Support
"""
import decimal
import tablib
try:
import ujson as json
except ImportError:
import json
title = 'json'
extensions = ('json', 'jsn')
def date_handler(obj):
if isinstance(obj, decimal.Decimal):
return str(obj)
elif hasattr(obj, 'isoformat'... | esentation of Databook."""
return json.dumps(databook._package(), default=date_handler)
def import_s | et(dset, in_stream):
"""Returns dataset from JSON stream."""
dset.wipe()
dset.dict = json.loads(in_stream)
def import_book(dbook, in_stream):
"""Returns databook from JSON stream."""
dbook.wipe()
for sheet in json.loads(in_stream):
data = tablib.Dataset()
data.title = sheet['... |
# -*- coding: utf-8 -*-
""" Implements a Class for Representing a Simulated Senate Election. """
from collections import Counter
from random import random
from random import seed as set_seed
from time import asctime
from time import localtime
from aus_senate_audit.senate_election.base_senate_election import BaseSena... | lot(ballot, 1)
def get_outcome(self, ballot_weights):
""" Returns the outcome of a senate election with the given ballot weights.
The social choice function used in the simulated senate election is Borda count.
:param :class:`Counter` ballot_weights: A mapping from a ballot type to the nu... | type: tuple
"""
counter = Counter()
for ballot, weight in ballot_weights.items():
for i, cid in enumerate(ballot):
counter[cid] += weight * i
# Get the :attr:`_seat` candidates with the lowest Borda counts in increasing order.
winners = counter.most_co... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
# 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/licen... | = InstructionSet()
for j in range(q.size):
gs.add(self.snapshot(m, (q, j)))
return gs
self._check_qubit(q)
return self._attach(SnapshotGate(m, q, self))
# Add to QuantumCircuit and CompositeGate classes
QuantumCircuit.snapshot = snapshot
CompositeGate.snapshot = snapshot
# cache ... | "bits": ["a"],
# gate snapshot(m) a { }
"body": node.GateBody([])
}
|
from django.con | f.urls import url
from . import views
urlpatterns = [
url(r'^carrinho/adicionar/(?P<slug>[\w_-]+)/$',
views.CreateCartItemView.as_view(), name='create_cartitem'),
ur | l(r'^carrinho/$', views.CartItemView.as_view(),
name='cart_item')
]
|
in out_str
# keywords tooltip
m = self.world.explore(
tooltip=True,
popup=False,
tooltip_kwds=dict(aliases=[0, 1, 2, 3, 4, 5], sticky=False),
)
out_str = self._fetch_map_string(m)
assert (
'fields=["pop_est","continent","name","iso... | assert "#7f7f7f'></span>Oceania" in out_str
assert "#dbdb8d'></span>Sevenseas(openocean)" in out_str
assert "#9edae5'></span>SouthAmerica" in out_str
m = self.missing.explore(
"continent", legend=True, missing_kwds={"color": "red"}
)
out_str = self._fetch_map_string(... | bar(self):
m = self.world.explore("range", legend=True)
out_str = self._fetch_map_string(m)
assert "attr(\"id\",'legend')" in out_str
assert "text('range')" in out_str
m = self.world.explore(
"range", legend=True, legend_kwds=dict(caption="my_caption")
)
... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.db.models import Count
from django.urls import reverse_lazy
from django.utils.translation import ugettext as _
from django.shortcuts import render, get_object_or_404, redirect
from django... | if tarif is None:
request.user.log(request.META, 'csrv', '"%(title)s", "%(descr)s", %(amount).2f' % {
'title': service.title or '-',
'descr': service.descr or '-',
'amount': service.amount or 0.0
| })
messages.success(request, _('Service has been saved'))
return redirect('tarifs:edit', tarif_id=service.pk)
else:
messages.warning(request, _('Some fields were filled incorrect, please try again'))
else:
frm = forms.TariffForm(instance=tarif)
return rend... |
__all__ = ["Block", "Un | known", "Multitextured", "DataValues", "Stairs", "MultitexturedStairs", "Slab", "Multitextured | Slab", "Log"]
|
#!/usr/bin/python
from gi.repository import Gtk, GObject
import time
import unittest
from testutils import setup_test_env
setup_test_env()
from softwarecenter.enums import XapianValues, ActionButtons
TIMEOUT=300
class TestCustomLists(unittest.TestCase):
def _ | debug(self, index, model, needle):
print ("Expected '%s' at index '%s', " +
"and custom list contained: '%s'") % (
needle, index, model[index][0].get_value(XapianValues.PKGNAME))
def assertPkgInListAtIndex(self, index, model, needle):
doc = model[index][0]
sel... | needle, self._debug(index, model, needle))
def test_custom_lists(self):
from softwarecenter.ui.gtk3.panes.availablepane import get_test_window
win = get_test_window()
pane = win.get_data("pane")
self._p()
pane.on_search_terms_changed(None, "ark,artha,software-c... |
#!/usr/bin/python
"""
This is a wrapper to run the 'lacheck(1)' tool from the 'lacheck' package.
Why do we need this wrapper?
- lacheck does NOT report in its exit status whether it had warnings or not.
- it is too verbose when there are no warnings.
"""
import sys # for argv, exit, stderr
import subprocess # for ... | 'lacheck',
sys.argv[1],
])
errors = False
remember = None
printed_remember = False
for line in out.split('\n'):
if line.startswith('**'):
remember = line
printed_remember = False
continue
if line == '':
continue
# ... | member:
print(remember)
printed_remember = True
print(line)
if errors:
sys.exit(1)
if __name__ == '__main__':
main()
|
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the | terms of the MIT License; see the
# LICENSE file for more details.
import re
from flask import abort, redirect, request
from werkzeug.exceptions import NotFound
from indico.modules.categories.models.legacy_mapping import LegacyCategoryMapping
from indico.web.flask.util import url_for
from indico.web.rh import RHSim... | d+l\d+$', legacy_category_id):
abort(404)
mapping = LegacyCategoryMapping.query.filter_by(legacy_category_id=legacy_category_id).first()
if mapping is None:
raise NotFound(f'Legacy category {legacy_category_id} does not exist')
view_args = request.view_args.copy()
view_args['legacy_categ... |
import unittest
import flavio
from math import sqrt, pi
from flavio.physics.zdecays.gammazsm import Zobs, pb
from flavio.physics.zdecays.gammaz import GammaZ_NP
from flavio.physics.zdecays import smeftew
par = flavio.default_parameters.get_central_all()
class TestGammaZ(unittest.TestCase):
def test_obs_sm(self)... | ediction('BR(Z->etau)'), 0)
self.assertEqual(flavio.sm_prediction('BR(Z->mutau)'), 0)
def test_Gamma_NP(self):
# compare NP contributions to A.49-A.52 from 1706.08945
GF, mZ, s2w_eff = par['GF'], par['m_Z'], par['s2w']*1.0010
d_gV = 0.055
d_gA = 0.066
# A.49-A.52 fro... |
dGamma_Zuu = sqrt(2)*GF*mZ**3/(pi) * (d_gA -1/3*(-3+8*s2w_eff)*d_gV) /2
dGamma_Zdd = sqrt(2)*GF*mZ**3/(pi) * (-3/2*d_gA +1/2*(-3+4*s2w_eff)*d_gV) /3
# term squared in d_gV and d_gA not included in 1706.08945
d_g_squared = sqrt(2)*GF*mZ**3/(3*pi)*(abs(d_gV)**2+abs(d_gA)**2)
self.... |
# -*- coding: | utf-8 -*-
"""
urwintranet.ui.views
~~~~~~~~~~~~~~~~~~
"""
from . import (auth, home, pa | rts)
|
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from .common import BaseTest
import jmespath
class TestApacheAirflow(BaseTest):
def test_airflow_environment_value_filter(self):
session_factory = self.replay_flight_data('test_airflow_environment_value_filter')
p = sel... | asName'], 'alias/mwaa')
def test_airflow_environment_tag(self):
session_factory = self.replay_flight_data('test_airflow_environment_tag')
new_tag = {'env': 'dev'}
p = self.load_policy(
{
| 'name': 'airflow-tag',
'resource': 'airflow',
'filters': [{
'tag:env': 'absent'
}],
'actions': [{
'type': 'tag',
'tags': new_tag
}]
},
session_factory=sess... |
"""
Created on Sep 14, 2015
@author: Mikhail
"""
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import visibility_of_element_located, visibility_of
from selenium.common.exceptions import TimeoutException
__author__ = 'Mikhail'
class Page(object):
def... | t(url)
def is_element_visible_by_locator(self, locator):
try:
self.wait.until(visibility_of_element_located(locator))
except TimeoutException:
return False
return True
def is_element_visible(self, | element):
try:
self.wait.until(visibility_of(element))
except TimeoutException:
return False
return True
|
import os
import fnmatch
def find_files(directory, pattern):
for root, di | rs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
for fname in find_files('.', 'CMakeLists.txt'):
f = open(fname, 'a')
f.write(
'\ninclude_d... | _PATH} ${GLUT_INCLUDE_PATH})')
f.close()
|
s_checks = models.ManyToManyField(
'StatusCheck',
blank=True,
help_text='Checks used to calculate service status.',
)
last_alert_sent = models.DateTimeField(
null=True,
blank=True,
)
alerts = models.ManyToManyField(
'AlertPlugin',
blank=True,
... | heckGroupMixin):
def duplicate(self):
checks = self.status_checks.all()
new_instance = self
new_instance.pk = None
new_instance.id = None
new_instance.name = u"Copy of %s" % self.name
new_instance.save()
for check in checks:
check.duplicate(ins... | erall_status
# Only active checks feed into our calculation
status_checks_failed_count = self.all_failing_checks().count()
self.overall_status = self.most_severe(self.all_failing_checks())
self.snapshot = InstanceStatusSnapshot(
instance=self,
num_checks_active=se... |
fro | m project import app
if __name__ == '__main__':
app.r | un()
|
from collections import defaultdict, namedtuple
import regex as re
from gary import ignore_parens_list
Record = namedtuple('Record', ['dob', 'eng', 'pos', 'phn'])
@ignore_parens_list
def split_words(text:str) -> list:
return re.split('\s*;\s*', text)
class ShParser:
def __init__(self, text):
self.... | if match[1] == 'ps':
if len(curr['ge']) > 0:
self.entries.append(curr)
curr['ge'] = []
curr['ps'] = match[2]
if match[1] == 'ge':
word_list = split_words(match[2])
for word | in word_list:
curr['ge'].append(word)
def getEntries(self):
for entry in self.entries:
if 'lx' in entry:
dob = entry['lx']
else:
dob = ''
eng = '‣'.join( entry['ge'])
pos = entry['ps']
phn ... |
import numpy
from cupy._core._scalar import get_typename
# Base class for cuda types.
class TypeBase:
def __str__(self):
raise NotImplementedError
def declvar(self, x):
return f'{self} {x}'
class Void(TypeBase):
def __init__(self):
pass
def __str__(self):
return '... | f.dtype == other.dtype
def __hash__(self):
return hash(self.dtype)
class ArrayBase(TypeBase):
| def __init__(self, child_type: TypeBase, ndim: int):
assert isinstance(child_type, TypeBase)
self.child_type = child_type
self.ndim = ndim
class CArray(ArrayBase):
def __init__(self, dtype, ndim, is_c_contiguous, index_32_bits):
self.dtype = dtype
self._c_contiguous = is_... |
severity failure;
res := (others => """ + logic_undef() + """);
else
for I in res_type'range loop
res (I) := la (I) {0} ra (I);
end loop;
end if;
return res;
end "{0}";\n"""
w (res.format(func, typ))
def disp_non_logical_warning(func):
return """
assert NO_WA... | gic};
variable res : compare_type;
begin
res := compare_eq;""";
res += init_int_var(dic['iparam'], dic['itype']) + """
for i in {vparam}a'reverse_range loop
""" + extract_bit (dic['vparam']) + \
extract_int_lsb("r", right)
if logic == 'std':
res += """
if {vparam}b =... | elsif lb = '0' and rb = '1' then
res := compare_lt;
end if;
end loop;"""
if func == "ucompare":
res += """
if r1 /= 0 then
res := compare_lt;
end if;"""
else:
res += """
if """ + conv_bit ("l (l'left)") + """ = '1' then
if r >= 0 then
res ... |
from venv import _venv
from fabric.api import task
@task
def migrate():
| """
Run Django's migrate command
"""
_venv("python manage.py migrate")
@task
def syncdb():
"""
Run Django's syn | cdb command
"""
_venv("python manage.py syncdb")
|
"""
basic set of `jut run` tests
"""
import json
import unittest
from tests.util import jut
BAD_PROGRAM = 'foo'
BAD_PROGRAM_ERROR = 'Error line 1, column 1 of main: Error: no such sub: foo'
class JutRunTests(unittest.TestCase):
def test_jut_run_syntatically_incorrect_program_reports_error_with_format_json(s... | {'time': '2014-01-01T00:00:04.000Z'}
])
def test_jut_run_emit_to_text(self):
"""
use jut to run the juttle program:
emit -from :2014-01-01T00:00:00.000Z: -limit 5
| and verify the output is in the expected text format
"""
process = jut('run',
'--format', 'text',
'emit -from :2014-01-01T00:00:00.000Z: -limit 5')
process.expect_status(0)
stdout = process.read_output()
process.expect_eof()
... |
# Our friend Monk has an exam that has quite weird rules. Each question has a difficulty level in the form of an
# Integer. Now, Monk can only solve the problems that have difficulty level less than X . Now the rules are-
#
# Score of the student is equal to the maximum number of answers he/she has attempted without sk... | e the student knows the solution to | the problem he/she attempts and always starts the paper from first
# question.
#
# Given the number of Questions, N ,the maximum difficulty level of the problem Monk can solve , X ,and the difficulty
# level of each question, Ai can you help him determine his maximum score?
#
# Input Format
# First Line contains Integ... |
'''OpenGL extension ARB.robustness_isolation
This module customises the behaviour of the
OpenGL.raw.GL.ARB.robustness_isolation to provide a more
Python-friendly API
Overview (from the spec)
GL | _ARB_robustness and supporting window system extensions allow
creating an OpenGL context supporting graphics reset notification
behavior. GL_ARB_ro | bustness_isolation provides stronger
guarantees about the possible side-effects of a graphics reset.
It is expected that there may be a performance cost associated
with isolating an application or share group from other contexts
on the GPU. For this reason, GL_ARB_robustness_isolation is
phrased as an opt-in mec... |
from setuptools import find_packages
from setuptools import setup
setup(
name='svs',
version='1.0.0',
description='The InAcademia Simple validation Service allows for the easy validation of affiliation (Student,'
'Faculty, Staff) of a user in Academia',
license='Apache 2.0',
classif... | tech@inacademia.org',
zip_safe=False,
url='http://www.inacademia.org',
packages=find_packages('src'),
package_dir={'': 'src'},
package_data={
'svs': [
'data/i18n/locale/*/LC_MESSAGES/*.mo',
'templates/*.mako',
'site/static/*',
],
},
message... | o', None),
('site/**', 'ignore', None)
]
},
install_requires=[
'satosa==3.3.1',
'Mako',
'gunicorn',
'Werkzeug'
]
)
|
custom_attributes_values = \
_use_id_instead_name_as_key_in_custom_attributes_values(custom_attributes,
custom_attributes_values)
_store_custom_attributes_values(validator.object, custom_attributes_values,
... | take_snapshot(validator.object, user=validator.object.owne | r)
custom_attributes_values = data.get("custom_attributes_values", None)
if custom_attributes_values:
custom_attributes = validator.object.project.issuecustomattributes.all().values('id', 'name')
custom_attributes_values = \
_use_id_instead_name_as_key_in_custom_... |
#!/usr/bin/env python
"""list all previously made bookings"""
import os
import sys
import cgi
import datetime
import json
import shuttle
import shconstants
import smtplib
import shcookie
print "Content-type: text/html\r\n"
shuttle.do_login(shcookie.u, shcookie.p)
form = cgi.FieldStorage()
if 'action' in form:
a... | form:
cal = form.getvalue("cal")
print '''<div id="outlook">
<a href="outlook.py?cal=%s">download booked trip</a>
</div>''' % (cal)
print '<div id="bookings">'
for b in bookings:
past = False
dt = datetime.datetime.strptime(b['dd'] + ' ' + b['dt'], "%m/%d/%Y %I:%M %p")
if dt < datetime.datetime.now() - da... | - datetime.timedelta(hours=2) - datetime.timedelta(minutes=1):
past = True
csspm += " past"
print '''<div class="booking%s">
<span class="t">%s</span>
<span class="r">%s</span>
<span class="dt">%s</span><span class="dl">%s</span>
<span class="gt">%s</span><span class="gl">%s</span>''' % (
csspm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.