prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from . import integ_test_base
class TestCustomEvaluateTimeout(integ_test_base.IntegTestBase):
def _get_evaluate_timeout(self) -> str:
return "3"
def test_custom_evaluate_timeout_with_script(self):
# Uncomment the following line to preserve
# test case output and other files (config, s... | st for testing custom evaluate timeouts "
"with scripts.",
}
conn = self._get_connection()
conn.request("POST", "/evaluate", payload, headers)
res = conn.getresponse()
actual_error_message = res.read().decode("utf-8")
self.assertEqual(408, res.status)
... | '"User defined script timed out. Timeout is set to 3.0 s.", '
'"info": {}}',
actual_error_message,
)
|
import dynet_config
dynet_config.set_gpu()
import dynet as dy
import os
import pickle
import numpy as np
import numpy as np
import os,sys
from sklearn import preprocessing
import pickle, logging
import argparse
debug = 0
class falcon_heavy(object):
def __init__(self, model, args):
self.pc = model.add_su... | elf.number_of_layers
if count == self.number_of_layers-1:
| t = dy.concatenate([activations[-1],input])
pred = g(dy.affine_transform([b, W, t ]))
else:
pred = g(dy.affine_transform([b, W, activations[-1]]))
activations.append(pred)
count += 1
if debug:
print "Activation dimens... |
from django.contrib import admin
from .models import Lesson, Course, CourseLead, QA
# from django.utils.translation import ugettext_lazy as _
from ordered_model.admin import OrderedModelAdmin
from core.models import User
# from adminfilters.models import Species, Breed
class UserAdminInline(admin.TabularInline):
... | dmin):
list_display = ('name', 'slug', 'published', )
ordering = ['id']
@admin.register(CourseLead)
class CourseLeadAdmin(admin.ModelAdmin):
list_display = (
'name',
'contact',
'course',
'status',
'student',
)
list_filter = ('status', )
ordering = ['stat... | n',
'move_up_down_links',
)
# list_filter = ('status', )
list_display_links = ('question', )
ordering = ['order']
|
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import re
import os
import argparse
import requests
from lxml import html as lxml_html
try:
import html
except ImportError:
import HTMLParser
html = HTMLParser.HTMLParser()
try:
import cPickle as pk
except ImportError | :
import pickle as pk
class LeetcodeProblems(object):
def get_problems_info(self):
leetcode_url = 'https://leetcode.com/problemset/algorithms'
res = requests.get(leetcode_url)
if not res.ok:
print('request error')
sys.exit()
cm = res.text
cmt | = cm.split('tbody>')[-2]
indexs = re.findall(r'<td>(\d+)</td>', cmt)
problem_urls = ['https://leetcode.com' + url \
for url in re.findall(
r'<a href="(/problems/.+?)"', cmt)]
levels = re.findall(r"<td value='\d*'>(.+?)</td>", cmt)
tinf... |
"""
preHeatEx.py - (Run this before heatExchanger2.py)
Performs inital energy balance for a basic heat exchanger design
Originally built by Scott Jones in NPSS, ported and augmented by Jeff Chin
NTU (effectiveness) Method
Determine the heat transfer rate and outlet temperatures when the type ... |
W_coldCpMin = W_cold*Cp_cold;
if ( Wh*Cp_hot < W_cold*Cp_cold ):
W_coldCpMin = Wh*Cp_hot
self.Qmax = W_coldCpMin*(T_hot_in - T_cold_in)*1.4148532; #BTU/s to hp
self.Qreleased = Wh*Cp_hot*(T_hot_in - T_hot_out)*1.4148532;
self.Qabsorbed = W_cold*Cp_cold*(T_cold_o... | ry:
self.LMTD = ((T_hot_out-T_hot_in)+(T_cold_out-T_cold_in))/log((T_hot_out-T_cold_in)/(T_hot_in-T_cold_out))
except ZeroDivisionError:
self.LMTD = 0
self.residual_qmax = self.Qreleased-self.effectiveness*self.Qmax
self.residual_e_balance = self.Qreleased-self.Qabsor... |
# -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | ral Public License for more details.
#
# You should have received a copy of the GNU Affero General P | ublic License
# along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>.
"""Flickr module for authentication."""
from flask_oauthlib.client import OAuth
import functools
import requests
class FlickrClient(object):
"""Class for Flickr integration."""
def __init__(self, api_key, logger=None):
... |
"""
tests.pytests.unit.beacons.test_bonjour_announce
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~
Bonjour announce beacon test cases
"""
import pytest
import salt.beacons.bonjour_announce as bonjour_announce
@pytest.fixture
def configure_loader_modules():
return {
bonjour_announce: {"last_state": {}, "last_state_extra": {"no_devices": False}}
}
def test_non_list_config():
... | beacon must be a list.")
def test_empty_config():
config = [{}]
ret = bonjour_announce.validate(config)
assert ret == (
False,
"Configuration for bonjour_announce beacon must contain servicetype, port and"
" txt items.",
)
|
class Interval(object):
"""
Represents an interval.
Defined as half-open interval [start,end), which includes the start position but not the end.
Start and end do not have to be numeric types.
"""
def __init__(self, start, end):
"Construct, start must be <= end."
if s... | "As string."
return '[%s,%s)' % (self.start, self.end)
def __repr__(self):
"String representation."
return '[%s,%s)' % (self.start, self.end)
| def __cmp__(self, other):
"Compare."
if None == other:
return 1
start_cmp = cmp(self.start, other.start)
if 0 != start_cmp:
return start_cmp
else:
return cmp(self.end, other.end)
def __hash__(self):
"Hash."
return hash(sel... |
#
# $Filename$$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
... | itions and the following disclaimer in the
# documentation and/or other materials provided with the
# distribution.
#
# * Neither the name of the German Aerospace Center nor the names of
# its contributors may be used to endorse or promote products derive | d
# from this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#A PARTICULAR PURPOSE ARE DISCLAI... |
"""
Publishes the Referee Box's messages as a ROS topic named "refbox" with type "referee"
"""
from referee_pb2 import SSL_Referee
import rospy
# Substitute "ekbots" here with your ROS package name
from ekbots.msg import referee, team_info
from socket import socket, inet_aton, IPPROTO_IP, IP_ADD_MEMBERSHIP
from soc... | anslate the team info
for team, buf in ((yellow, proto.yellow), (blue, proto.blue)):
team.name = buf.name
team.score = buf.score
team.red_cards = buf.red_cards
team.ye | llow_card_times = buf.yellow_card_times
team.yellow_cards = buf.yellow_cards
team.timeouts = buf.timeouts
team.timeout_time = buf.timeout_time
team.goalie = buf.goalie
trama.yellow = yellow
trama.blue = blue
# Translate the rest
trama.packet_timestamp = proto.packet_timestamp
trama.stage = proto.stage
... |
R_LAST_DATA,
ATTR_MONITORED_CONDITIONS,
CONF_APP_KEY,
DATA_CLIENT,
DOMAIN,
TYPE_BINARY_SENSOR,
TYPE_SENSOR,
)
_LOGGER = logging.getLogger(__name__)
DATA_CONFIG = "config"
DEFAULT_SOCKET_MIN_RETRY = 15
TYPE_24HOURRAININ = "24hourrainin"
TYPE_BAROMABSIN = "baromabsin"
TYPE_BAROMRELIN = "baromr... | ENTAGE, TYPE_SENSOR, "humidity"),
TYPE_SOILHUM9: ("Soil Humidity 9", PERCENTAGE, TYPE_SENSOR, "humidity"),
TYPE_SOILTEMP10F: ("Soil Temp 10", TEMP_FAHRENHEIT, TYPE_SENSOR, "temperature"),
TYPE_SOILTEMP1F: ("Soil Temp 1", TEMP_FAHRENHEIT, TYPE_SENSOR, "temperature"),
TYPE_SOILTEMP2F: ("Soil Temp 2", TEMP... | emp 4", TEMP_FAHRENHEIT, TYPE_SENSOR, "temperature"),
TYPE_SOILTEMP5F: ("Soil Temp 5", TEMP_FAHRENHEIT, TYPE_SENSOR, "temperature"),
TYPE_SOILTEMP6F: ("Soil Temp 6", TEMP_FAHRENHEIT, TYPE_SENSOR, "temperature"),
TYPE_SOILTEMP7F: ("Soil Temp 7", TEMP_FAHRENHEIT, TYPE_SENSOR, "temperature"),
TYPE_SOILTEMP... |
from __future__ import division
from PIL import Image
from . import modes
from .transform import Transform
class ImageSize(object):
@property
def image(self):
if not self._image and self.path:
self._image = Image.open(self.path)
return self._image
def __init__(self, path=No... | if not self.width:
self.needs_enlarge = self.height > self.image_height
if not self.enlarge:
self.height = min(self.height, self.image_height)
self.width = self.image_width * self.height // self.image_height
return
# Don't maintain aspect ra... | not self.enlarge:
self.width = min(self.width, self.image_width)
self.height = min(self.height, self.image_height)
return
if self.mode not in (modes.FIT, modes.CROP, modes.PAD):
raise ValueError('unknown mode %r' % self.mode)
# This effectively ... |
# -*- coding: utf-8 -*-
from datetime import datetime
from app import db
from app.models import components_tags
from app.users.models import User
from app.tags.models import Tag
from app.util import unix_time
class WebComponent(db.Model):
__tablename__ = 'web_component'
id = db.Column(db.Integer, primary_ke... | .Column(db.String(256))
tags = db.relationship(
Tag,
secondary=components_tags,
backref=db.backref('web_components', lazy='dynamic'))
def __init__(
self,
name,
description,
owner,
repository_url):
self.created = datetim... | y_url = repository_url
def __iter__(self):
return {
'id': self.id,
'created': unix_time(self.created),
'name': self.name,
'description': self.description,
'owner': dict(self.owner),
'repository_url': self.repository_url,
't... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import timeline_recorder
from telemetry.timeline import inspector_timeline_data
class TabBackendException(Exception):
... | s = result['events']
return inspector_timeline_data.InspectorTimelineData(raw_events)
def _SendSyncRequest(self, request, timeout=60):
"""Sends a devtools remote debugging protocol request.
The types of request that are valid is determined by protocol.json:
https://src.chro | mium.org/viewvc/blink/trunk/Source/devtools/protocol.json
Args:
request: Request dict, may contain the keys 'method' and 'params'.
timeout: Number of seconds to wait for a response.
Returns:
The result given in the response message.
Raises:
TabBackendException: The response indica... |
elf.CalcSum = CalcSum
def __str__(self):
schecksum = ('%04Xh (%04Xh) *** checksum mismatch ***' % (self.Checksum,self.CalcSum)) if self.CalcSum != self.Checksum else ('%04Xh' % self.Checksum)
_s = "\n%s%s +%08Xh {%s}\n%sType %02Xh, Attr %08Xh, State %02Xh, Size %06Xh, Checksum %s" % (self.i... | % fv_pth), fv.MD5 )
if fv.SHA1 != '': write_file( ("%s.sha1" % fv_pth), fv.SHA1 )
if fv.SHA256 != '': write_file( ("%s.sha256" % fv_pth), fv.SHA256 )
volume_path = os.path.join( uefi_region_path, "%02d_%s.dir" % (voln, fv.Guid) )
if not os.path.exists( volume_path ): os.makedirs( volume_path )
... | I_SECTION_PE32: 'pe32', EFI_SECTION_TE: 'te', EFI_SECTION_PIC: 'pic', EFI_SECTION_COMPATIBILITY16: 'c16'}
def dump_section( sec, secn, parent_path, efi_file ):
if sec.Name is not None:
sec_fs_name = "%02d_%s" % (secn, sec.Name)
section_path = os.path.join(parent_path, sec_fs_name)
if se... |
from __future__ import division
import numpy as np
from . import common_args
from ..util import scale_samples, read_param_file
def sample(problem, N, seed=None):
"""Generate model inputs using Latin hypercube sampling (LHS).
Returns a NumPy matrix containing the model inputs generated by Latin
... | o CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument('-n', '--samples', type=int, required=True,
help='Number of Samples')
return parser
def cli_action(args):
""... | ram_file(args.paramfile)
param_values = sample(problem, args.samples, seed=args.seed)
np.savetxt(args.output, param_values, delimiter=args.delimiter,
fmt='%.' + str(args.precision) + 'e')
if __name__ == "__main__":
common_args.run_cli(cli_parse, cli_action)
|
#!/usr/bin/env python
'''
Define functions to query the twitch.tv streaming
websites.
More info on the Twitch.tv REST api here:
https://github.com/justintv/twitch-api
'''
import sys
import logging
import requests
'''
Twitch.tv API stream listing request. This API call takes a comma
separated list of channel names... | ay
# which are currently streaming
def fetch_streams(channel_names):
response = requests.get(STREAM_URL % (",".join(channel_names)))
try:
message = response.json()["streams"]
except ValueError:
# JSON Decode failed
sys.exit("Invalid message from twitch.tv: %s" % (response.text))
... | urn message
|
from __future__ import with_statement
from fabric.contrib.console import confirm
from fabric.api import local
import fileinput
def server(port=""):
replace_for_local()
if port:
local("python manage.py runserver 0.0.0.0:" + port + " | --settings=linkedin_search.local")
else:
local("python manage.py runserver 0.0.0.0:8888 --settings=linkedin_search.local")
def test():
local("python manage.py te | st --settings=linkedin_search.local")
def setting(setting=""):
local("python manage.py " + setting + " --settings=linkedin_search.local")
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | --------------------------------------------------------------------------
from .proxy_only_resource import ProxyOnlyResource
class BackupRequest(ProxyOnlyResource):
"""Description of a backup which will be performed.
Variables are only populated by the server, and will be ignored when
sending a request... | Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
:param backup_request_name: Name of the backup.
:type backup_request_name: str
:param enabled: True if the backup schedule is enabled (must be included
in that case... |
from __future__ import print_function
import numpy as np
import turtle
from argparse import ArgumentParser
from base64 import decodestring
from zlib import decompress
# Python 2/3 compat
try:
_input = raw_input
except NameError:
_input = input
'''TODO:
* add a matplotlib-based plotter
* add a path export functi... | e.startswith(b'DEFINE '):
continue
_, kind, number = line.split()
kind = kind.decode('ascii')
number = int(number)
raw_data = | b''
while not line.endswith(b';'):
line = next(lines).strip()
raw_data += line
# strip ; terminator
raw_data = raw_data[:-1]
# add base64 padding
if len(raw_data) % 4 != 0:
raw_data += b'=' * (2 - (len(raw_data) % 2))
# decode base64 -> decode zlib -> convert to byte array
... |
quence-ToolKit/2016/resources/ui/genrep/dialogs/apply_this_to.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_apply_to(object):
def setupUi(self, apply_to):
apply_to.setObjectName("apply_to")
... | 160, 28))
self.value_1.setObjectName("value_1")
self.gridLayout.addWidget(self.value_1, 1, 2, 1, 1)
self.criterion_1 = QtWidgets.QComboBox(self.form_area)
self.criterion_1.setMinimumSize(QtCore.QSize(160, | 28))
self.criterion_1.setObjectName("criterion_1")
self.criterion_1.addItem("")
self.criterion_1.addItem("")
self.criterion_1.addItem("")
self.criterion_1.addItem("")
self.gridLayout.addWidget(self.criterion_1, 1, 0, 1, 1)
self.value_2 = QtWidgets.QLineEdit(self.f... |
from functools import wraps
import numpy
from theano import scalar as scal, Constant
from theano.gof import local_optimizer
from theano.tensor import (DimShuffle, get_scalar_constant_value,
NotScalarConstantError)
from .basic_ops import GpuFromHost, HostFromGpu
from .elemwise import GpuDim... | node.op.scalar_op == scal.add and
node.nin == 2):
targ = find_node(node.inputs[0], cls)
W = node.inputs[1]
if targ is None:
targ = find_node(node.inputs[1], cls)
W = node.inputs[0]
| if targ is None:
return None
if not is_equal(targ.inputs[beta_in], 0.0):
# other cases are too complex for now
return None
if W.broadcastable != targ.inputs[out_in].broadcastable:
# Would need to exp... |
length = self[linklist[0]].shape[0]
for l in linklist:
if self[l].shape[0] != length:
raise OutOfSyncError
self.link = linklist
def unlinkFields(self, unlinklist=None):
"""Remove fields from the link list or clears link given by the list of
string `... | = self.endmarker[max(self.endmarker)]
except ValueError:
return 0
return length
else:
| # all linked fields have equal length. return the length of the first.
l = self.link[0]
return self.endmarker[l]
def _resize(self, label=None):
if label:
label = [label]
elif self.link:
label = self.link
else:
label = s... |
from twisted.web.server import | Site
from .root import RootResource
from .auth import AuthResource
def make_site(**kwargs):
root_resource = RootResource()
auth_resource = AuthResource(kwargs['authenticator'])
root_resource.putChild('a | uth', auth_resource)
return Site(root_resource)
|
Number of samples per class from train
num_valid_extra : int, optional
Number of samples per class from extra
"""
# load difficult train
data = load("{0}train_32x32.mat".format(SVHN.data_path))
valid_index = []
for i ... | WRITEME
"""
sizes = {'train': 73257, 'test': 26032, 'extra': 531131,
'train_all': 604388, 'valid': 6000, 'splitted_train' : 598388}
image_size = 32 * 32 * 3
# For consistency between experiments better to make new random stream
rng = make_np_rng(None, 322, ... | fle")
def design_matrix_view(data_x, data_y):
"""reshape data_x to deisng matrix view
and data_y to one_hot
"""
data_x = numpy.transpose(data_x, axes = [3, 2, 0, 1])
data_x = data_x.reshape((data_x.shape[0], 32 * 32 * 3))
# TODO assuming ... |
This file is part of conftron.
##
## Copyright (C) 2011 Matt Peddie <peddie@jobyenergy.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 version 2 of the
## License, or (at y... | if self.has_key('absmax'):
self.min = -float(self.absmax)
self.max = float(self.absmax)
self.parent = parent
self.parentname = parent.name
self._musthave(parent, parse_settings_noval)
self.classname = parent.classname
parent.die += self._filter()
def... | return die
def _are_defaults_sane(self):
## Default values outside the range given by the bounds
## don't make sense either.
die = 0
if (float(self['min']) > float(self['default'])
or float(self['max']) < float(self['default'])):
print parse_settings_badval... |
# 1. del: funkcije
#gender: female = 2, male = 0
def calculate_score_for_gender(gender):
if gender == "male":
return 0
else: return 2
#age: 0-100 if age < 10 --> 0, 11 < age < 20 --> 5, 21 < age < 35 --> 2, 36 < age < 50 --> 4, 50+ --> 1
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age >... | lt += calculate_score_for_status(status)
result += calculate_score_for_ignorance(ignorance)
result += calculate_score_for_money_have(money_have)
result += calucula | te_score_for_money_want(money_want)
result += calculate_score_for_rl_friends(rl_friends)
result += calculate_score_for_children(children)
return result
# 3. del: ------------- output za userja
#gender
print "Are you male or female?"
gender = raw_input(">> ")
#note to self: "while" pomeni da cekira na loop, "if" c... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import os
import sys
import re
import gettext
from oxy.arg import parse as argparse
from oxy.verbose import VerboseOutput
class Mbox():
NONE = 0
READ = 1
HEADERCANDIDATE = 2
COPY = 3
END = 4
vOut = None
state = NONE
nLine = 0
header... | Header line = "{}" = {}'.format(
line[:20], result), 3)
return result
def isInsideHeader():
line = self.cleanLine()
result = bo | ol(
re.search('^[^ ]+: .*$', line)
or re.search('^\s+[^ ].*$', line)
)
self.vOut.prnt('isInsideHeader line = "{}" = {}'.format(
line[:20], result), 3)
return result
def ifGetMessageId():
line = self.cleanLine()
... |
from gu | i import playerDialog
name = "haha"
name = playerDialog().show()
prin | t(name)
|
Exception):
await self.collection.upsert(self.KEY, self.CONTENT)
@async_test
async def test_raw_bin_tc_json_insert(self):
with self.assertRaises(ValueFormatException):
await self.collection.insert(self.KEY, self.CONTENT)
@async_test
async def test_raw_bin_tc_json_replac... | cy_tc_json_upsert(self):
await self.collection | .upsert(self.KEY, self.CONTENT)
resp = await self.collection.get(self.KEY)
result = resp.content_as[dict]
self.assertIsNotNone(result)
self.assertIsInstance(result, dict)
self.assertEqual(self.CONTENT, result)
@async_test
async def test_legacy_tc_json_insert(self):
... |
import wx
import sys
import os
import time
import threading
import math
import pynotify
import pygame.mixer
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python")
from pprzlink.ivy import IvyMessagesInterface
WIDTH = 150
HEIGHT = 40
UPDATE_INTERVAL = 250
class RadioWatchFrame(wx.Frame):... | rclink_alert)
# else:
# self.notification.close()
def gui_update(self):
self.rc_statusText.SetLabel(["OK", "LOST", "REALLY LOST"][self.rc_status])
self.update_timer.Restart(UPDATE_INTERVAL)
def rclink_alert(self):
self.alertChannel.queue(self.alertSound)
... | font.SetPointSize(size * 1.4)
control.SetFont(font)
def __init__(self):
wx.Frame.__init__(self, id=-1, parent=None, name=u'RCWatchFrame',
size=wx.Size(WIDTH, HEIGHT), title=u'RC Status')
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.rc_statusText = wx.Stat... |
#import wrftools
#from exceptions import ConfigError, DomainError | , ConversionError
#import tools
#import io
#__all__ = ['wrftools', 'tools', 'io']
| |
import sys
import types
import typing as t
import decorator as deco
from gssapi.raw.misc import GSSError
if t.TYPE_CHECKING:
from gssapi.sec_contexts import SecurityContext
def import_gssapi_extension(
name: str,
) -> t.Optional[types.ModuleType]:
"""Import a GSSAPI extension module
This method im... | return func(self, *args, **kwargs)
except GSSError as e:
defer_step_errors = getattr(self, '__DEFER_STEP_ERRORS__', False)
if e.token is not None and defer_step_errors:
self._last_err = e
# skip the "return func" line above in the traceback
tb = e.__traceback__.... | rator
def check_last_err(
func: t.Callable,
self: "SecurityContext",
*args: t.Any,
**kwargs: t.Any,
) -> t.Any:
"""Check and raise deferred errors before running the function
This method checks :python:`_last_err` before running the wrapped
function. If present and not None, the exception ... |
from mio import runtime
from mio.utils import method
from mio.object import Object
from mio.lexer import encoding
from mio.core.message import Message
from mio.errors import Attribute | Error
class String(Object):
def __init__(self, value=u""):
super(String, self).__init__(value=value)
self.create_methods()
try:
self.parent = runtime.find("String")
except AttributeError:
self.parent = runtime.find("Object")
def __iter__(self):
... | other
def __int__(self):
return int(self.value)
def __float__(self):
return float(self.value)
def __repr__(self):
return "u\"{0:s}\"".format(self.value)
def __str__(self):
return self.value.encode(encoding)
def __unicode__(self):
return self.value
@... |
registry = set()
def register(active=True):
def decorate(f | unc):
print('running register(active=%s)->decorate(%s)' % (active, func))
if active:
registry.add(func)
else:
registry.discard(func)
return func
return decorate
@register(active=False)
def f1():
print('running f1()')
@register()
def f2()... |
def f3():
print('running f3()') |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
"""OVH DynHost IP Updater.
Updates at least every 15 minutes the DynHost Record IP of the server.
Uses the OVH API.
Requires:
* ovh - https://github.com/ovh/python-ovh
* ipgetter - https://github.com/phoemur/ipgetter
"""
import re
import time
import os.path
import ConfigPar... | ler(ch)
# The paths in the OVH API (api.ovh.com)
UPDATE_PATH = "/domain/zone/{zonename}/dynHost/record/{id}"
REFRESH_PATH = "/domain/zone/{zonename}/refresh"
# The file where the IP will be stored
# As the script doesn't run continuosly, we need to retreive the IP somewhere...
IP_FILE = "stored_ip.txt"
# The period ... | every minute, this reduces the number of calls to the
# OVH server.
MIN_UPDATE_TIME = 15 # In minutes [1-59]
# Regex for checking IP strings
check_re = re.compile(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
def get_conf():
"""Get the configuration from the file `sub... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-18 23:22
from __future__ import unicode_literals
from django.db import migrations
import enumfields.fields
import wallet.enums
import enum
class TrxType(enum.Enum):
FINALIZED = 0
PENDING = 1
CANCELLATION = 2
class Migration(migrations.Migr... | ('wallet', '0009_remove_wallettransaction_trx_status'),
]
operations = [
migrations.AlterField(
model_name='wallettransaction',
name='trx_type',
field=e | numfields.fields.EnumIntegerField(default=0, enum=TrxType),
),
]
|
"""
Tests for miscellaneous models
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import | , print_function
import numpy as np
import pandas as pd
import os
import re
import warnings
from statsmodels.tsa.statespace import mlemodel
from statsmodels imp | ort datasets
from numpy.testing import assert_almost_equal, assert_equal, assert_allclose, assert_raises
from nose.exc import SkipTest
from .results import results_sarimax
current_path = os.path.dirname(os.path.abspath(__file__))
class Intercepts(mlemodel.MLEModel):
"""
Test class for observation and state i... |
BACKUPPC_DIR = "/usr/share/backuppc"
TARGET_HOST = "192.168.1.65"
BACKUPPC_USER_UID = 110
BACKUPPC_USER_GID = 116
DEBUG = False
TRANSLATIONS = {
'Status_idle': 'inattivo',
'Status_backup_starting': 'avvio backup',
'Status_backup_in_progress': 'backup in esecuzione',
'Status_restore_starting': 'avvio ri... | archivio fallito',
'Reason_no_ping': 'no ping',
'Reason_backup_canceled_by_user': 'backup annullato dall\'utente',
'Reason_restore_canceled_by_user': 'ripristino annullato dall\'utente',
'Reason_archive_canceled_by_user': 'archivio annullato dall\'utente',
'Disabled_OnlyManualBackups': 'auto disabil... | tato',
'Disabled_AllBackupsDisabled': 'disabilitato',
'full': 'completo',
'incr': 'incrementale',
'backupType_partial': 'parziale',
} |
ption( "Kan het project " + self.projectpath + " niet aanmaken")
for root, _ , filenames in os.walk(os.path.join(self.datafolder, self.name)):
for filename in filenames:
if filename.endswith(SHAPEFILE_TAG):
if filename.startswith(PROFIELEN_TAG):
... | :
"""
Data laden en controleren uit een gegeven folder default is het ./data.
In de datafolder dienen folders staan in het volgende hierarchie
data -> klant_1
project_1
hydrovakken shapebestanden
dwg profielen shapebestanden
| en metfiles
project_2
...
- klant_2
...
De databestaden moeten beginnen met volgende prefixen
HYDROVAKKEN_TAG = "Hydrovakken_"
PROFIELEN_TAG = "DWP_"
METFILE_TAG = ".met"
SHAPEFILE_TAG =".shp"
... |
size=[USR_AGE_DICT_SIZE, 16],
is_sparse=IS_SPARSE,
param_attr='age_table')
usr_age_fc = layers.fc(input=usr_age_emb, size=16)
USR_JOB_DICT_SIZE = paddle.dataset.movielens.max_job_id() + 1
usr_job_id = layers.data(name='job_id', shape=[1], dtype="int64")
usr_job_emb = layers.embedd... | ut
assert feed_target_names[0] == "user_i | d"
# Use create_lod_tensor(data, recursive_sequence_lengths, place) API
# to generate LoD Tensor where `data` is a list of sequences of index
# numbers, `recursive_sequence_lengths` is the length-based level of detail
# (lod) info associated with `data`.
# For example, data = [[1... |
c.start()
assert proc.is_alive()
assert proc.exitcode is None
q.put(5)
await proc.join(timeout=30)
assert not proc.is_alive()
assert proc.exitcode == 5
@pytest.mark.skipif(WINDOWS, reason="POSIX only")
@gen_test()
async def test_signal():
proc = AsyncProcess(target=exit_with_signal, args=... | ()
# FIXME: this breaks if changed to async def...
@gen.coroutine
def on_stop(_proc):
assert _proc is proc
yield gen.moment
evt.set()
# Normal process exit
proc = AsyncProcess(target=feed, args=(to_child, from_child))
| evt.clear()
proc.set_exit_callback(on_stop)
proc.daemon = True
await proc.start()
await asyncio.sleep(0.05)
assert proc.is_alive()
assert not evt.is_set()
to_child.put(None)
await evt.wait(timedelta(seconds=5))
assert evt.is_set()
assert not proc.is_alive()
# Process termi... |
'''
A Multilayer Perceptron implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
import tensorf... | _logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
a... | i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
y: batch_y})
... |
'''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Idaho class
'''
from gbdxtools import Interface
from gbdxtools.idaho import Idaho
from auth_mock import get_mock_gbdx_session
import vcr
from os.path import join, isfile, dirname, realpath
import tempfile
impor... | ages_by_catid_and_aoi.yaml', filter_headers=['authorization'])
def test_idaho_get_images_by_catid_and_aoi(self):
i = Idaho(self.gbdx)
catid = '10400100203F1300'
aoi_wkt = "POLYGON ((-105.0207996368408345 39.7338828628182839, -105.0207996368408345 39.7365972921260067, -105.0158751010894775 39... | 94775 39.7338828628182839, -105.0207996368408345 39.7338828628182839))"
results = i.get_images_by_catid_and_aoi(catid=catid, aoi_wkt=aoi_wkt)
assert len(results['results']) == 2
@vcr.use_cassette('tests/unit/cassettes/test_idaho_get_images_by_catid.yaml', filter_headers=['authorization'])
def t... |
re_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], islist=True)
DEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEFAULTS, 'var_compression_level', 'ANSIBLE_VAR_COMPRESSION_LEVEL', 0, integer=True)
# disclosure
DEFAULT_NO_LOG = get_config(p, DEFAULTS, '... | S', None)
DEFAULT_BECOME_ASK_PASS = get_config(p, 'privilege_escalation', 'become_ask_pass', 'ANSIBLE_BECOME_ASK_PASS', False, boolean=True)
# PLUGINS
# Modules that | can optimize with_items loops into a single call. Currently
# these modules must (1) take a "name" or "pkg" parameter that is a list. If
# the module takes both, bad things could happen.
# In the future we should probably generalize this even further
# (mapping of param: squash field)
DEFAULT_SQUASH_ACTIONS ... |
from coinpy.lib.serialization.structures.s11n_tx import TxSerializer
from coinpy.model.constants.bitcoin import MAX_BLOCK_SIZE, is_money_range
from coinpy.lib.serialization.scripts.serialize import ScriptSerializer
class TxVerifier():
def __init__(self, runmode):
self.runmode = runmode
self.tx_ser... | ge : %d bytes" % (len(tx.rawdata | )))
def check_vin_empty(self, tx):
if (not tx.in_list):
raise Exception("vin empty" )
def check_vout_empty(self, tx):
if (not tx.out_list):
raise Exception("vout empty" )
def check_money_range(self, tx):
for txout in tx.out_list:... |
""" Simple JSON-RPC 2.0 protocol for aiohttp"""
from .exc import (ParseError, InvalidRequest, InvalidParams,
InternalError, InvalidResponse)
from .errors import JError, JResponse
from validictory import validate, ValidationError, SchemaError
from functools import wraps
from uuid import uuid4
from aio... | # Good if does not valid to ERR_JSONRPC20 object.
pass
except Exception as err:
raise InvalidResponse(err)
try:
validate(data, RSP_JSONRPC20)
if id != data['id']:
raise InvalidResponse(
"Rsponse id {local} not eq... | nse(err)
if schem:
try:
validate(data['result'], schem)
except ValidationError as err:
raise InvalidResponse(err)
except Exception as err:
raise InternalError(err)
return Response(**data)
|
import SocketServer
class ProtoHandler(SocketServer.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
a = msg.split(" ",2)
if len(a) >1 and a[0] == "GET":
a = a[1].split("/")
a =[i for i in a if i != '']
if len(a) == 0:
| self.request.sendall(self.server.ret)
else:
self.server.data=a
print a
class ProtoServer(SocketServer.TCPServer):
def __init__(self,hostport,default):
self.allow_reuse_address = True
SocketServer.TCPServer.__init__(self,... | , 6661),"index.html")
s.serve_forever()
|
from pymysql.times import TimeDelta
from pymysql.constants import ER, FIELD_TYPE
from pymysql.converters import conversions
import pymysql
# Helpers
def _cast_result(doctype, result):
batch = [ ]
try:
for field, value in result:
df = frappe.get_meta(doctype).get_field(field)
if df:
value = cast_fieldty... | frappe.log("with values:")
frappe.log(values)
frappe.log(">>>>")
self._cursor.execute(query, values)
else:
if debug:
self.explain_query(query)
frappe.errprint(query)
if (frappe.conf.get("logging") or False)==2:
fr | appe.log("<<<< query")
frappe.log(query)
frappe.log(">>>>")
self._cursor.execute(query)
except Exception as e:
if ignore_ddl and e.args[0] in (ER.BAD_FIELD_ERROR, ER.NO_SUCH_TABLE,
ER.CANT_DROP_FIELD_OR_KEY):
pass
# NOTE: causes deadlock
# elif e.args[0]==2006:
# # mysql has gone... |
def get_stack_elements(stack):
return stack[1:stack.to | p].elements
def get_queue_elements(queue):
if queue.head <= queue.tail:
return queue[queue.head:queue.tail - 1].elements
| return queue[queue.head:queue.length].elements + queue[1:queue.tail - 1].elements
|
"""
.. module:: editor_subscribe_label_deleted
The **Editor Subscribe Label Deleted** Model.
PostgreSQL Definition
---------------------
The :code:`editor_subscribe_label_deleted` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE editor_subscribe_label_deleted
(
editor... | ementation.
:param editor: ref | erences :class:`.editor`
:param gid: references :class:`.deleted_entity`
:param deleted_by: references :class:`.edit`
"""
editor = models.OneToOneField('editor', primary_key=True)
gid = models.OneToOneField('deleted_entity')
deleted_by = models.ForeignKey('edit')
def __str__(self):
... |
from distutils.core import setup
from setuptools import find_packages
setup(name='blitzdb',
version='0.2.12',
author='Andreas Dewes - 7scientists',
author_email='andreas@7scientists.com',
license='MIT',
entry_points={
},
url='https://github.com/adewes/blitzdb',
packages=find_packages(),
zip_safe=False,
description... | se feel free to `submit an issue <https://github.com/adewes/blitzdb/issues>`_ on Github.
Changelog
=========
* 0.2.12: Added support for proper att | ribute iteration to `Document`.
* 0.2.11: Allow setting the `collection` parameter through a `Document.Meta` attribute.
* 0.2.10: Bugfix-Release: Fix Python 3 compatibility issue.
* 0.2.9: Bugfix-Release: Fix serialization problem with file backend.
* 0.2.8: Added `get`, `has_key` and `clear` methods to `Document` clas... |
"""
.. todo::
WRITEME
"""
import theano.tensor | as T
from theano.gof.op import get_debug_values
from theano.gof.op import debug_assert
import numpy as np
from theano.tensor.xlogx import xlogx
from pylearn2.utils import contains_nan, isfinite
de | f entropy_binary_vector(P):
"""
.. todo::
WRITEME properly
If P[i,j] represents the probability of some binary random variable X[i,j]
being 1, then rval[i] gives the entropy of the random vector X[i,:]
"""
for Pv in get_debug_values(P):
assert Pv.min() >= 0.0
assert Pv... |
import re
import unicodedata
from injector import inject, AssistedBuilder
import cx_Oracle as pyoracle
class Oracle(object):
"""Wrapper to connect to Oracle Servers and get all the metastore information"""
@inject(oracle=AssistedBuilder(callable=pyoracle.connect), logger='logger')
def __init__(self, orac... | ame, | column_name, data_type, data_length, nullable, data_default, data_scale " \
"FROM ALL_TAB_COLUMNS " \
"WHERE table_name IN ({tables}) " \
"{owner}" \
"ORDER BY COLUMN_ID".format(tables=self.__join_tables_list(tables), owner=query_with_... |
"""
A python class to encapsulate the ComicBookInfo data
"""
"""
Copyright 2012-2014 Anthony Beville
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... | assign('numberOfIssues', toInt(metadata.issueCount))
assign('comments', metadata.comments)
assign('genre', metadata.genre)
assign('volume', toInt(metadata.volume))
assign('numberOfVolumes', toInt(metadata.volumeCount))
assign('language', calibre_langcode_to_name(canonicalize_la... | ting)
assign('credits', metadata.credits)
assign('tags', metadata.tags)
return cbi_container
|
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
},
'us-east-1': {
'endpoint': 'api.us-east-1.outscale.com',
... | ck',
'transform_func': str
}
},
'network_interface_attachment': {
'attachment_id': {
'xpath': 'attachment/attachmentId',
'transform_func': str
},
'instance_id': {
'xpath': 'attachment/instanceId',
'transform_func': str
... | func': str
},
'device_index': {
'xpath': 'attachment/deviceIndex',
'transform_func': int
},
'status': {
'xpath': 'attachment/status',
'transform_func': str
},
'attach_time': {
'xpath': 'attachment/attachTime',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-09 22:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comercial', '0061_auto_20160206_2052'),
]
operations = [
migrations.AddField(
... | =True, choices=[(b'texto', b'Texto'), (b'inteiro', b'Inteiro'), (b'decimal', b'Decimal')], max_ | length=100),
),
]
|
l_field.context = {'request': request}
# Establish that there is no serializer class on the related
# field yet.
self.assertFalse(hasattr(rel_field, '_serializer_class'))
# Create a serializer class.
ret_val = rel_field._create_serializer_class(RelatedModel)
self.assert... | self.rel_field.queryset = NormalModel.objects.get_queryset()
else:
self.rel_field | .queryset = NormalModel.objects.get_query_set()
def test_related_field_from_id_dict(self):
"""Test that a related field's `from_native` method, when
sent a dictionary with an `id` key, returns that ID.
"""
# Test the case where we get a valid value back.
with mock.patch.obje... |
def extractChuunihimeWordpressCom(item):
'''
Parser for 'chuunihime.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
r | eturn None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
r | eturn False
|
import functools
import itertools
import json
import multiprocessing
import os
import shutil
import sys
import time
import cv2
import numpy
import utility.config
import utility.cv
import utility.geometry
import utility.gui
import utility.image
import utility.log
# Explicitly disable OpenCL. Querying for OpenCL suppo... | igher score
best_match = match
continue
# Save best match
| matches.append(best_match)
utility.log.performance("matches", start)
# Determine action
possible_actions = utility.geometry.calculate_actions(matches)
utility.log.performance("calculate_actions", start)
for action in possible_actions:
if action["action"] == "double" and action["dista... |
self.em_template_file, em_file)
context.add_artifact('em', em_file, 'data')
report_file = os.path.join(output_directory, 'report.html')
generate_report(freq_power_table, measured_cpus_table, cpus_table,
idle_power_table, self.report_template_file,
... | elf.little_energy_metrics = []
if self.power_metric:
self.big_power_metrics = [pm.format(core=self.big_core) for pm in self.power_metric]
self.little_power_metrics = [pm.format(core=self.little_core) for pm in self.power_metric]
else: # must be energy_metric
self.big... | metrics = [em.format(core=self.big_core) for em in self.energy_metric]
self.little_energy_metrics = [em.format(core=self.little_core) for em in self.energy_metric]
def configure_clusters(self):
self.measured_cores = None
self.measuring_cores = None
self.cpuset = self.device.get_... |
# encoding: utf-8
# Copyright 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
| # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses | /LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitation... |
import requests
class DrygDAO:
def __init__(self):
pass
def get_day | s_for_year(self, year):
response = requests.get("http://api.dryg.net/dagar/v2.1/%s" % year)
data = respon | se.json()
workdays = [x["datum"] for x in data["dagar"] if x["arbetsfri dag"] == "Nej"]
return workdays
|
{'level_mc': {'_txt': {'text': '6'},
'currentLabel': 'up',
| 'progress_m | c': {'currentLabel': '_0'}}} |
of the SectionClassifiers appears again in sec_name)
* level (0 if it is top level sections: chapters, and so on)
* a list of exercises beloging to the section and
* a dictionary of subsections (again Section objects)
* Section = (sec_name, level, [list of e... | n belong to a section/subsection/subsubsection.
Write sections using ';' in the '%summary' line. For ex., '%summary Section; Subsection; Subsubsection'.
<BLANKLINE>
| Each problem can have a suggestive name.
Write in the '%problem' line a name, for ex., '%problem The Fish Problem'.
<BLANKLINE>
Check exercise E28E28_pdirect_003 for the above warnings.
-------------------------------
Instance of: E28E28_pdirect_003
--------------------... |
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache. | org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an | "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-10 23:14
from __future__ import unicode_literals
from django... |
#!/usr/bin/env python
# Copyright (C) 2011 Igalia S.L.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This... | er General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import os
script_dir = None
def script_path(*args):
global script_dir
if not script_dir:
script_dir = os.path.join(os.path.dirname(... | p_level_path(*args):
return os.path.join(*((script_path('..', '..'),) + args))
|
import base64
import logging
import platform
from datetime import date, timedelta
from invoke import run, task
from elasticsearch import helpers
from dateutil.parser import parse
from six.moves.urllib import parse as urllib_parse
import scrapi.harvesters # noqa
from scrapi import linter
from scrapi import registry
f... | =1000):
''' Task to run a migra | tion.
:param migration: The migration function to run. This is passed in
as a string then interpreted as a function by the invoke task.
:type migration: str
:param kwargs_string: parsed into an optional set of keyword
arguments, so that the invoke migrate task can accept a variable
number of a... |
# Created by Sean Nelson on 2018-08-19.
# Copyright 2018 Sean Nelson <audiohacked@gmail.com>
#
# This file is part of pyBusPirate.
#
# pyBusPirate 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... | rial.Serial', autospec=True)
def setUp(self, mock_serial): # pylint: disable=W0613,W0221
self.bus_pirate = onewire.OneWire("/dev/ttyUSB0")
def tearDown(self):
pass
def test_exit(self):
self.bus_pirate.serial.read.return_value = "BBIO1"
self.assertEqual(self.bus_pirate.exit,... | (0x00)
def test_mode(self):
self.bus_pirate.serial.read.return_value = "1W01"
self.assertEqual(self.bus_pirate.mode, "1W01")
self.bus_pirate.serial.write.assert_called_with(0x01)
def test_enter(self):
self.bus_pirate.serial.read.return_value = "1W01"
self.assertEqual(se... |
from django import template
import cle | vercss
register = template.Library()
@register.tag(name="clevercss")
def do_clevercss(parser, token):
nodelist = parser.parse(('endclevercss',))
parser.delete_first_tok | en()
return CleverCSSNode(nodelist)
class CleverCSSNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
output = self.nodelist.render(context)
return clevercss.convert(output)
|
from django.contrib.auth.models import User
from rest_framework import serializers
from servicelevelinterface.models import Monitor, Contact, Command
class MonitorSerializer(serializers.ModelSerializer):
owner = serializers.CharField(source='owner.username', read_only=True)
class Meta:
mod | el = Monitor
class ContactSerializer(serializers.ModelSerializer):
owner = serializers.CharField(source='owner.username', read_only=True)
class Meta:
model = Contact
class CommandSerializer(serializers.ModelSerializer):
class Meta:
model = Command
# Serializer used just when creating u... | word', 'email')
|
import datetime
import logging
try:
import threading
except ImportError:
thr | eading = None
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from debug_toolbar.panels import DebugPanel
class ThreadTrackingHandler(logging.Handler):
def __init__(self):
if threading is None:
raise NotImplementedError("threading modu... | panel cannot be used without it")
logging.Handler.__init__(self)
self.records = {} # a dictionary that maps threads to log records
def emit(self, record):
self.get_records().append(record)
def get_records(self, thread=None):
"""
Returns a list of records for the provide... |
import globus_sdk
CLIENT_ID = 'f7cfb4d6-8f20-4983-a9c0-be3f0e2681fd'
client = globus_sdk.NativeAppAuthClient(CLIENT_ID)
#client.oauth2_start_flow(requested_scopes="https://auth.globus.org/scopes/0fb084ec-401d-41f4-990e-e236f325010a/deriva_all")
client.oauth2_start_flow(requested_scopes="https://auth.globus.org/scopes... | ut = getattr(__builtins__, 'raw_input', input)
auth_code = get_input(
'Please enter the code you get after login here: ').strip()
token_response = client.oauth2_exchange_code_for_tokens(auth_code)
print str(token_response)
nih_commons_data = token_response.by_resource_s | erver['nih_commons']
DERIVA_TOKEN = nih_commons_data['access_token']
print DERIVA_TOKEN
|
"""
Write an efficient algorithm that | searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first int | eger of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
"""
__author__ = 'Danyang'
class Solution:
def searchMatrix(self, matrix, target):
... |
from django.core.exceptions import MultipleObjectsReturned
from django.shortcuts import redirect
from django.urls import reverse, path
from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.api.v2.views import PagesAPIViewSet, BaseAPIViewSet
from wagtail.images.api.v2.views import ImagesAPIViewSet
from wagtai... | ssmethod
def get_urlpatterns(cls):
"""
This returns a list of URL patterns for the endpoint
"""
return [
path('', cls.as_view({'get': 'listing_view'}), name='listing'),
path('<int:pk>/', cls.as_view({'get': 'detail_view'}), name='detail'),
path('<s... | l'),
path('find/', cls.as_view({'get': 'find_view'}), name='find'),
]
class OpenStaxImagesAPIViewSet(ImagesAPIViewSet):
meta_fields = BaseAPIViewSet.meta_fields + ['tags', 'download_url', 'height', 'width']
nested_default_fields = BaseAPIViewSet.nested_default_fields + ['title', 'download_... |
# Copyright 2021 Akretion (http://www.akreti | on.com).
# License AGPL-3.0 or later (http://www.gnu.org/l | icenses/agpl).
{
"name": "No automatic deletion of SMS",
"summary": "Avoid automatic delete of sended sms",
"author": "Akretion,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/connector-telephony",
"license": "AGPL-3",
"category": "",
"version": "14.0.1.1.0",
"depen... |
##########################################################################
#
# Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | = "a compound parameter",
members = [
IECore.V3dParameter(
name = "j",
description = "a v3d",
defaultValue = IECore.V3dData(),
presets = (
( "one", imath.V3d( 1 ) ),
( "two", imath.V3d( 2 ) )
)
),
IECore.M44fParameter(
name = "k",
... | = (
( "one", imath.M44f( 1 ) ),
( "two", imath.M44f( 2 ) )
)
),
]
)
]
)
def doOperation( self, operands ) :
assert operands["h"] == IECore.V3fData( imath.V3f( 1, 0, 0 ) )
assert operands["i"] == IECore.V2dData( imath.V2d( 0 ) )
compoundPreset = IECore.CompoundObj... |
#
# Copyright 2018 Analytics Zoo 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 applicable law or agreed to... | TestCase
from zoo.chronos.detector.anomaly.ae_detector import AEDetector
class TestAEDetector(ZooTestCase):
def setup_method(self, method):
pass
def teardown_method(self, method):
pass
def create_data(self):
cycles = 10
time = np.arange(0, cycles * np.pi | , 0.01)
data = np.sin(time)
data[600:800] = 10
return data
def test_ae_fit_score_rolled_keras(self):
y = self.create_data()
ad = AEDetector(roll_len=314)
ad.fit(y)
anomaly_scores = ad.score()
assert len(anomaly_scores) == len(y)
anomaly_indexe... |
# -*- coding: utf-8 -*-
# Copyright 2007-2016 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | tiff, semper_unf, blockfile, dens, emd,
protochips)
io_plugins = [msa, digital_micrograph, fei, mrc, ripple, tiff, semper_unf,
blockfile, dens, emd, protochips]
_logger = logging.getLogger(__name__)
try:
from hyperspy.io_plugins import netcdf
i... | tcdf)
except ImportError:
pass
# NetCDF is obsolate and is only provided for users who have
# old EELSLab files. Therefore, we silenly ignore if missing.
try:
from hyperspy.io_plugins import hdf5
io_plugins.append(hdf5)
from hyperspy.io_plugins import emd
io_plugins.append(emd)
except Impor... |
._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_system_add_keyspace(self):
iprot = self._iprot
(fname, mtype, rseqid) = iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(iprot)
... | read(iprot)
iprot.readMessageEnd()
raise x
result = execute_cql_query_result()
result.read(iprot)
iprot.readMessageEnd()
if result.success is not None:
return result.success
if result.ire is not None:
raise result.ire
if res... | is not None:
raise result.ue
if result.te is not None:
raise result.te
if result.sde is not None:
raise result.sde
raise TApplicationException(TApplicationException.MISSING_RESULT, "execute_cql_query failed: unknown result")
def execute_cql3_query(self, q... |
"""
This DatabaseHandler is used when you do not have a database installed.
"""
import proof.ProofConstants as P | roofConstants
import proof.adapter.Adapter as Adapter
class NoneAdapter(Adapter.Adapter):
def __init__(self):
pass
def getResourceType(self):
return ProofConstants.NONE
def getConnection(self):
return None
def toUpperCase(self, s):
return s
| def ignoreCase(self, s):
return self.toUpperCase(s)
def getIDMethodSQL(self, obj):
return None
def lockTable(self, con, table):
pass
def unlockTable(self, con, table):
pass
|
#!/usr/bi | n/env python
# -*- coding: utf-8 -*-
"""Contains Custom Exception Class"""
class CustomError(Exception):
"""
Attributes:
None
"""
def __init__(self, message, cause):
"""Custom Error that stores error reason.
Args:
cause (str): Reason for error.
message ... | >>> print myerr.cause
Messed up!
"""
self.cause = cause
self.message = message
Exception.__init__(self)
|
""" | The pioneer component."" | "
|
#!/usr/bin/python
"""
m5subband.py ver. 1.1 Jan Wagner 20150603
Extracts a narrow subband via filtering raw VLBI data.
Reads formats supported by the mark5access library.
Usage : m5subband.py <infile> <dataformat> <outfile>
<if_nr> <factor> <Ldft>
<start_bin> <stop_bi... | rning: output rate is non-integer (%e Ms/s)! ***' % (outMbps))
(vdifref,vdifsec) = m5lib.helpers.get_VDIF_time_from_MJD(mj | d,sec+1e-9*ns)
vdif = m5lib.writers.VDIFEncapsulator()
vdif.open(fout, format=vdiffmt, complex=False, station='SB')
vdif.set_time(vdifref,vdifsec, framenr=0)
vdiffmt = vdif.get_format()
# Report
bw = float(dms.samprate)*0.5
print ('Input file : start MJD %u/%.6f sec' % (mjd,sec+ns*1e-9))
print ('Bandwidth ... |
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to cr... | n called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_bidding... | "get_bidding_seasonality_adjustment"
] = self.grpc_channel.unary_unary(
"/google.ads.googleads.v9.services.BiddingSeasonalityAdjustmentService/GetBiddingSeasonalityAdjustment",
request_serializer=bidding_seasonality_adjustment_service.GetBiddingSeasonalityAdjustme... |
#coding: utf-8
from scapy.all import *
class WILDCARD:
""" Used to indicate that some fields in a scapy packet should be ignored when comparing """
pass
class NO_PKT:
""" Indicate that a sent packet should have no reply """
pass
def pkt_match(expected, actual):
""" Check if all fields described i... | h_object.encode('hex')))
else:
tlvs.append('{{Type:{} Value:{}}}'.format(tlv.type, tlv.value.encode('hex')))
return "[{}] <{}>{}".for | mat(",".join(segs), ",".join(map(lambda key: "{} {}".format(key, options[key]),options)), "" if not tlvs else " "+" ".join(tlvs))
def ip_str(ip):
return "{} -> {}".format(_(ip.src), _(ip.dst))
def udp_str(udp):
if udp.sport or udp.dport:
return "UDP({},{})".format(_(udp.sport), _(... |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU G | eneral Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'ismail@kartoza.com'
__revision__ = '$Format:%H$'
__date__ = '08/12/15'
__copyright__ = ('Copyright 2012, Australia Indonesia F | acility for '
'Disaster Reduction')
import json
from types import NoneType
from safe.common.exceptions import MetadataCastError
from safe.metadata.property import BaseProperty
class BooleanProperty(BaseProperty):
"""A property that accepts boolean."""
# if you edit this you need to adap... |
sting model variable with these parameters or creates a new one.
Args:
name: the name of the new or existing variable.
shape: shape of the new or existing variable.
dtype: type of the new or existing variable (defaults to `DT_FLOAT`).
initializer: initializer for the variable if one is created.
r... | tional scope for filtering the variables to return.
R | eturns:
a copied list of variables with the given name and prefix.
"""
return get_variables(scope=scope, suffix=suffix)
def get_variables_by_name(given_name, scope=None):
"""Gets the list of variables that were given that name.
Args:
given_name: name given to the variable without any scope.
scope... |
#!/usr/bin/python2
# -- coding: utf-8 --
# Converts a .qm file to a .ts file.
# More info: http://www.mobileread.com/forums/showthread.php?t=261771
# By pipcat & surquizu. Thanks to: tshering, axaRu, davidfor, mobileread.com
import codecs, cgi
def clean_text(txt, is_utf) :
if is_utf == False:
txt = txt.decode('u... | # save xml
if last_t3 != t3:
if last_t3 != '':
f.write('</context>\n')
f.write('<context>\n')
f.write('\t<name>'+t3+'</name>\n')
last_t3 = t3
f.write('\t<message>\n') if t1b == '' else f.write('\t<message numerus="yes">\n')
f. | write('\t\t<source>'+clean_text(t2, True)+'</source>\n')
if t1b == '':
f.write('\t\t<translation>'+clean_text(t1, False)+'</translation>\n')
else:
f.write('\t\t<translation>\n')
f.write('\t\t\t<numerusform>'+clean_text(t1, False)+'</numerusform>\n')
f.write('\t\t\t<numerusform>'+clean_... |
env = {}
self._entities = []
self.name = name
self.env = env
self.graph = None
def process(self, channels=('root',), ignore_outlet_node=False, output_channels=()):
"""(Pipeline, pandas.DataFrame, str) -> type(df_map)
*Description*
:param ignore_ou... | et_start_node(self, channel):
self._check_graph()
nodes = filter(lambda x: channel in x.output_channels and x.type == 'source', self.graph.nodes())
if len(nodes) > 0:
return nodes[0]
raise Exception('You can\'t use channel without source node')
def _process_entity(self, ... | p)) -> type(cls)
*Description*
"""
obj = cls(*construct_arguments)
obj.env = self.env
if priority:
obj.priority = priority
obj.register(self)
self._entities.append(obj)
if channel is None and len(obj.input_channels) == 0 and len(obj.output_chan... |
#-*- encoding: utf-8 -*-
"""
Right triangles with integer coordinates
The points P | (x1, y1) and Q (x2, y2) are plotted at integer co-ordinates and are joined to the origin, O(0,0), to form ΔOPQ.
There are exactly fourteen triangl | es containing a right angle that can be formed when each co-ordinate lies between 0 and 2 inclusive; that is,0 ≤ x1, y1, x2, y2 ≤ 2.
Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed?
"""
from utils import *
#
|
# Copyright (C)2016 D. Plaindoux.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2, or (at your option) any
# later version.
import unittest
from fluent_rest.spec.rest ... | f):
@PUT
def test():
pass
self.assertTrue(specification(test).hasGivenVerb(u'PUT'))
def test_should_have_POST(self):
@POST
def test():
pass
self.assertTrue(specification(test).hasGivenVerb(u'POST'))
def test_should_h | ave_DELETE(self):
@DELETE
def test():
pass
self.assertTrue(specification(test).hasGivenVerb(u'DELETE'))
def test_should_have_a_Verb(self):
@Verb(u'UPLOAD')
def test():
pass
self.assertTrue(specification(test).hasGivenVerb(u'UPLOAD'))
de... |
END)
if entry.end_comment and BLOCK_COMMENTS in self.elements:
self._write_block_comments(entry.end_comment, 'E', address)
self._write_blocks(entry.footer, address, True)
def write_body(self, entry):
if entry.ctl in 'gu':
entry_ctl = 'b'
else:
e... | i += 1
return sub_blocks
def write_sub_block(self, ctl, entry_ctl, comment, instructions, lengths):
length = 0
sublengths = []
address = instructions[0].address
if ctl == 'C':
# Compute the sublengths for a 'C' sub-block
for i, instruction in enu... | if i < len(instructions) - 1:
sublength = instructions[i + 1].address - addr
else:
sublength = self.assembler.get_size(instruction.operation, addr)
if sublength > 0:
length += sublength
bases = instruction.l... |
from django.db.models import Count
from django.conf import settings
from solo.models import SingletonModel
import loader
MAX_REVIEWERS = settings.MAX_REVIEWERS
# Simple algorithm that checks to see the number of years the studies span and
# returns one study per year
def one_per_year(candidate_studies, user, annotatio... | so use that one
# If not check to see if there is a global list object setup, if so use that one
# Otherwise just pull from the candidate_studies
def lists(candidate_studies, user, annotation_class = None):
from models import Config
study_list = (hasattr(user, 'study_list') and user.study_list) or Config.get_... | ist:
return candidate_studies
studies = study_list.studies.exclude(radiologystudyreview__user_id = user.id)
return studies
#TODO Cross Validate Algorithm that chooses studies and puts them on other users lists.
registry = loader.Registry(default=one_per_year, default_name = "one per year")
registry.r... |
##############################################################################
# Copyright (c) 2017, Los Alamos National Security, LLC
# Produced at the Los Alamos National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, ... | will be useful, but
# WITHOUT ANY WARRANTY; with | out even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# F... |
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth i... | ogle.com/dir/')
u'dir'
>>> _name_from_url('http://google.com/dir')
u'dir'
>>> _name_from_url('http://goo | gle.com/dir/..')
u'dir'
>>> _name_from_url('http://google.com/dir/../')
u'dir'
>>> _name_from_url('http://google.com')
u'google.com'
>>> _name_from_url('http://google.com/dir/subdir/file..ext')
u'file.ext'
"""
from urlparse import urlparse
p = urlparse(url)
for base in (p.pa... |
import pygame
import sys
import os
class Env:
def __init__(self, teamA, teamB, field_si | ze, display, robots=None,
debug=False):
self.teamA = teamA
self.teamB = teamB
self.width = field_size[0]
self.heig | ht = field_size[1]
self.display = display
self.ball = None
self.robots = robots
self.robots_out = {'A': [False, False], 'B': [False, False]}
self.debug = debug
self.dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
self.field = pygame.image.load(self... |
import StringIO
class Plugin(object):
ANGULAR_MODULE = None
JS_FILES = []
CSS_FILES = []
@classmethod
def PlugIntoApp(cls, app):
pass
@classmethod
def GenerateHTML(cls, root_url="/"):
out = StringIO.StringIO()
for js_file in cls.JS_FILES:
js_file = js... | tylesheet" href="%s%s"></link>\n' % (
root_url, css_file))
if cls.ANGULAR_MODULE:
out.write("""
<script>var manuskriptPluginsList = manuskriptPluginsList || [];\n
manuskriptPluginsList.push("%s");</script>\n""" % cls.ANGULAR_MODULE)
return o | ut.getvalue()
|
uration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
from recommonmark.parser import CommonMarkParser
# If extensions (or modules to document with autodoc) are in another directory,
# add t... | = [
('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation',
u'Read the Docs', 'ReadtheDocsTemplate', '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_domai... | @detailmenu in the "Top" node's menu.
#texinfo_n |
import pytest
import os
@pytest.fixture(autouse=True)
def change_tempory_directory(tmpdir):
tmpd | ir.chdir()
yield
i | f os.path.exists("tarnow.tmp"):
os.remove("tarnow.tmp")
@pytest.fixture(autouse=True)
def patch_subprocess(mocker):
mocker.patch("subprocess.call")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.