prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import datetime
import csv
with open('SYSTEMS.csv') as f:
reader = csv.reader(f)
ALLOWED_SYSTEMS = [l[0] for l in reader]
class IntelEntry:
KEYS = ["timer_name", "alliance", "system", "time", "date", "location"]
def __init__(self, timer_name="", alliance="", system="", time="", date="", location=""... | trptime(' '.join([date, time]), '%m/%d/%y %H:%M')
if self.time < datetime.date | time.now():
raise ValueError("Provided date/time not valid. Time must be in the future.")
else:
raise ValueError("Provided date/time not valid. Time must be in format '%m/%d/%y %H:%M'.")
def to_dict(self):
return { "timer_name": self.timer_name,
"allianc... |
e = sz
sz = self.get_young_var_basesize(self.min_nursery_size)
self.lb_young_var_basesize = sz
def setup(self):
self.old_objects_pointing_to_young = self.AddressStack()
# ^^^ a list of addresses inside the old objects space; it
# may contain static prebuilt objects as well. ... | simple" case or object too big: don't use the nursery
return SemiSpaceGC.malloc_fixedsize_clear(self, typeid, size,
| has_finalizer,
is_finalizer_light,
contains_weakptr)
size_gc_header = self.gcheaderbuilder.size_gc_header
totalsize = size_gc_header + size
result = self.nursery_free
... |
"""Support for the Roku remote."""
import requests.exceptions
from homeassistant.components import remote
from homeassistant.const import CONF_HOST
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Roku remote platform."""
if not discovery_info:
retu... | id(self):
"""Return a unique ID."""
return self._device_info.serial_num
@property
def is_on | (self):
"""Return true if device is on."""
return True
@property
def should_poll(self):
"""No polling needed for Roku."""
return False
def send_command(self, command, **kwargs):
"""Send a command to one device."""
for single_command in command:
i... |
# # # WARNING # # #
# This list must also be updated in doc/_templates/autosummary/class.rst if it
# is changed here!
_doc_special_members = ('__contains__', '__getitem__', '__iter__', '__len__',
'__add__', '__sub__', '__mul__', '__div__',
'__neg__', '__hash__')
from ._b... | _snr, assert_stcs_equal, modified_env,
| _click_ch_name)
from .numerics import (hashfunc, _compute_row_norms,
_reg_pinv, random_permutation, _reject_data_segments,
compute_corr, _get_inst_data, array_split_idx,
sum_squared, split_list, _gen_events, create_slices,
... |
': 'A new password, when changing the current one.',
},
'code': {
'location': 'json',
'help': 'A temporary code used to reset the password.',
},
'email': {
'location': 'json',
'help': 'The email.',
},
'description': {
'location': 'json',
'help': 'T... | api.abort_with_msg(404, 'User not found', ['username'])
resp = {
'username': user.username,
'description': user.description,
}
# Add ema | il if this is the owner of the account
token = args['token']
if token:
decoded = decode_token(token)
if decoded['username'] == username:
resp['email'] = user.email
return resp
@api.doc(parser=api.create_parser('token', 'description',
... |
"""
Author: Junhong Chen
"""
from Bio import SeqIO
import gzip
import sys
import os
pe1 = []
pe2 = []
pname = []
for dirName, subdirList, fileList in os.walk(sys.argv[1]):
for fname in fileList:
tmp = fname.split(".")[0]
tmp = tmp[:len(tmp)-1]
if tmp not in pname:
pname... | e, 'w') as w_file:
for filen in file_list:
print 'working with',filen
with gzip.open(filen, 'rU') as o_file:
seq_records = SeqIO.parse(o_file, | 'fastq')
SeqIO.write(seq_records, w_file, 'fastq')
#print pe1
#print pe2
concat(sys.argv[2]+"-pe1.fq", pe1)
concat(sys.argv[2]+"-pe2.fq", pe2)
|
zes from settings or fallback to the module constants
"""
page_size = AGNOCOMPLETE_DEFAULT_PAGESIZE
settings_page_size = getattr(
settings, 'AGNOCOMPLETE_DEFAULT_PAGESIZE', None)
page_size = settings_page_size or page_size
page_size_min = AGNOCOMPLETE_MIN_PAGESIZE
settings_page_size_min... | f):
"""
Return the computed page_size
It takes into account:
* class variables
* constructor arguments,
* settings
* fallback to the module constants if needed.
"""
return self._page_size
def get_query_size(self):
"""
| Return the computed default query size
It takes into account:
* class variables
* settings,
* fallback to the module constants
"""
return self._query_size
def get_query_size_min(self):
"""
Return the computed minimum query size
It takes i... |
def revertdigits( item ):
| return (item%10)*100 + (int(item/10)%10)*10 + int(item/1 | 00)
numlist = [314, 315, 642, 246, 129, 999]
numlist.sort( key=revertdigits )
print( numlist ) |
#!/usr/bin/python3
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... | print (origin, sizeOrig, spacingOrig)
# TODO: Don't cut away data at the end
# size = ((int(sizeOrig[0]) + factor - 1) // factor,
# (int(sizeOrig[1]) + factor - 1) // factor,
# (int(sizeOrig[2]) + factor - 1) // factor)
size = (int(sizeOrig[0]) // factor,
int(sizeOrig[1]... | ]) // factor)
spacing = spacingOrig * factor
with inputData.GetBufferReadonly() as bufferOld:
arrayOld = bufferOld.array
arrayOld2 = arrayOld[:size[0] * factor,
:size[1] * factor, :size[2] * factor]
arrayOld3 = arrayOld2.view()
arrayOld3.shape = si... |
'''
Created on Jun 6, 2014
@author: rtermondt
'''
from django.conf import settings
def global_settings(request):
invitation_system_setting = getattr(settings, 'INVITATION_SYSTEM', None)
if invitation_system_setting == True:
invite_system = True
else:
invite_system = False
| return {
'INVITATION_SYSTEM': invite_system
}
| |
'''Michael Lange <klappnase (at) freakmail (dot) de>
The ToolTip class provides a flexible tooltip widget for Tkinter; it is based on IDLE's ToolTip
module which unfortunately seems to be broken (at least the version I saw).
INITIALIZATION OPTIONS:
anchor : where the text should be positioned inside the widg... | m") == 'aqua':
tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "none")
self.create_contents()
tw.update_idletasks()
x, y = self.coords()
tw.wm_geometry("+%d+%d" % (x, y))
tw.deiconify()
def _hide(self)... | thods might be overridden in derived classes:----------------------------------##
def coords(self):
# The tip window must be completely outside the master widget;
# otherwise when the mouse enters the tip window we get
# a leave event and it disappears, and then we get an enter
... |
#!/usr/bin/env python
# angelus.py - John Burnett & Will Johnson (c)2015
#
# Angelus does the following:
# -FFT analysis
# -Partial tracking
# -Modal analysis
# -Resynthesis
#
# Angelus will eventually do the following:
# -FFT Analysis -> Notation
# -Modal Analysis -> 3D mesh (and reverse?)
from FFT_Analyzer import ... | fname = sys.argv[1]
title = parse_fname(fname)
infile = "../audio/" + fname
| outfile = "../build/" + title + ".ro"
analysis = FFT_Analyzer(infile)
analysis.perform_analysis()
analysis.stft(20)
analysis.get_modal_data(30)
out = writeRObU(outfile, analysis.modal_model)
out.write()
synth = Synthesizer(analysis, title)
synth.write_wav()
#synth.write_residual(... |
# -*- cod | ing: utf-8 -*-
im | port common_sale_contract
import test_sale_contract
|
import unittest
from streamlink.strea | m import StreamIOIterWrapper
class TestPluginStream(unittest.TestCase):
def test_iter(self):
def generator():
yield b"1" * 8192
yield b"2" * 4096
yield b"3" * 2048
fd = StreamIOIterWrapper(generator())
self.assertEqual(fd.read(4096), b"1" * 4096)
... | , b"1" * 2048)
self.assertEqual(fd.read(1), b"2")
self.assertEqual(fd.read(4095), b"2" * 4095)
self.assertEqual(fd.read(1536), b"3" * 1536)
self.assertEqual(fd.read(), b"3" * 512)
|
from django.conf import settings
from django.conf.urls.defaults import *
from models import *
from django.views.generic import date_based, list_detail
from django.contrib.auth.decorators import login_required
# Number of random images from the gallery to display.
SAMPLE_SIZE = ":%s" % getattr(settings, 'GALLERY_SAMPLE... | lery-archive-day'),
url(r'^gallery/(?P<year>\d{4})/(?P<month>[a-z]{3})/$', login_required(date_based.archive_month), gallery_args, name='pl-gallery-archive-month'),
url(r'^gallery/(?P<year>\d{4})/$', login_required(date_based.archive_year), gallery_args, name='pl-gallery-archive-year'),
url(r'^gallery/?$', ... | gallery_args, name='pl-gallery-archive'),
)
urlpatterns += patterns('django.views.generic.list_detail',
url(r'^gallery/(?P<slug>[\-\d\w]+)/$', login_required(list_detail.object_detail), {'slug_field': 'title_slug', 'queryset': Gallery.objects.filter(is_public=True), 'extra_context':{'sample_size':SAMPLE_SIZE}}, na... |
#!/usr/bin/python -*- coding:utf-8 -*-
__Author__ = "Riyaz Ahmad Bhat"
__Email__ = "riyaz.ah.bhat@gmail.com"
import re
from collections import namedtuple
from sanity_checker import SanityChecker
class DefaultList(list):
"""Equivalent of Default dictionaries for Indexing Errors."""
def __init__(self, defaul... | ),cat_,gen_,num_,per_,case_,vib_,tam_.strip("'")
def updateFSValues (self, attributeValue_pairs):
attributes = dict(zip(['head_','poslcat_','af_','vpos_','name_','drel_','parent_','mtype_','troot_','chunkId_',\
'coref_','stype_','voicetype_','posn_'], [None] * 14))
attributes.update(dict(zip(['lemma | _','cat_','gen_','num_','per_','case_','vib_','tam_'], [''] * 8)))
for key,value in attributeValue_pairs.items():
if key == "af":
attributes['lemma_'],attributes['cat_'],attributes['gen_'],attributes['num_'],\
attributes['per_'],attributes['case_'],attributes['vib_'],attributes['tam_'] = \
self.morph... |
i | mport nspkg1.foo
| |
'''
Tree from:
http://www.quesucede.com/page/show/id/python-3-tree-implementation
'''
from urllib.parse import urlparse
import os
(_ROOT, _DEPTH, _BREADTH) = range(3)
class Node:
def __init__(self, identifier):
self.__id | entifier = identifier
self.__children = []
@property
def identifier(self):
return self.__identifier
@property
def children(self):
return self.__children
def add_child(self, identifier):
self.__children.append(identifier)
class Tree:
def __init__(self):
... | def add_node(self, identifier, parent=None):
print("identifier: " + identifier + " parent= " + str(parent))
node = Node(identifier)
self[identifier] = node
if parent is not None:
self[parent].add_child(identifier)
return node
def display(self, identifier, dep... |
#!/usr/bin/python
import sys, commands, struct, operator, subprocess, os
if len(sys.argv) != 3:
print 'usage:',sys.argv[0],'<program> <core>'
sys.exit(1)
prog, core = sys.argv[1:]
# finds out the size of void*/size_t. could be hardcoded for speed...
try:
cell = int(commands.getoutput('gdb '+prog+r''' -ex 'prin... | tack in reversed(total):
print '%d%% %d %s'%(int(100.*size/heapsize), size, stack2sizes[stack])
for addr in stack:
if addr:
print ' 0x%x'%addr, syminfo[addr]
blocks = find_blocks(open(core,'rb').read | ())
if not blocks:
print 'no heap blocks found in the core dump (searched for metadata enclosed in the magic string HeaP...ProF)'
sys.exit(1)
syminfo = sym_info(code_addrs(blocks), prog)
report(blocks, syminfo)
|
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5 import uic
from . import guiStart
from . import guiCompileSuccess
# sys.path.insert(1, 'C:/Users/GuSan/Desktop/powerOverWhelming/project/src/comp_exec')
from ..comp_exec import validation
from . import guiErrorCode
class GuiSelectCode(QtWidgets.QMainWi... | eturn_search.setText(_translate("SelectCode", "Return to Search"))
def __init__(self):
QtWidgets.QMainWind | ow.__init__(self)
self.setupUi(self)
self.initUi()
def initUi(self) :
self.btn_compile_start.clicked.connect(self.compile_click)
self.opt_select_code_1.setChecked(True)
self.btn_return_search.clicked.connect(self.return_search)
#window_start = guiStart.GuiStart(s... |
nguage.getLanguage()[:2] # getLanguage returns e.g. "fi_FI" for "language_country"
PackageInfoHandler.__init__(self, self.statusCallback, blocking = False, neededTag = 'ALL_TAGS', neededFlag = self.ImageVersion)
self.directory = resolveFilename(SCOPE_METADIR)
self.hardware_info = HardwareInfo()
self.list = List... | sole.appContainers) == 0:
if callback is not None:
callback(True)
callback = None
elif self.NotifierCallback is not None:
self.NotifierCallback(True)
self.NotifierCallback = None
def startIpkgUpdate(self, callback = None):
if not self.Console:
| self.Console = Console()
cmd = self.ipkg.ipkg + " update"
self.Console.ePopen(cmd, self.IpkgUpdateCB, callback)
def IpkgUpdateCB(self, result, retval, extra_args = None):
(callback) = extra_args or None
if result:
if self.Console:
if len(self.Console.appContainers) == 0:
if callback is not None... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
import os
import sys
from optparse import OptionParser, BadOptionError
from celery import __version__
from celery.platforms im | port EX_FAILURE, detached
from celery.utils.log import get_logger
from celery.bin.base import daemon_options, Option
logger = get_logger(__name__)
OPTION_LIST = daemon_options(default_pidfile="celeryd.pid") + (
Option("--fake",
default=False, action="store_true", dest="fake",
... | _directory=None, fake=False, ):
with detached(logfile, pidfile, uid, gid, umask, working_directory, fake):
try:
os.execv(path, [path] + argv)
except Exception:
from celery import current_app
current_app.log.setup_logging_subsystem("ERROR", logfile)
log... |
# Copyright (c) 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You 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 wri... | 'Flavors', metadata,
sa.Column('name', sa.String(64), primary_key=True),
sa.Column('project', sa.String(64)),
sa.Column('capabilities', sa.Text()))
Catalogue = sa.Table( | 'Catalogue', metadata,
sa.Column('pool', sa.String(64),
sa.ForeignKey('Pools.name',
ondelete='CASCADE')),
sa.Column('project', sa.String(64)),
sa.Column('queue', sa.String(64), null... |
rom constants import *
from helpers import OrderedAttrDict, utc
"""
The AS types and their FLV representations.
"""
log = logging.getLogger('flvlib.astypes')
class MalformedFLV(Exception):
pass
# Number
def get_number(f, max_offset=None):
return get_double(f)
def make_number(num):
return make_double... | e):
# We need a blob, not unicode. Arbitrarily choose UTF-8
string = string.encode('UTF-8')
length = make_ui32(len(string))
return length + string
# ECMA Array
class ECMAArray(OrderedAttrDict):
pass
def get_ecma_array(f, max_offset=None):
length = get_ui32(f)
log.debug( | "The ECMA array has approximately %d elements", length)
array = ECMAArray()
while True:
if max_offset and (f.tell() == max_offset):
log.debug("Prematurely terminating reading an ECMA array")
break
marker = get_ui24(f)
if marker == 9:
log.debug("Marker!... |
ep_GS: str
irrep_ES: str
irrep_trans: str
edtm_length: np.ndarray
f_length: float
edtm_velocity: np.ndarray
f_velocity: float
mdtm: np.ndarray
R_length: float
R_velocity: float
spin_mult: str
R_eigvec: Union[core.Matrix, List[core.Matrix]]
L_eigvec: Union[core.Matrix, Lis... | state_sym]
| # length-gauge electric dipole transition moment
edtm_length = engine.residue(R, mints.so_dipole())
# length-gauge oscillator strength
f_length = ((2 * e) / 3) * np.sum(edtm_length**2)
# velocity-gauge electric dipole transition moment
edtm_velocity = engine... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is a doctest example with Numpy arrays.
For more information about doctest, see
https://docs.python.org/3/library/doctest.html (reference)
and
www.fil.univ-lille1.fr/~L1S2API/CoursTP/tp_doctest.html (nice examples in
French).
To run doctest, execute this script... | parameter.
Examples
--------
>>> a = numpy.array([1., | 2., numpy.nan])
>>> a
array([ 1., 2., nan])
>>> example4(a)
array([False, False, True], dtype=bool)
Be careful with white space! The following will work...
>>> a
array([ 1., 2., 0.])
but this one would't
# >>> a
# array([ 1., 2., 0.])
As an alternative, the `doctes... |
import unittest
import time
from datetime import datetime
from app import create_app, db
from app.models import User, AnonymousUser, Role, Permission
class UserModelTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self... | ample.net')
| self.assertFalse(u2.change_email(token))
self.assertTrue(u2.email == 'susan@example.org')
def test_duplicate_email_change_token(self):
u1 = User(email='john@example.com', password='cat')
u2 = User(email='susan@example.org', password='dog')
db.session.add(u1)
db.session.ad... |
import numpy as np
import torch
from PIL import Image
from argparse import ArgumentParser
from torch.optim import SGD, Adam
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, CenterCrop, Normalize
from torchvision.transforms import ToTensor, ToPILIm... | == 'segnet':
Net = SegNet
assert Net is not None, f'model {args.model} not available'
model = Net(NUM_CLASSES)
if args.cuda:
model = model.cuda()
if args.state:
try:
model.load_state_dict(torch.load(args.state))
except AssertionError:
model.load... | rgs.mode == 'train':
train(args, model)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--cuda', action='store_true')
parser.add_argument('--model', required=True)
parser.add_argument('--state')
subparsers = parser.add_subparsers(dest='mode')
subparsers.requir... |
# read_hadamard_file.py
# Reads data from a text file to create a 3D
# version of a given Hadamard Matrix.
# Created by Rick Henderson
# Created on June 4, 2015
# Completed June 5, 2015
# Note: A "Hadamard File" is a text file containing rows
# rows of + and - where the + indicates a 1 or a cube
# and th... |
# Now an entire row has been read, so reset char_number to 0
| char_number = 0
# Program Ends
|
from numpy.distutils.core import setup, Extension
#f | rom setuptools import setup, Extension
setup(
name = "Infer", version = "1.0",
description='Python version of MCMC, plus other inference codes under development',
author='Neale Gibson',
author_email='ngibs | on@eso.org',
packages=['Infer'],
package_dir={'Infer':'src'},
#and extension package for solving toeplitz matrices...
ext_modules = [
Extension("Infer.LevinsonTrenchZoharSolve",sources=["src/LevinsonTrenchZoharSolve.c"],),
]
)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @ | author: Emanuel Cino < | ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from . import communication_config
from . import communication_job
from . import communication_attachment
from . import res_partner
from . import email
from . import c... |
# -*- coding: utf-8 -*-
###############################################################################
#
# ListPlaylistsByID
# Returns a collection of playlists that match the provided IDs.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Licen... | super(ListPlaylistsByIDInputSet, self)._set_input('AccessToken', value)
def set_ClientID(self, value):
"""
Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Google. Required for OAuth authentication unless providing a valid AccessToken.)
... | is Choreo. ((conditional, string) The Client Secret provided by Google. Required for OAuth authentication unless providing a valid AccessToken.)
"""
super(ListPlaylistsByIDInputSet, self)._set_input('ClientSecret', value)
def set_Fields(self, value):
"""
Set the value of the Fields i... |
#!/usr/bin/env python
# "manhole" entry point, friendlier ipython startup to remote container
__author__ = 'Dave Foster <dfoster@asascience.com>'
def main():
import sys, os, re, errno, json, socket
from pkg_resources import load_entry_point
r = re.compile('manhole-(\d+).json')
if len(sys.argv) == 2... | False if is a likely container.
"""
mh_pid = int(r.search(f).group(1))
try:
| os.getpgid(mh_pid)
except OSError as e:
if e.errno == errno.ESRCH:
return False
raise # unexpected, just re-raise
# the pid seems legal, now check status of sockets - the pid may be reused
... |
Time()
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, 'Invalid')
def testFormatDateTimeWithoutDynamicTime(self):
"""Tests the _FormatDateTime function without dynamic time."""
output_mediator = self._CreateOutputMediat... | per = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(se | lf._TEST_EVENTS[0]))
filename_string = test_helper._FormatFilename(
event, event_data, event_data_stream)
self.assertEqual(filename_string, 'log/syslog.1')
def testFormatHostname(self):
"""Tests the _FormatHostname function."""
output_mediator = self._CreateOutputMediator()
test_helper = ... |
# 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 th... | KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.hypervisors.compute import views
urlpatterns = [
url(r'^(?P<compute_host>[^/]+)/evacuate_host$',
... | name='disable_service'),
url(r'^(?P<compute_host>[^/]+)/migrate_host$',
views.MigrateHostView.as_view(),
name='migrate_host'),
]
|
# -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | #
# 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 Publ... | eived a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
import res_partner
import oehealth_annotation
import oehealth_professional_category
import oeheal... |
tory.')
transform_parser.add_argument('--output', required=True,
help='path of output directory.')
transform_parser.add_argument(
'--prefix', required=True, metavar='NAME',
help='The prefix of the output file name. The output files will be like '
'NAME_00000_of... | omma seperated headers of the prediction data. ' +
'Order must match the training order.')
predict_parser.add_argument('--image_columns',
help='Online models only. ' +
'Comma seperated headers of image URL columns. ' +... | alse,
help='If not set, add a column of images in output.')
predict_parser.add_argument('--cloud', action='store_true', default=False,
help='whether to run prediction in cloud or local.')
predict_parser.add_cell_argument(
'prediction_data',
req... |
from flask_admin import expose
from listenbrainz.webserver.a | dmin import AdminIndexView
class HomeView(AdminIndexView):
@expose('/')
def index(self):
return self.render('ad | min/home.html')
|
"""
A p | ythonic interface to the Zabbix API.
"""
from .api import Api, ApiException
from .objects.host import Host
from .objects.hostgroup import HostGroup
from .objects.item import Item
from .objects.trigger import Trigger
from .objects.itservice import ItServi | ce
|
from decimal import Decimal
class Integer:
def __init__(self, val=None):
self | .val = int(val)
def __repr__(self):
return self.val
class Text:
def __init__(self, val=None):
self.val = str(val)
def __repr__ | (self):
return self.val
class Bool:
def __init__(self, val=None):
self.val = bool(val)
def __repr__(self):
return self.val
class Real:
def __init__(self, val=None):
self.val = Decimal(val)
def __repr__(self):
return self.val
class Date:
pass
|
import codecs
import pathlib
import re
import sys
from distutils.command.build_ext import build_ext
from distutils.errors import (CCompilerError, DistutilsExecError,
DistutilsPlatformError)
from setuptools import Extension, setup
if sys.version_info < (3, 5, 3):
raise RuntimeError("... |
description='Async http client/server framework (asyncio)',
long_description='\n\n'.join((read('README.rst'), read('CHANGES.rst'))),
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Prog... | :: 3.7',
'Development Status :: 5 - Production/Stable',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Topic :: Internet :: WWW/HTTP',
'Framework :: AsyncIO',
],
author='Nikolay Kim',
author_e... |
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from edc_registration.models import RegisteredSubject
from .base_maternal_clinical_measurements import BaseMaternalClinicalMeasurements
class MaternalClinicalMeasurementsOne(BaseMaternalClinicalMeasurements):
h... | verbose_name="Mother's height? ",
validators=[MinValueValidator(134), MaxValueValidator(195), ],
help_text="Measured in Centimeters (cm)")
class Meta:
app_label = 'td_maternal'
verbose_name = 'Maternal Clinical Measurements One'
verbose_name_plural = 'Maternal Clinica... | |
#!/usr/bin/env python3
import os
import sys
thispath = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper"))
from MiscFxns import *
from StandardModules import *
import pulsar_psi4
def ApplyBasis(syst,bsname,bslabel="primary"):
return psr.system.apply_si... | 817912 0.4267562
O -0.2432343 -1.0198566 -1.1953808
H 0.4367536 -0.3759433 -0.9973297
H -0.5031835 -0.8251492 -2.0957959
""")
mol = ApplyBasis(mol,"sto-3g","sto-3g")
| wfn=psr.datastore.Wavefunction()
wfn.system=mol
MyMod=mm.get_module("PSR_CP",0)
NewWfn,Egy=MyMod.deriv(0,wfn)
tester.test("Testing CP Energy via Deriv(0)", True, CompareEgy, Egy[0])
NewWfn,Egy=MyMod.energy(wfn)
tester.test("Testing CP Energy via Energy()", True, Com... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ver... | ense 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.
import Axon
from Kamaelia.Chassis.ConnectedServ | er import ServerCore
class RequestResponseComponent(Axon.Component.component):
def main(self):
while not self.dataReady("control"):
for msg in self.Inbox("inbox"):
self.send(msg, "outbox")
self.pause()
yield 1
self.send(self.recv("control"), "sign... |
from models.sampler import DynamicBlockGibbsSampler
from models.distribution import DynamicBernoulli
from models.optimizer import DynamicSGD
from utils.utils import prepare_frames
from scipy import io as matio
from data.gwtaylor.path import *
import ipdb
import numpy as np
SIZE_BATCH = 10
EPOCHS = 100
SIZE_HIDDEN = 50... | en_k_states, visible_k_probs, visible_k_states, data[:, :, 1:])
# update model values
bernoulli.weights += d_weight_update
bernoulli.bias_hidden += d_bias_hidden_update
bernoulli.bias_visible += d_bias_visible_update
bernoulli.vis_vis_weights += d_vis_vis
bernoulli.vis_h... | _, _, \
_, visible_k_states = gibbs_sampler.sample(data[:, :, 0], data[:, :, 1:])
error += np.mean(np.abs(visible_k_states - data[:, :, 0]))
error = 1./len(batch_idx_list) * error;
print error
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEA | SE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/deed/event_perk/shared_lambda_shuttle_static_deed.iff"
result.attribute_template_id = 2
result.stfName("event_perk","lambda_shuttle_static_deed_name")
#### BEGI... | DIFICATIONS ####
return result |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from unittest import mock
from configman.dotdict import DotDict
from socorro.lib.task_manager import TaskManager, defa... | _sleep(self, | seconds, wait_log_interval=0, wait_reason=""):
try:
if self.count >= 2:
raise KeyboardInterrupt
self.count += 1
except AttributeError:
self.count = 0
tm = MyTaskManager(config, task_func=mock.Mo... |
'pmap_index', 0)
self.fmap_index = self._get_metadata('fmap_index', 0)
self.lmap_index = self._get_metadata('lmap_index', 0)
self.omap_index = self._get_metadata('omap_index', 0)
self.rmap_index = self._get_metadata('rmap_index', 0)
self.nmap_index = self._get_metadata('nmap_inde... | name = name_file.readline().strip()
except (OSError, IOError) as msg:
LOG.error(str(msg))
return name
def version_supported(self):
| """Return True when the file has a supported version."""
return True
def _get_table_func(self, table=None, func=None):
"""
Private implementation of get_table_func.
"""
if table is None:
return list(self.__tables.keys())
elif func is None:
re... |
from djblets.cache.backend import cache_memoize
class BugTracker(object):
"""An interface to a bug tracker.
BugTracker subclasses are used to enable interaction with different
bug trackers.
"""
def get_bug_info(self, repository, bug_id):
"""Get the information for the specified bug.
... | values should be gi | ven as an empty string.
"""
return {
'summary': '',
'description': '',
'status': '',
}
def make_bug_cache_key(self, repository, bug_id):
"""Returns a key to use when caching fetched bug information."""
return 'repository-%s-bug-%s' % (repo... |
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2013 Task Coach developers <developers@taskcoach.org>
Task Coach 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
... | hmentSelector
from itemctrl import Column
from listctrl import VirtualListCtrl
from checklistbox import CheckListBox
from treectrl import CheckTreeCtrl, TreeListCtrl
from squaremap import SquareMap
from timeline import Timeline
from datectrl import DateTimeCtrl, TimeEntry
from textctrl import SingleLineTextCtrl, MultiL... | port SpinCtrl
from tooltip import ToolTipMixin, SimpleToolTip
from dirchooser import DirectoryChooser
from fontpicker import FontPickerCtrl
from syncmlwarning import SyncMLWarningDialog
from calendarwidget import Calendar
from calendarconfig import CalendarConfigDialog
from password import GetPassword
import masked
fro... |
#!/usr/bin/env python
"""simple thread pool
@author: dn13(dn13@gmail.com)
@author: Fibrizof(dfang84@gmail.com)
"""
import threading
import Queue
import new
def WorkerPoolError( Exception ):
pass
class Task(threading.Thread):
def __init__(self, queue, result_queue):
threading.Thread.__init__(self)
... | while self.running:
call = self.queue.get()
if call:
try:
reslut = call()
| self.result_queue.put(reslut)
except:
pass
self.queue.task_done()
class WorkerPool( object ):
def __init__( self, threadnum ):
self.threadnum = threadnum
self.q = Queue.Queue()
self.result_q = Queue.Queue()
self.ts =... |
from ..utils.command import BaseCommand
from ..utils.tabulate import tabulate
from ..utils.info import get_packages, Sources
class Colors:
PURPLE = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
UNDERLINE = '\033[4m'
ENDC = '\033[0m'
class Command(BaseCommand):
name... | hod
def run(cls, args):
cls._run()
@classmethod
def _run(cls):
packages = get_packages((Sources.required, Sources.installed))
packages = list(filter(lambda p: p.wanted_rule, packages)) # filter out ones with no wanted version (not in package.json)
packages_to_display = []
fo | r package in packages:
package.get_wanted_version()
if not package.version or (
package.version != package.latest_version or
package.version != package.wanted_version):
packages_to_display.append(package)
cls.display_outdated(packages_to_display)
@staticmethod
def display_outdated(packages):
if ... |
ist(self):
"""
Tests --list output of migrate command
"""
out = six.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: True):
call_command("migrate", list=True, stdout=out, verbosity=0, no_color=False)
self.assertEqual(
... | , "migrations", "0001", stdout=out)
output = out.getvalue()
self.assertIn(connection.ops.start_tra | nsaction_sql(), output)
self.assertIn(connection.ops.end_transaction_sql(), output)
# Test forwards. All the databases agree on CREATE TABLE, at least.
out = six.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
self.assertIn("create table", out.getvalue().... |
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
class home_grid_id(Variable):
'''The grid_id of a person's residence.'''
def dep... | },
'person':persons
},
dataset = 'person'
)
should_be = array([9, 9, 7, 7, 7])
self.assert_ | (ma.allclose(values, should_be, rtol=1e-7),
'Error in ' + self.variable_name)
if __name__=='__main__':
opus_unittest.main() |
_ in content_view.repository])
content_view.publish()
cvv = content_view.read().version[0]
self.assertEqual(len(cvv.read().environment), 1)
for i in range(1, randint(3, 6)):
lce = entities.LifecycleEnvironment(organization=self.org).create()
promote(cvv, lce.id)... | """@Test: Add Docker-type repository to content view and publish it.
Then add that content view to composite one. Publish and promote that
c | omposite content view to the next available lifecycle-environment.
@Assert: Docker-type repository is promoted to content view found in
the specific lifecycle-environment.
@Feature: Docker
"""
lce = entities.LifecycleEnvironment(organization=self.org).create()
repo = _... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
|
from yali.storage import StorageError
class LibraryError(StorageError) | :
pass
|
"""
Interrogate stick for supported capabilities.
"""
import sys
from codinghyde.ant import driver
from codinghyde.ant import node
from config import *
# Initialize
stick = driv | er.USB1Driver(SERIAL, debug=DEBUG)
antnode = node.Node(stick)
antnode.start()
# Interrogate stick
# Note: This method will return immediately, as the stick's capabilities are
# interrogated on node initialization (node.start()) in order to set proper
# internal Node instance state.
capabilities = antnode.getCapabiliti... | bilities['std_options']
print 'Advanced options: %X' % capabilities['adv_options']
# Shutdown
antnode.stop()
|
("realm")
.filter(
delivery_email__iexact=email.strip(),
is_active=True,
realm__deactivated=False,
is_bot=False,
)
.order_by("date_joined")
)
accounts: List[Accounts] = []
for profile in profiles:
accounts.append(
di... | = True
# Note that bot_owner_id can be None with legacy data.
result["bot_owner_id"] = row["bot_owner_id"]
elif custom_profile_field_data is not None:
result["profile_data"] = custom_profile_field_data
return result
def user_profile_to_user_row(user_profile: UserProfile) -> Dict[str, ... | te the user_profile having been
# fetched from a QuerySet using `.values(*realm_user_dict_fields)`
# even though we fetched UserProfile objects. This is messier
# than it seems.
#
# What we'd like to do is just call model_to_dict(user,
# fields=realm_user_dict_fields). The problem with this is... |
# -*- coding: utf-8 -*-
"""Installer script for Pywikibot 2.0 framework."""
#
# (C) Pywikibot team, 2009-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
import itertools
import os
import sys
PYTHON_VERSION = sys.version_info[:3]
PY2 = (PYTHON_VERSIO... | uth>=0.2.4'],
'html': ['BeautifulSoup4'],
}
if PY2:
# Additional core library dependencies which are only available on | Python 2
extra_deps.update({
'csv': ['unicodecsv'],
'MySQL': ['oursql'],
'unicode7': ['unicodedata2>=7.0.0-2'],
})
script_deps = {
'flickrripper.py': ['Pillow'],
'states_redirect.py': ['pycountry'],
'weblinkchecker.py': ['memento_client>=0.5.1'],
}
# flickrapi 1.4.4 install... |
# (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | on.load(f)
self._cache[key] = value
return value
finally:
f.close()
def set(self, key, value):
self._cache[key] = value |
cachefile = "%s/%s" % (self._cache_dir, key)
try:
f = open(cachefile, 'w')
except (OSError,IOError), e:
utils.warning("error while trying to read %s : %s" % (cachefile, str(e)))
else:
f.write(utils.jsonify(value))
finally:
f.close... |
#!/usr/bin/env python
"""Upserts Domains from Salesforce Domain__c.
"""
import logging
import os
from django.core.management.base import BaseCommand
import iss.models
import iss.salesforce
logger = logging.getLogger(os.path.basename(__file__))
class Command(BaseCommand):
def add_arguments(self, parser):
... | ince` days.
"""
logger.info('upserting domains modified in last {since} days'.
format(since=modified_since))
modified_domains = (iss.salesforce.Domain.get_domains_modified_since(
days_ago=modified_since))
fo | r domain in modified_domains:
iss.models.Domain.upsert(domain)
|
from sslyze import ServerNetworkLocation
from sslyze.plugins.elliptic_curves_plugin import (
SupportedEllipticCurvesScanResult,
SupportedEllipticCurvesImplementation,
)
from tests.connectivity_utils import check_connectivity_to_server_and_return_info
from tests.markers import can_only_run_on_linux_64
from tests... | orts_ecdh_key_exchange
assert result.supported_curves
assert result.rejected_curves
# And a CLI output can be generated
assert SupportedEllipticCurvesImplementati | on.cli_connector_cls.result_to_console_output(result)
@can_only_run_on_linux_64
class TestEllipticCurvesPluginWithLocalServer:
def test_supported_curves(self):
# Given a server to scan that supports ECDH cipher suites with specific curves
server_curves = ["X25519", "X448", "prime256v1", "secp384r1... |
# Copyright 2012-2013 Ravello Systems, 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 agree... | 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.
from __future__ import absolute_ | import, print_function
import argparse
import textwrap
from testmill import (console, manifest, keypair, login, error,
application, tasks, util, inflect)
from testmill.state import env
usage = textwrap.dedent("""\
usage: ravtest [OPTION]... run [-i] [-c] [--new] [--vms <vmlist>]
... |
# Copyright (c) 2012, Tycho Andersen. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... | hall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A P | ARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class QtileS... |
__author__ = 'thatcher'
from django.contrib import admin
# from django.contrib.auth.models import User
# from django.contrib.auth.admin import UserAdmin
# from django.contrib.sessions.
from django.contrib.sessions.models import Session
from .models import *
from base.forms import *
def images_thubmnail(self):
ret... | , 'show', 'author']
admin.site.register(NewsItem, NewsItemAdmin)
class EventAdmin(admin.ModelAdmin):
model = Event
list_display = ['title', 'location', 'date_and_time']
admin.site.register(Event, EventAdmin)
class PostAdmin(admin.ModelAdmin):
| model = GenericPost
list_display = ['title', 'category', 'publication_date']
admin.site.register(GenericPost, PostAdmin)
class CategoryAdmin(admin.ModelAdmin):
model = PostCategory
list_display = ['name', 'added_date']
admin.site.register(PostCategory, CategoryAdmin)
class ImageAdmin(admin.ModelAdmin):
... |
le uses imp for python up to 3.2 and importlib for python 3.3 on; the
correct implementation is delegated to _compatibility.
This module also supports import autocompletion, which means to complete
statements like ``from datetim`` (curser at the end would return ``datetime``).
"""
from __future__ import with_statement... | der, name, is_pkg in pkgutil.iter_modules(search_path):
names.append(generate_name(name))
return names
def _sys_path_with_modifications(self):
# If you edit e.g. gunicorn, there will be imports like this:
# `from gunicorn | import something`. But gunicorn is not in the
# sys.path. Therefore look if gunicorn is a parent directory, #56.
in_path = []
if self.import_path:
parts = self.file_path.split(os.path.sep)
for i, p in enumerate(parts):
if p == self.import_path[0]:
... |
from __future__ import division
from collections import deque
class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
"""
self.queue = deque(maxlen=size)
def next(self, val):
"""
:type val: int
... | Given a stream of integers and a window size,
# calculate the moving a | verage of all integers in the sliding window.
if __name__ == '__main__':
m = MovingAverage(3)
assert m.next(1) == 1
assert m.next(10) == (1 + 10) / 2
assert m.next(3) == (1 + 10 + 3) / 3
assert m.next(5) == (10 + 3 + 5) / 3
|
# -*- coding: utf-8 -*-
"""Racndicmd setup.py."""
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import os
import sys
class Tox(TestCommand):
"""Tox."""
user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def initialize_options(self):
... | ox_args:
errno = tox.cmdline(args=shlex.split(self.tox_args))
else:
errno = tox.cmdline(self.tox_args)
sys.exit(errno)
classifiers = [
"Development Status :: 3 - Alpha",
"Programming Language :: Pyt | hon",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language ... |
from .c | ompany import Company
from .contact import Contact
from .deal import Deal
from .note import Note
from .requester import Requester
class AgileCRM:
def __init__(self, domain, email, api_key):
requester = Requester(domain, email, api_key)
self.contact = Contact(requester=requester)
self.comp... | self.deal = Deal(requester=requester)
self.note = Note(requester=requester)
|
#!/usr/bin/env python3
#!/usr/bin/python
# https://en.wikipedia.org/wiki/Matplotlib
import numpy
import matplotlib.pyplot as plt
from numpy.random import rand
a = rand(100)
b = rand(100)
plt.scatter(a, b)
plt.show() | ||
'''
A MLP algorithm example using TensorFlow library.
This example is using generate random distribution
(http://cs231n.github.io/neural-networks-case-study/)
Code references:
https://github.com/shouvikmani/Tensorflow-Deep-Learning-Tutorial/blob/master/tutorial.ipynb
https://github.com/aymericdamien/TensorFlow-Example... | .ravel(), yy.ravel()]})
Z = np.argmax(Z, axis=1)
Z = Z.reshape(xx.shape)
fig = p | lt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X_train[:, 0], X_train[:, 1], c=yc, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.show()
|
# Copyright 2016 Palo Alto Networks, 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 agre... |
self.max_counter += 1
new_max_counter = '%016x' % self.max_counter
self.db[key+new_max_counter] = value
def backwards_iterator(self, timestamp, counter):
starting_key = '%016x%016x' % (timestamp, counter)
items = [[k, v] for k, v in self.db.iteritems() if k <= starting_key... | self.db_open = False
@staticmethod
def oldest_table():
tables = [t.name for t in MOCK_TABLES]
LOG.debug(tables)
if len(tables) == 0:
return None
return sorted(tables)[0]
def table_factory(name, create_if_missing=True):
table = next((t for t in MOCK_TABLE... |
from unittest import TestCase
from compile import add_jmp_opcodes, break_to_atoms
from compile.jmp_add import travel, shuffle
from opcode_ import PRT
class TestJMPAdd(TestCase):
def test_added_init_jmp(self):
node_chain = PRT.build_from_string('u', None)
atoms = break_to_atoms(node_chain)
... | to_atoms(atom)
atoms = add_jmp_opcodes(atoms)
self.assertEqual(atoms[0][0].target_uuid,
first_node.uuid)
def test_reach_to_end(s | elf):
node_chain = PRT.build_from_string('T', None) + \
PRT.build_from_string('h', None) + \
PRT.build_from_string('e', None) + \
PRT.build_from_string('A', None) + \
PRT.build_from_string('n', None) + \
PRT... |
from django.contrib import admin
from .models import Album, Song
# Re | gister your models here.
admin.site.register(Album)
admin.site.regis | ter(Song)
|
#!/usr/bin/env python
from traits.api import HasStrictTraits, Float
from mock import Mock
class MyClass(HasStrictTraits):
number = Float(2.0)
def add_to_number(self, value):
""" Add the value to `number`. """
self.number += value
my_class = MyClass()
# Using my_class.add_to_number = Mock... | k on the instance `__dict__` works.
my_class.__dict__['add_to_number'] = Mock()
# We can now use the mock in our tests.
my_class.add_to_number(42)
print my_class | .add_to_number.call_args_list
|
if thisage > age:
age = thisage
return age
def has_other_reviewers(self, excludeusers):
'''Determine if the patch has been reviewed by any
users that are not in 'excludeusers'''
hasReviewers = False
for approval in self.approvals:
if not... | (includeusers):
hasReviewers = True
return hasReviewers
def has_current_reviewers(self, includeusers):
'''Determine if the current patch version has
been reviewed by any of the | users in 'includeusers'. '''
patch = self.get_current_patch()
if patch is None:
return False
return patch.has_reviewers(includeusers)
def has_current_other_reviewers(self, excludeusers):
'''Determine if the current patch version has
been reviewed by any of the us... |
#!/usr/bin/python
import Adafruit_GPIO as GPIO
import time, os
#print "GETTING GPIO OBJECT"
gpio = GPIO.get_platform_gpio()
#print "SETUP CSID1"
#gpio.setup("CSID1", GPIO.OUT)
#print os.path.exists('/sys/class/gpio/gpio133')
#print "SETUP XIO-P1"
#gpio.setup("XIO-P1", GPIO.IN)
#GPIO.setup("U14_13", GPIO.IN)
#prin... | sleep(1)
#print "LOW", gpio.input("XIO-P1")
#gpio.output("CSID1", GPIO.HIGH)
| #print "HIGH", gpio.input("XIO-P1")
#gpio.output("CSID1", GPIO.LOW)
#print "LOW", gpio.input("XIO-P1")
#this example will test out CHIP XIO-P0 in to XIO-P1
#jumper the pins to test
#
#my test required sudo to work, gpio access requires sudo before changing permissions
#gpio.setup("XIO-P0", GPIO.OUT)
#gpio.setup("XIO-... |
################################################################################
#
# Copyright 2015-2020 Félix Brezo and Yaiza Rubio
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Softwa... | edentials = {}
#self.needsCredentials["phonefy"] = False
self.needsCredentials["usufy"] = False
#self.needsCredentials[ | "searchfy"] = False
#################
# Valid queries #
#################
# Strings that will imply that the query number is not appearing
self.validQuery = {}
# The regular expression '.+' will match any query.
#self.validQuery["phonefy"] = ".*"
self.val... |
turn redirect(url)
@rendered_with("opendebates/list_ideas.html")
@allow_http("GET", "POST")
def questions(request):
# If the user is GETting the list of questions, then redirect to the list_ideas
# page for this Debate.
if request.method == 'GET':
return redirect(reverse("list_ideas"))
if not... | alid():
form.save()
messages.info(request, _(u'This question has been flagged for merging.'))
return redirect(idea)
return {
'idea': idea,
'form': form,
}
@rendered_with("opendebates/top_archive.html")
@allow_http("GET")
def top_archive(request, slug):
category = ge... | _or_404(TopSubmissionCategory,
debate=request.debate, slug=slug)
submissions = category.submissions.select_related(
"submission", "submission__voter", "submission__voter__user",
"submission__category").order_by("rank", "created_at").all()
return {
'catego... |
# Copyright (C) 2017 Equinor ASA, Norway.
#
# The file 'site_config.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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 Lic... |
self.driver.set_option(
option[ConfigKeys.NAME], option[ConfigKeys.VALUE]
)
def create_job_queue(self):
queue = JobQueue(self.driver, max_submit=self.max_submit)
return qu | eue
def create_local_copy(self):
return self._alloc_local_copy()
def has_job_script(self):
return self._has_job_script()
def free(self):
self._free()
@property
def max_submit(self):
return self._max_submit()
@property
def queue_name(self):
return ... |
from setuptools import setup, find_packages
import os
import allensdk
# http://bugs.python.org/issue8876#msg208792
if hasattr(os, 'link'):
del os.link
def prepend_find_packages(*roots):
''' Recursively traverse nested packages under the root directories
'''
packages = []
for root in roots:
... | packages = prepend_find_packages('allensdk'),
package_data={'': ['*.conf', '*.cfg', '*.md', '*.json', '*.dat', '*.env', '*.sh', 'bps', 'Makefile', 'COPYING'] },
description = 'core libraries for the allensdk.',
install_requires = ['h5py>=2.2.1',
'matplotlib>=1.4.2',
| 'pandas>=0.16.2',
'numpy>=1.8.2',
'six>=1.8.0',
'pynrrd <= 0.2.0.dev'],
dependency_links = [
'git+https://github.com/mhe/pynrrd.git@9e09b24ff1#egg=pynrrd-0.1.999.dev'
],
tests_require=['nose>=1.2.1',
... |
import shutil
from nose.tools import *
from holland.lib.lvm import LogicalVolume
from holland.lib.lvm.snapshot import *
from tests.constants import *
class TestSnapshot(object):
def setup(self):
self.tmpdir = tempfile.mkdtemp()
def teardown(self):
shutil.rmtree(self.tmpdir)
def test_snap... | alize', 'pre-snapshot', 'post-snapshot',
'pre-mount', 'post-mount', 'pre-unmount', 'post-unmount',
'pre-remove', 'post-remove', 'finish'):
snapshot.register(evt, bad_callback)
assert_raises(CallbackFailuresError, snapshot.start, lv)
snapshot.u... | t, bad_callback)
if snapshot.sigmgr._handlers:
raise Exception("WTF. sigmgr handlers still exist when checking event => %r", evt)
|
#!/usr/bin/env python3
import json
import os
import subprocess
def connection_lost(network_id, timeout_seconds):
p = | subprocess.Popen(["hamachi", "go-online", network_id])
try:
p.wai | t(timeout_seconds)
except subprocess.TimeoutExpired:
p.kill()
return True
return False
if __name__ == "__main__":
with open("/etc/hamachi-watchdog/hamachi-watchdog.conf", "r") as f:
config = json.load(f)
network_id = config['network_id']
timeout_seconds = config['ti... |
#!/usr/bin/env python
## \file merge_solution.py
# \brief Python script for merging of the solution files.
# \author F. Palacios
# \version 6.1.0 "Falcon"
#
# The current SU2 release has been coordinated by the
# SU2 International Developers Society <www.su2devsociety.org>
# with selected contributions from the op... | tions = -1 ):
config = SU2.io. | Config(filename)
if partitions > -1 :
config.NUMBER_PART = partitions
SU2.run.merge(config)
#: def merge_solution()
if __name__ == '__main__':
main()
|
# - | *- coding: utf-8 -*-
| # Copyright 2014-17 Eficent Business and IT Consulting Services S.L.
# <contact@eficent.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from . import progress_measurements_entry
|
"""
Texture Replacement
+++++++++++++++++++
Example of how to replace a texture in game with an external image.
``createTexture()`` and ``removeTexture()`` are to be called from a
module Python Controller.
"""
from bge import logic
from bge import texture
def createTexture(cont):
"""Create a new Dynamic Texture"... | j = cont.owner
# get the reference pointer (ID) of the internal texture
ID = texture.materialID(obj, 'IMoriginal.png')
# create a texture object
object_texture = texture.Texture(obj, ID)
# create a new source with an external image
url = logic.expandPath("//newtexture.jpg")
new_source = t... | manent Python object
logic.texture = object_texture
# update/replace the texture
logic.texture.source = new_source
logic.texture.refresh(False)
def removeTexture(cont):
"""Delete the Dynamic Texture, reversing back the final to its original state."""
try:
del logic.texture
except:... |
'r' )
self.ls = {}
self.__load_ls()
def __load_ls( self ):
ils = self.zf.infolist()
for i in ils:
try:
ids, e = i.filename.split( '.' )
id = int( ids, 16 )
self.ls[id] = i
except:
print 'WARNI... | elf.to_commit[:completion]:
shutil.move( t[1], t[0] )
# Sometimes move() seems to leave files behin | d
for t in self.to_commit:
try:
if( os.path.isfile( t[1] ) ):
os.remove( t[1] )
except:
pass
raise
# Comitted
self.state = 'committed'
def rollback( self ):
if( self.st... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python libr... | formation necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using... | identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle wil... |
import random
class intDict(object):
"""A dictionary with integer keys"""
def | __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])
def add | Entry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry."""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucke... |
#!/usr/bin/env p | ython
from sys import argv
def calcRabbits(n,k):
pairs = [1, 1]
for i in range(2,n):
#try:
f1 = pairs[i-1]
f2 = pairs[i-2] * 3
pairs.append((f1+f2))
# except IndexError:
# pass
return pairs
if __name__ == "__main__":
try:
n = int(argv... | int(argv[2])
print(calcRabbits(n,k))
except (IndexError, ValueError):
print("Usage: python fib.py <intN> <intK>")
|
from cms.models.pluginmod | el import CMSPlugin
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import gettext_lazy as _
from djan | go.utils.translation import get_language
from partners.models import Partner
class PartnersPlugin(CMSPluginBase):
name = _("Partners")
model = CMSPlugin
render_template = "partners/partners_plugin.html"
text_enabled = False
allow_children = False
def render(self, context, instance, placehold... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext
from django.contrib import messages
from django.contrib.adm... | eturn group, bridge
def group_context(group, bridge):
# @@@ use bridge
ctx = {
"group": group,
}
if group:
ctx["group_base"] = bridge.group_base_te | mplate()
return ctx
def signup(request, **kwargs):
form_class = kwargs.pop("form_class", SignupForm)
template_name = kwargs.pop("template_name", "account/signup.html")
template_name_failure = kwargs.pop("template_name_failure", "signup_codes/failure.html")
success_url = kwargs.pop("success_ur... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", | "sleeptomusicweb.settings")
from django.core.management import execute_from_command_line
execute_from_command_ | line(sys.argv)
|
import mimetypes
import unittest
from os import path
from django.conf.urls.static import static
from django.http import FileResponse, HttpResponseNotModified
from django.test import SimpleTestCase, override_settings
from django.utils.http import http_date
from django.views.static import was_modified_since
from .. imp... | FC
2616, section 14.25.
"""
file_name = 'file.txt'
invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT'
response = self.client.get('/%s/%s' % (self.prefix, file_name),
HTTP_IF_MODIFIED_SINCE=invalid_date)
response_content = b''. | join(response)
with open(path.join(media_dir, file_name), 'rb') as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(len(response_content), int(response['Content-Length']))
def test_404(self):
response = self.client.get('/%s/non_existing_resource' % self.prefix)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) | and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' if no si | des are equal
#
# The tests for this method can be found in
# about_triangle_project.py
# and
# about_triangle_project_2.py
#
def triangle(a, b, c):
if a <=0 or b <= 0 or c <= 0:
raise TriangleError(f"Non-positive value passed for sides:{a},{b},{c}")
sum1 = a + b
sum2 = a + c
sum3 = b + c... |
#!/usr/bin/python
#! -*- coding:utf-8 -*-
from sqlalchemy import Column, Integer, String
from database import Base
class Message(Base):
__tablename__ = 'message'
MessageId = Column(Integer, primary_key=True)
DeviceId = Column(String(50))
MessageBody = Column(String(1000))
MessageType = Column(Inte... | Column(Integer)
LastUseTime = Column(String(50))
def __init__(self, json):
self.DeviceId = json["DeviceId"]
self.UseTimes = json["UseTimes"]
self.LastUseTime = json["LastUseTime"]
def get_json(self):
| return {
"DeviceId":self.DeviceId,
"UseTimes":self.UseTimes,
"LastUseTime":self.LastUseTime
}
def __repr__(self):
return repr(self.get_json())
|
# Copyright 2018 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/lic | enses/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.
# ==============================================================================
"""Class OneDeviceStrategy implementing DistributionStrategy.""... |
"""
A HTML5 target.
"""
from targets import _
from html import TYPE
import html
NAME = _('HTML5 page')
EXTENSION = 'html'
HEADER = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="%(ENCODING)s">
<title>%(HEADER1)s</title>
<meta name="generator" content="http://txt2tags.org">
<link rel="stylesheet" href="%(STYLE)s"... | se' : '</em>' ,
'fontUnderlineOpen' : '<span class="underline">',
'fontUnderlineClose' : '</span>' ,
'fontStrikeOpen' : '<del>' ,
'fontStrikeClose' : '</del>' ,
'listItemClose' : '</li>' ,
'numlistItemClose' : '</li>' ... | 'deflistItem2Close' : '</dd>' ,
'bar1' : '<hr class="light">' ,
'bar2' : '<hr class="heavy">' ,
'img' : '<img~a~ src="\a" alt="">' ,
'imgEmbed' : '<img~a~ src="\a" alt="">' ,
'_imgAlignLeft' : ' class="l... |
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
result = 0
kind = list(set(candies))
if len(kind) > len(candies)/2:
result = len(candies)/2
else:
| result = len(kind)
| return result
|
import numpy
from chainer import cuda, Function
def _cu_conv_sum(y, x, n):
# Convolutional sum
# TODO(beam2d): Use scan computation
rdim = x.size / (x.shape[0] * x.shape[1])
cuda.elementwise(
'float* y, const float* x, int rdim, int N, int n_',
'''
int half_n = n_ / 2;
... | )(gx, x[0], gy[0], self.scale, self.beta,
2 * self.alpha * self.beta)
return gx,
def local_response_normalization(x, n=5, k=2, alpha=1e-4, bet | a=.75):
"""Local response normalization across neighboring channels.
This function implements normalization across channels. Let :math:`x` an
input image with :math:`N` channels. Then, this function computes an output
image :math:`y` by following formula:
.. math::
y_i = {x_i \\over \\left(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.