prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
"""
HTTP handeler to serve specific endpoint request like
http://myserver:9004/endpoints/mymodel
For how generic endpoints requests is served look
at endpoints_handler.py
"""
import json
import logging
import shutil
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.handlers import Ma... | e):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self.logger.log(logging.DEBUG, f"Processing DELETE for /endpoints/{name}")
try:
endpoints = self.tabpy_state.get_endpoints(name)
if len(endpoint... | self.error_out(404, f"endpoint {name} does not exist.")
self.finish()
return
# update state
try:
endpoint_info = self.tabpy_state.delete_endpoint(name)
except Exception as e:
self.error_out(400, f"Error when remo... |
the red_button. Here we have defined
the commands and the cmdset in the same modul | e, but if you
have many different commands to merge it is often better
to define the cmdset separately, picking and choosing from
among the avai | lable commands as to what should be included in the
cmdset - this way you can often re-use the commands too.
"""
import random
from evennia import Command, CmdSet
# Some simple commands for the red button
# ------------------------------------------------------------
# Commands defined on the red button
# ----------... |
01000
PSR_EC = 0x00002000
PSR_RSV = 0x000FC000
PSR_ICC = 0x00F00000
PSR_C = 0x00100000
PSR_V = 0x00200000
PSR_Z = 0x00400000
PSR_N = 0x00800000
PSR_VER = 0x0F000000
PSR_IMPL = 0xF0000000
PSL_ALLCC = PSR_ICC
PSL_USER = (PSR_S)
PSL_USERMASK = (PSR_ICC)
PSL_UBITS = (PSR_ICC|PSR_EF)
def USERMODE(ps): return (((ps) & PSR_PS... | _STOPPING = 0x0200
TP_WATCHPT = 0x0400
TP_PAUSE = 0x0800
TP_CHANGEBIND = 0x1000
TS_LOAD = 0x0001
TS_DONT_SWAP = 0x0002
TS_SWAPENQ = 0x0004
TS_ON_SWAPQ = 0x0008
TS_CSTART = 0x0100
TS_UNPAUSE = 0x0200
TS_XSTART = 0x0400
TS_PSTART = 0x0800
TS_RESUME = 0x1000
TS_CREATE = 0x2000
TS_ALLSTART = \
(TS_CSTART|TS_UNPAUSE... |
def THREAD_TRANSITION(tp): return thread_transition(tp);
def THREAD_STOP(tp): return \
def THREAD_ZOMB(tp): return THREAD_SET_STATE(tp, TS_ZOMB, NULL)
def SEMA_HELD(x): return (sema_held((x)))
NO_LOCKS_HELD = 1
NO_COMPETING_THREADS = 1
# Included from sys/cred.h
# Included from sys/uio.h
from TYPES import *
# ... |
# from test_plus.test import TestCase
# |
#
# class TestUser(TestCase):
#
# def setUp(self):
# self.user = self.make_user()
#
# | def test__str__(self):
# self.assertEqual(
# self.user.__str__(),
# 'testuser' # This is the default username for self.make_user()
# )
#
# def test_get_absolute_url(self):
# self.assertEqual(
# self.user.get_absolute_url(),
# '/users/testus... |
#/usr/bin/env python
import codecs
import os
import sys
from setuptools import setup, find_packages
if 'publish' in sys.argv:
os.syste | m('python setup.py sdist upload')
sys.exit()
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
# Dynamically calculate the version based on galeria.VERSION.
version = __import__('galeria').get_version()
setup(
name='django-galeria',
version=version,
description='Pluggable gallery/po... | jects',
long_description=read(os.path.join(os.path.dirname(__file__), 'README.rst')),
author='Guilherme Gondim',
author_email='semente+django-galeria@taurinus.org',
maintainer='Guilherme Gondim',
maintainer_email='semente+django-galeria@taurinus.org',
license='BSD License',
url='https://bitb... |
side of an
rpc API.
"""
# The default namespace, which can be overridden in a subclass.
RPC_API_NAMESPACE = None
def __init__(self, topic, default_version, version_cap=None,
serializer=None):
"""Initialize an RpcProxy.
:param topic: The topic to use for all messag... | s None:
serializer = rpc_serializer.NoOpSerializer()
self.serializer = serializer
super(RpcProxy, self).__init__()
def _set_version(self, msg, vers):
"""Helper m | ethod to set the version in a message.
:param msg: The message having a version added to it.
:param vers: The version number to add to the message.
"""
v = vers if vers else self.default_version
if (self.version_cap and not
rpc_common.version_is_compatible(self.v... |
def has_module_perms(self, user, app_label):
if not user.is_anonymous() and not user.is_active:
return False
return app_label == "app1"
def get_all_permissions(self, user, obj=None):
if not obj:
return [] # We only support row level perms
if not isins... | tUp(self):
User.objects.create_user(self.TEST_USERNAME,
self.TEST_EMAIL,
self.TEST_PASSWORD)
@override_settings(AUTHENTICATION_BACKENDS=[bac | kend])
def test_changed_backend_settings(self):
"""
Tests that removing a backend configured in AUTHENTICATION_BACKENDS
make already logged-in users disconnect.
"""
# Get a session for the test user
self.assertTrue(self.client.login(
username=self.TEST_US... |
def is_displayed(self):
return (
self.in_intel_reports and
self.title.text == 'Dashboards for "{}"'.format(self.context["object"].group) and
self.dashboards.is_opened and
self.dashboards.tree.currently_selected == [
"All Dashboards",
... | boardView(DashboardFormCommon):
add_button = Button("Add")
@property
def is_displayed(self):
return (
self.in_intel_reports and
self.title.text == "Adding a new dashboard" and
self.dashboards.is_opened and
self.dashboards.tree.currently_selected == [
... | rds",
"All Groups",
self.context["object"].group
]
)
class EditDashboardView(DashboardFormCommon):
save_button = Button("Save")
reset_button = Button("Reset")
@property
def is_displayed(self):
return (
self.in_intel_reports and
... |
# The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
from collections import OrderedDict
from math import log, sqrt
import numpy as np
import pandas as pd
from six.moves import cStringIO as StringIO
from bokeh.plotting import figure, show, output_server
antibiotics = """
bacteria,... | lor = OrderedDict([
("Penicillin", "#0d3362"),
("Streptomycin", "#c | 64737"),
("Neomycin", "black" ),
])
gram_color = {
"positive" : "#aeaeb8",
"negative" : "#e69584",
}
df = pd.read_csv(StringIO(antibiotics),
skiprows=1,
skipinitialspace=True,
engine='python')
width = 800
height = 800
inner_radius = 90
outer_radius ... |
#!/usr/bin/env python
#
# Copyright (c) 2009, Roboterclub Aachen e.V.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or witho | ut
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this ... | nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WAR... |
from sacred import Experiment
ex = | Experiment('my_commands')
@ex.config
def cfg():
name = 'kyle'
@ex.command
def greet(name):
print('Hello {}! Nice to greet you!'.format(name))
@ex.command
def shout():
print('WHAZZZUUUUUUUUUUP!!!????')
@ex.automain
def main():
print('This is just the main command. Try greet or shou | t.') |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 7 14:53:55 2016
@author: nu
"""
import numpy as np
import timeit, os, sys
from astropy.coordinates import SkyCoord
from astropy.table import Column
from astroquery.vizier import Vizier
from astropy import units as u
from TAROT_PL import TarotPIP
from Filter_data import ... | andidate in NOMAD1\n\n")
stop = timeit.default_timer()
runtime = stop - start
print("\nRuntime = %2.2f" %runtime)
#graph0 = candidateplot(TAROT_data.tbdata,XYcandi['Xpix'],XYcandi['Ypix'], 'Candidate by angula | r separation')
|
"""alter database for mysql compatibility
Revision ID: 9be372ec38bc
Revises: 4328f2c08f05
Create Date: 2020-02-16 15:43:35.276655
"""
from alembic import op
import sqlalchemy as sa
from docassemble.webapp.database import dbtableprefix, dbprefix, daconfig
import sys
# revision identifiers, used by Alembic.
revision =... | table_name='machinelearning',
column_name='key',
type_=sa.Text()
)
op.alter_column(
table_name='machinelearning',
column_name='group_id',
type_=sa.Text()
)
op.alter_column(
table_name='globalobjectstorage',
column_name='key',
type_=sa.T... | oads')
|
# -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of CampOS Event,
# an Odoo module.
#
# Copyright (c) 2015 Stein & Gabelgaard ApS
# http://www.steingabelgaard.dk
# Hans Henrik G | aelgaard
#
# CampOS Event 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 option) any
# later version.
#
# CampOS Event is distributed
# in the hope that it will be useful, b... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA
#
# 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/l... | VI_BGR +
| self._videoinput_wrapper.VI_VERTICAL_FLIP
)
)
return frame
# override
def _read_frame_func(self):
frame = self.read_raw()
return frame
# override
def _initialize_driver_func(self):
pass
# override
def _cleanup_driver_func(self)... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | tensions.admin.osksadm.extension_handler\
import ExtensionHandler as KSADMExtensionHandler
from keystone.contrib.extensions.admin.oskscatalog.extension_handler\
import ExtensionHandler as KSCATALOGExtensionHandler
def configure_extensions(mapper, options):
#TODO: Make extensions configurable.
ksadm_ex... | kscatalog_extension_handler = KSCATALOGExtensionHandler()
kscatalog_extension_handler.map_extension_methods(mapper, options)
|
# -*- coding: utf-8 -*-
import netaddr
from opinel.utils.aws import get_name
from opinel.utils.globals import manage_dictionary
from opinel.utils.fs import load_data, read_ip_ranges
from AWSScout2.utils import ec2_classic, get_keys
from AWSScout2.configs.regions import RegionalServiceConfig, RegionConfig
from AWSSc... | (cidr)
if cidr in ip_prefix:
return 'Unkn | own CIDR in %s %s' % (ip_range['service'], ip_range['region'])
return 'Unknown CIDR'
#
# Propagate VPC names in VPC-related services (info only fetched during EC2 calls)
#
def propagate_vpc_names(aws_config, current_config, path, current_path, resource_id, callback_args):
if resource_id == ec2_classic:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('organizations', '0002_migrate_locations_to_facilities'),
('notifications', '0003_auto_20150912_2049'),
]
operations = [
... | notification',
name='location',
field=models.ForeignKey(verbose_name='facility', to='organizations.Facility'),
),
migrations.RenameField(
model_name='notification',
old_name='location',
new_name='facility',
),
migrations.AlterFi... | lity'),
),
]
|
#__author__ = 'hello'
# -*- coding: cp936 -*-
import re
import os
import random
import json
import string
import ctypes
from myexception import *
PATH = './img/'
dm2 = ctypes.WinDLL('./CrackCaptchaAPI.dll')
if not os.path.exists('./img'):
os.mkdir('./img')
def str_tr(content):
instr = "0123456789"
outs... | = Header(subject,'utf-8')
msg['From'] = sender
msg['To'] = receiver
try:
send_smtp = smtplib.SMTP()
send_smtp.connect(smtpserver)
send_smtp.login(user,pas)
| send_smtp.sendmail(sender,receiver,msg.as_string())
send_smtp.close()
print 'ok'
except:
print 'error'
|
class Solution(object):
def findPaths(self, m, n, N, i, j):
"""
:type m: int
:type n: int
:type N: int
:type i: int
:type j: int
:rtype: int
"""
MOD = 1000000007
paths = 0
cur = {(i, j): 1}
for i in xrange(N):
... | in [[-1, 0], [0, 1], [1, 0], [0, -1]]:
| nx = x + dx
ny = y + dy
if nx < 0 or ny < 0 or nx >= m or ny >= n:
paths += cnt
paths %= MOD
else:
next[(nx, ny)] += cnt
next[(nx, ny)] %= MOD
cur =... |
h = (ay - y + h)
return x, (ay - y - h), w, h
return x, (ay - y)
def getBox(box, pagesize):
"""
Parse sizes by corners in the form:
<X-Left> <Y-Upper> <Width> <Height>
The last to values with negative values are interpreted as offsets form
the right and lower border.
"""
b... | # self.file = urlResponse
else:
urlResponse = urllib2.urlopen(uri)
self.mimetype = urlResponse.info().get("Content-Type", None).split(";")[0]
self.uri = urlResponse.geturl()
self.file = url... | if basepath:
uri = os.path.normpath(os.path.join(basepath, uri))
if os.path.isfile(uri):
self.uri = uri
self.local = uri
self.setMimeTypeByName(uri)
self.file = open(uri, "rb")
def getFile(s... |
#!/usr/bin/python
import sys, os, re
import json
import argparse
import pprint
arg_parser = argparse.ArgumentParser(description='Define tests')
arg_parser.add_argument('-p', '--pretty-print', action="store_true", help="select human friendly output, default is CSV")
arg_parser.add_argument('-i', '--info', action="stor... | _argument('in_dir', help="Input directory contatining JSON files")
arg_parser.add_argument('keys', nargs=argparse.REMAINDER, help="keys to extract")
args = arg_parser.parse_args()
def load_json(fname):
return json | .load(open(fname, "r"))
def load_all(src_dir):
data = {}
file_list = os.listdir(src_dir)
for f in file_list:
if not os.path.splitext(f)[1] == ".json":
continue
fp = os.path.join(src_dir, f)
try:
data[f] = load_json(fp)
except ValueError:
p... |
alternative_gp.append(gp.lower())
# Comment out the line beflow to test the source updater
# alternative_gp += ["%USERPROFILE%\AppData\Local\GitHub\PORTAB~1\bin\git.exe", "C:\Program Files (x86)\Git\bin\git.exe"]
# Returns a empty string if failed
output = GitUpdater... | output['versionsBehind'] = 0
htpc.COMMITS_BEHIND = 0
output['updateNeeded'] = False
else:
behind = self.behind_by(current, latest)
htpc.COMMITS_BEHIND = behind
output['versionsBehind'] = behind
self.logger.info("Currently " + str(output['v... | d latest """
self.logger.debug('Checking how far behind latest')
try:
url = 'https://api.github.com/repos/%s/%s/compare/%s...%s' % (gitUser, gitRepo, current, latest)
result = loads(urllib2.urlopen(url).read())
behind = int(result['total_commits'])
self.lo... |
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.forms import AuthenticationForm
from django.utils.decorators import method_decorator
from django.utils.http import is_safe_url
from django.views.decorators.debug import sensitive_post_parameters
from django.views import generic
fr... | return redirect_to
class LogoutView(generic.RedirectView) | :
permanent = False
pattern_name = 'main:landing'
def get(self, request, *args, **kwargs):
auth.logout(request)
return super(LogoutView, self).get(request, *args, **kwargs)
class ProfileView(generic.TemplateView):
template_name = 'accounts/profile_detail.html'
|
packet was received.
"""
logging.info('recieved DHCPRELEASE from: %s:%s',
source_address.ip, source_address.port)
logging.debug('\n%s\n', packet)
self._get_client_options(
'DHCP_RELEASE', self._get_packet_info(packet))
def _handleDHCPReque... | ress (dhcp.Address):
The address from which the request was received.
port (int):
The port on which the packet was received.
| """
logging.info('recieved DHCPREQUEST from: %s:%s',
source_address.ip, source_address.port)
logging.debug('\n%s\n', packet)
[msg_type, options] = self._get_client_options(
'DHCP_REQUEST', self._get_packet_info(packet))
self._send_dhcp_msg(... |
def find_number(x):
str_x = str(x)
if len(str_x) == 1:
raise Exception()
left_most = str_x[0]
try:
small_from_rest = find_number(int(str_x[1:]))
return int(left_most + str(small_from_rest))
except:
# min() will throw exception if parameter is empty list, meaning no d... | er than the left_most digit.
new_left_most = min([c for c in str_x[1:] if c > left_mos | t])
# assumption: no repeated digit
rest_of_digits = ''.join(sorted([c for c in str_x if c != new_left_most]))
y = new_left_most + rest_of_digits
return int(y)
print(find_number(5346)) |
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2020 Philipp Wolfer
#
# 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... | se):
def test_supports_tag(self):
fmt = ext_to_format(self.testfile_ext[1:])
self.assertTrue(fmt.supports_tag('copyright'))
self.assertTrue(fmt.supports_tag('compilation'))
self.assertTrue(fmt.supports_tag('bpm'))
self.assertTrue(fmt.supports_tag('djm... | tag('lyrics:lead'))
self.assertTrue(fmt.supports_tag('~length'))
for tag in self.replaygain_tags.keys():
self.assertTrue(fmt.supports_tag(tag))
@skipUnlessTestfile
def test_ci_tags_preserve_case(self):
# Ensure values are not duplicated on repeated sa... |
_depreciation_line_ids = depreciation_lin_obj.search(cr, uid, [('asset_id', '=', asset.id), ('move_id', '=', False)])
if old_depreciation_line_ids:
depreciation_lin_obj.unlink(cr, uid, old_depreciation_line_ids, context=context)
amount_to_depr = residual_amount = asset.value_res... | val['currency_id'] = company.currency_id.id
return {'value': val}
def onchange_purchase_salvage_value(self, cr, uid, ids, purchase_value, salvage_value, context=None):
val = {}
for asset in self.browse(cr, uid, ids, context=context):
if purchase_value:
... | purchase_value - salvage_value
if salvage_value:
val['value_residual'] = purchase_value - salvage_value
return {'value': val}
_columns = {
'account_move_line_ids': fields.one2many('account.move.line', 'asset_id', 'Entries', readonly=True, states={'draft':[('readonly... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaegraph.business_base import NodeSearch, DeleteNode
from classificacaodtm_app.commands import ListClassificacaodtmCommand, SaveClassificacaodtmCommand, UpdateClassificacaodtmCommand, \
ClassificacaodtmPublicForm, Classificacaodtm... | eClassificacaodtmCommand(classificacaodtm_id, **classificacaodtm_properties)
def list_classificacaodtms_cmd():
"""
Command to list Classificacaodtm entities ordered by their creation dates
:return: a Command proceed the db operations when executed
"""
return ListClassificacaodtmCommand()
def cla... | cacaodtm_detail_form(**kwargs):
"""
Function to get Classificacaodtm's detail form.
:param kwargs: form properties
:return: Form
"""
return ClassificacaodtmDetailForm(**kwargs)
def classificacaodtm_short_form(**kwargs):
"""
Function to get Classificacaodtm's short form. just a subset o... |
"""!
@brief Test templates for K-Means clustering module.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
from pyclustering.tests.assertion import assertion
from pyclustering.cluster.encoder import type_encoding, cluster_encoder
from pyclustering.cluster.... | er in centers:
assertion.eq(len(sample[0]), len(center))
if expected_cluster_length is not None:
obtained_cluster_sizes.sort()
expected_cluster_length.sort()
assertion.eq(obtained_cluster_sizes, expected_cluster_length)
@staticmethod
d... | sample = read_sample(path_to_file)
metric = kwargs.get('metric', distance_metric(type_metric.EUCLIDEAN_SQUARE))
itermax = kwargs.get('itermax', 200)
kmeans_instance = kmeans(sample, initial_centers, 0.001, ccore, metric=metric, itermax=itermax)
kmeans_instance.process()
... |
import numpy as np
from shesha.util.writers.common import dm
from shesha.util.writers.common import wfs
from shesha.util.writers.common import imat
from astropy.io import fits
def wfs_to_fits_hdu(sup, wfs_id):
"""Return a fits Header Data Unit (HDU) representation of a single WFS
Args:
sup : (compasSS... | t]) : optional, default all, list of the DM indices to include
| controller_id : (int) : optional, index of the controller passed to yao
influ : (int) : optional, actuator index for the influence function
compose_type : (str) : optional, possibility to specify split tomography case ("controller" or "splitTomo")
"""
print("writing data to" + file_name)
... |
"""
Compute WordVectors using Yelp Data
"""
from gensim.models.word2vec import Word2Vec
from util.language import detect_language, tokenize_text
from data_handling import get_reviews_data |
# Set to true for zero in in English reviews. Makes the process much slower
FILTER_ENGLISH = True
# Name for output w2v model file
OUTPUT_MODEL_FILE | = "w2v_yelp_100_alpha_0.025_window_4"
PICKLED_DATA = "/home/alfredo/deep-nlp/data/reviews.pickle."
NUM_PARTITIONS = 2 # Use all data
reviews_texts, _, _, _, _ = get_reviews_data(range(1, NUM_PARTITIONS), PICKLED_DATA)
# Each review will be considered a sentence
sentences = []
for num, text in enumerate(reviews_texts... |
# Django settings for python project.
DEBUG = True
import logging
LOG_LEVEL = logging.INFO
if DEBUG:
LOG_LEVEL = logging.DEBUG
logging.basicConfig(
level = LOG_LEVEL,
format = '[%(asctime)s %(name)s %(levelname)s] %(message)s',
)
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain... | to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT.
# Example: "http://media.lawrence.com"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, | JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '!q2sh7ue8^=bu&wj9tb9&4fx^dayk=wnxo^mtd)xmw1y2)6$w$'
# List of callables that know how to import templates from ... |
if renz == 'NONE':
opts.renz[n] = None
continue
try:
_ = RESTRICTION_ENZYMES[renz]
except KeyError:
print ('\n\nERROR: restriction enzyme %s not found.' % (renz)
+ 'Use one of:\n\n'
+ ' '.join(sorted(RESTRICTION_EN... | opts.mapper_param = opts.mappe | r_param[0].split()
else:
opts.mapper_param = dict([o.split(':') for o in opts.mapper_param])
else:
opts.mapper_param = {}
if opts.mapper == 'gem' and opts.gem_version < 3:
gem_valid_option = set(["granularity", "q", "quality-format",
"gem-quali... |
C.
#
# 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 un... | e)
self.assertIsInstance(process, tff.templates.AggregationProcess)
|
server_state_type = tff.type_at_server(())
expected_initialize_type = tff.FunctionType(
parameter=None, result=server_state_type)
self.assert_types_equivalent(process.initialize.type_signature,
expected_initialize_type)
expected_measurements_type = tff.type_at_... |
#!/usr/bin/python
i | mport sys
import requests
try:
url = sys.argv[1]
r = requests.get('http://%s' %url ,timeout=3)
except requests.exceptions.Timeout:
print 'url timeout\n%s' %url
sys.exit(2)
except:
print 'url error \n%s' %url
sys.exit(2)
url_status = r.status_code
if url_status == 200:
... | |
# CTCI 1.3
# URLify
import unittest
# My Solution
#------------------------------------------ | -------------------------------------
# CTCI Solution
def urlify(string, length):
'''function replaces single spaces with %20 and removes trailing spaces'''
new_index = len(string)
for i | in reversed(range(length)):
if string[i] == ' ':
# Replace spaces
string[new_index - 3:new_index] = '%20'
new_index -= 3
else:
# Move characters
string[new_index - 1] = string[i]
new_index -= 1
return string
#----------------... |
# System imports
import os
from os.path import join
import pytest
from git import *
from PyGitUp.git_wrapper import RebaseError
from PyGitUp.tests import basepath, write_file, init_master, update_file, testfile_name
test_name = 'rebase_error'
repo_path = join(basepath, test_name + os.sep)
def setup():
master_pa... | to test repo
path = join(basepath, test_name)
master.clone(path, b=test_name)
repo = Repo(path, odbt=GitCmdObjectDB)
assert repo.working_dir == path
# Modify file in master
update_file(master, test_name)
# Modify file in our repo
contents = 'completely changed!'
repo_file = join(... | odify file in master
update_file(master, test_name)
def test_rebase_error():
""" Run 'git up' with a failing rebase """
os.chdir(repo_path)
from PyGitUp.gitup import GitUp
gitup = GitUp(testing=True)
with pytest.raises(RebaseError):
gitup.run()
|
#!/usr/bin/env python
#! -*- coding: utf-8 -*-
from gi.repository import Cld
from gi.repository import DcsCore as dc
from gi.repository import DcsUI as du
from gi.repository import Gtk
class DcsExample(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="DCS Example")
config = Cld.X... | ct("ai0")
self.dev = self.context.get_object("dev0")
self.dev.open()
if(not self.dev.is_open):
print "Open device " + self.dev.id + " failed"
#self.task = self.context.get_object("tk0")
#self.task.run()
self.aictl = du.AIControl("/ai0")
self.aictl.co... | (self, widget):
widget.offer_cld_object(self.chan)
win = DcsExample()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
#!/usr/bin/python
import io
import os
import unittest
import logging
import uuid
from mediafire import MediaFireApi, MediaFireUploader, UploadSession
from mediafire.uploader import UPLOAD_SIMPLE_LIMIT_BYTES
APP_ID = '42511'
MEDIAFIRE_EMAIL = os.environ.get('MEDIAFIRE_EMAIL')
MEDIAFIRE_PASSWORD = os.environ.get('MEDI... | seTest(unittest.TestCase):
def setUp(self):
# Reset logging to info to avoid leaking credentials
logger = logging.getLogger('mediafire.api')
logger.setLevel(logging.INFO)
self.api = MediaFireApi()
session = self.api.user_get_session_token(
... | nittest.skipIf('CI' not in os.environ, "Running outside CI environment")
class MediaFireSmokeSimpleTest(MediaFireSmokeBaseTestCase.BaseTest):
"""Simple tests"""
def test_user_get_info(self):
result = self.api.user_get_info()
self.assertEqual(result["user_info"]["display_name"],
... |
with each list under a matching header (xfail files, xfail methods, skip files, skip methods)'''))
group.add_argument(
'-G',
'--category',
metavar='category',
action='append',
dest='categoriesList',
help=textwrap.dedent('''Specify categories of test cases ... | be specified more than once.'''))
# Configuration options
group = parser.add_argument_group('Configuration options')
group.add_ar | gument(
'--framework',
metavar='framework-path',
help='The path to LLDB.framework')
group.add_argument(
'--executable',
metavar='executable-path',
help='The path to the lldb executable')
group.add_argument(
'--server',
metavar='server-path',
... |
#!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr
from gnuradio import blocks
from gnuradio import filter
from gnuradio import analog
from gnuradio import audio
from gnuradio.filter import... | d argument here, something like
# "pulse" if using pulse audio or "plughw:0,0".
audio_sink = audio.sink(int(audio_rate))
# now wire it all together
self.connect(src, fm_demod)
self.connect(fm_demod, resamp_filter)
self.connect(resamp_filter, (audio_sink,0))
def main(arg... | raph()
tb.start() # fork thread and return
input('Press Enter to quit: ')
tb.stop()
if __name__ == '__main__':
main(sys.argv[1:])
|
fr | om atlas_web imp | ort app
app.run(debug=True) |
el(logging.INFO)
def get_crt(account_key, csr, acme_dir, log=LOGGER, CA=DEFAULT_CA):
# helper function base64 encode for jose spec
def _b64(b):
return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "")
# parse account key to get public key
log.info("Parsing account key...")
proc =... | UGH IT! It's
only ~200 lines, so it won't take long.
===Example Usage===
python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > sign | ed.crt
===================
===Example Crontab Renewal (once per month)===
0 0 1 * * python /path/to/acme_tiny.py --account-key /path/to/account.key --csr /path/to/domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > /path/to/signed.crt 2>> /var/log/acme_tiny.log... |
-------
def _in_margins ( self, x, y ):
ml = self.margin_left
mb = self.margin_bottom
return xy_in_bounds( x, y, add_rectangles(
self.bounds,
( ml, mb, -(self.margin_right + ml), -(self.margin_top + mb) ) ) )
#----------------------------------------------------... | gc.set_stroke_color( bo | rder_color )
gc.set_line_width( bs )
gc.begin_path()
gc.rect( x + ml + bsh, y + mb + bsh,
dx - ml - mr - bs, dy - mb - mt - bs )
gc.stroke_path()
# Calculate the origin of the image/text box:
te... |
import _plotly_utils.basevalid | ators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bordercolor", parent_name="sankey.hoverlabel", **kwargs
):
super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | e=kwargs.pop("edit_type", "calc"),
**kwargs
)
|
"""App related signal handlers."""
import redis
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from modoboa.admin import models as admin_models
from . import constants
def set_message_limit(instance, key):
"""Store message limit in Redis."""
old_... | .REDIS_PORT,
db=settings.REDIS_QUOTA_DB
)
if instance.message_limit is None | :
# delete existing key
if rclient.hexists(constants.REDIS_HASHNAME, key):
rclient.hdel(constants.REDIS_HASHNAME, key)
return
if old_message_limit is not None:
diff = instance.message_limit - old_message_limit
else:
diff = instance.message_limit
rclient.hi... |
# Copyright 2019 Tecnativa - David
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import SUPERUSER_ID, api
_logger = logging.getLogger(__name__)
def pre_init_hook(cr):
"""Speed up the installation of the module on an existing Odoo instance"""
cr.execute(
""... | ability, [])
m | oves_by_reserved_availability[move.reserved_availability].append(move.id)
for qty, ids in moves_by_reserved_availability.items():
cr.execute(
"UPDATE stock_move SET qty_returnable = %s " "WHERE id IN %s",
(qty, tuple(ids)),
)
moves_no_return_done =... |
# -*- coding:utf8 -*-
from scrapy import Request
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.loader.processors import Join
from scrapy.loader import ItemLoader
from scrapy.selector import HtmlXPathSelector, Selector
from zadolbali.items import StoryItem
cla... | a['date']))
loader.add_xpath('tags', '//div[@class="story"]/div[@class="meta"]/div[@class="tags"]/ul/li/a/@href')
loader.add_xpath('text', 'string(//div[@class="story"]/div[@class="text"])')
loader.add_xpath('likes', 'string(//div[@class="story"]/div[@c | lass="actions"]//div[@class="rating"])')
loader.add_xpath('hrefs', '//div[@class="story"]/div[@class="text"]//a/@href')
loader.add_value('hrefs', '')
loader.add_value('url', str(response.url))
return loader.load_item() |
from vtdb import base_cursor
from vtdb import dbexceptions
write_sql_pattern = re.compile(r'\s*(insert|update|delete)', re.IGNORECASE)
def ascii_lower(string):
"""Lower-case, but only in the ASCII range."""
return string.encode('utf8').lower().decode('utf8')
class VTGateCursorMixin(object):
def connection_l... | tch API will be used.
shards: List of strings.
keyspace_ids: Struct('!Q').packed keyspace IDs.
keyranges: Str keyranges.
writable: True if writable.
as_transaction: True if an executemany call is its own transaction.
single_db: True if sing | le db transaction is needed.
twopc: True if 2-phase commit is needed.
"""
super(VTGateCursor, self).__init__(single_db=single_db, twopc=twopc)
self._conn = connection
self._writable = writable
self.description = None
self.index = None
self.keyspace = keyspace
self.shards = shards
... |
ransform(datan)
data_components_all=nmf.components_
return data_decomp_all,data_components_all
def rgb_comp(arr2d, affine=True):
cmy_cmyk=lambda a:a[:3]*(1.-a[3])+a[3]
rgb_cmy=lambda a:1.-a
rgb_cmyk=lambda a:rgb_cmy(cmy_cmyk(a))
return numpy.array([rgb_cmyk(a) for a in arr2d])
def im... | #ramaninfod['Spectrum 0 index']
ramaninfod['xdata']/=1000.
ramaninfod['ydata']/=1000.#convert to mm
ramaninfod['xshape']= len(np.unique(ramaninfod['xdata']))
ramaninfod['yshape']= len(np.unique(ramaninfod['ydata']))
ramaninfod['dx']= (ramaninfod['xdata'].max()-ramaninfod['xdata'].min())/(ramaninfod['xshape']-1)
ramani... | od['dy']
ntot=nx*ny
ramanreshape=lambda arr: np.reshape(arr, (ramaninfod['xshape'], ramaninfod['yshape'])).T[::-1, ::-1]
ramannewshape=(ramaninfod['yshape'], ramaninfod['xshape'])
image_of_x=ramanreshape(ramaninfod['xdata'])
image_of_y=ramanreshape(ramaninfod['ydata'])
#extent=[ramaninfod['xdata'].max(), r... |
"""Tests for control_flow_ops.py."""
import tensorflow.python.platform
from tensorflow.core.framework import graph_pb2
from tensorflow.python.framework import ops
from tensorflow.python.framework.test_util import TensorFlowTestCase
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import st... | de { name: "root" op: "NoOp" input: "^root/NoOp" input: "^root/NoOp_1"
device: "/task:2" }
""", self._StripGraph(gd))
class ShapeTestCase(T | ensorFlowTestCase):
def testShape(self):
with ops.Graph().as_default():
tensor = tf.constant([1.0, 2.0])
self.assertEquals([2], tensor.get_shape())
self.assertEquals([2],
control_flow_ops.with_dependencies(
[tf.constant(1.0)], tensor).get_shap... |
#!/usr/bin/python3
'''
This is a * sort * of static method but is ugly since the
function is really global and not in the class.
'''
class Book:
num = 0
def __init__(self, price):
self.__price = price
B | ook.num += 1
def printit(self):
print('price is', self.__price)
def setPrice(self, newprice):
self.__price = newprice
def getNumBooks():
return Book.num
# lets create some books...
b1 = Book(14)
b2 = Book(13)
# lets access the static member and the static methods...
print('Book.num (di... | tic method via the instance')
# access the static member through an instance...
print(b1.num)
print(b2.num)
b3 = Book(12)
print(b1.num)
print(b2.num)
print(b3.num)
|
# -*- coding: utf-8 -*-
import bot
import time
"""
load irc/auth/nickserv
nickserv set password hunter2
config set modules.nickserv.enabled True
config set modules.nickserv.ghost True
nickserv register email@do.main
nickserv verify register myaccount c0d3numb3r
nickserv identify
"""
class M_NickServ(bot.Module):
... | word.", ["password"])
self.addcommand(self.setn, "set name",
"Set the NickServ name.", ["[name]"])
def setn(self, context, args):
args.default("name", "")
self.setsetting("name", args.getstr("name"))
return "Set name to: %s" % self.getsetting | ('name')
def setp(self, context, args):
args.default("password", "")
self.setsetting("password", args.getstr("password"))
return "Set password to: %s" % self.getsetting('password')
def name(self):
return self.getsetting("name") or self.server.settings.get(
'server.u... |
#!/usr/bin/env python2.7
# Copyright (c) 2014-2016 Marcello Salvati
#
# 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 3 of the
# License, or (at your option) any later version.
#... | to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
import logging
import sys
import json
import threading
from time import sleep
from core.beefapi import BeefAPI
from core.utils import SystemConfig, shutdown
from plugins.plugin import Plugin
from plugins.Inject import I... | eEF hooks & autoruns modules based on Browser and/or OS type"
version = "0.3"
has_opts = False
def initialize(self, options):
self.options = options
self.ip_address = SystemConfig.getIP(options.interface)
Inject.initialize(self, options)
self.tree_info.append("Mode: {}".format(self.config['BeEFAutorun... |
import logging
from abc import abstractmethod, ABCMeta
from urllib import request
class UrlShortener(meta | class=ABCMeta):
@abstractmethod
def shorten(self, url: str) -> str:
pass
def log(self, url):
logging.info("Short URL: {}".format(url))
class Off(UrlShortener):
def shorten(self, url: str):
return url
class TinyURL(UrlShortener):
def shorten(self, url: str) -> str:
... | _url_shortener(name: str) -> UrlShortener:
if name == "tinyurl":
return TinyURL()
return Off()
|
R), 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_TEMPLATE_DIR,
os.path.join(BASE_TEMPLATE_DIR, 'allauth')],
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug... | tAdapter'
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_LOGOUT_REDIRECT_URL = LOGIN_URL
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': ('django.contrib.auth.'
'password_validation.UserAttributeSimilarityValidator'),
},
{
'NAME':
'django.con... | django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
},
{
'NAME':
'accounts.validators.CharacterTypePasswordValidator'
},
{
'NAME':
'accounts.... |
"""
Base class for all nodes in the scene graph. It is implemented
using the composite pattern.
Responsibilities:
- Hold the relative position to its parent.
- Blit itself on the parent.
- Dirty flag itself to trigger regeneration of surface.
"""
class Component(object):
def __init__(self):
self._position... | f surface(self):
return None
def dirty(self):
self._dirty = True
def _recreate_surface(self):
if self._dirty:
| self._surface = self.surface()
self._dirty = False
"""
Decorator to mark component methods that change the look
of the surface and therefor need to trigger regeneration.
"""
def recreate_surface(function):
def wrapper(self, *args):
self.dirty()
return function(self, *args)
ret... |
from Bio import Entrez
from Bio import SeqIO
from Bio import Seq
from Bio.Alphabet import IUPAC
genomes | = ["Escherichia coli str. K-12 substr. MC4100 complete genome","Escherichia coli Nissle 1917, complete genome","Escherichia coli LY180, complete genome"]
genomes_short = ["K12","Nissle","LY180"]
for n,genome in enumerate(genomes):
Entrez.email = "fake@drexel.edu"
handle = Entrez.esearch(db="nucleotide", term=... | ead(handle)
handle.close()
handle = Entrez.efetch(db="nucleotide", id=records['IdList'][0], rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()
mygenes = ["thrA","mogA","dnaK","nhaA","ksgA"]
output_handle=open("seq"+str(n+1)+".fna","w")
for feature in record... |
from pylons_common.lib.log import create_logger
from pylons_common.lib.utils import pluralize
logger = create_logger('pylons_common.lib.datetime')
from datetime import datetime, timedelta
DATE_FORMAT_ACCEPT = [u'%Y-%m-%d %H:%M:%S', u'%Y-%m-%d %H:%M:%SZ', u'%Y-%m-%d', u'%m-%d-%Y', u'%m/%d/%Y', u'%m.%d.%Y', u'%b %d, %... | elif diff.days < 0 and diff.days >= -7:#Within one week back
return '%s ago' % pluralize(-diff.days, '{0} days', '1 day')
| elif diff.days > 0 and diff.days < 7:#Within one week back
return 'in %s' % pluralize(diff.days, '{0} days', '1 day')
else:
return date.strftime("%b %e, %Y")## on 10/03/1980
def now():
return datetime.utcnow() |
#
# This file contains functions and constants to talk
# to and from a Novation Launchpad via MIDI.
#
# Created by paul for mididings.
from mididings import *
# MEASURES - constants useful for the Pad
side = list(range(0, 8))
longside = list(range(0, 9))
step = 16 # vertical gap on pad
FirstCtrl = 104 # ctrl o... | 11,
7: 12,
}
dorics = {
0: 0,
1: 2,
2: 3,
3: 5,
4: 7,
5: 9,
6: 10,
7: 12,
}
phrygians = {
0: 0,
1: 1,
2: 3,
| 3: 5,
4: 7,
5: 8,
6: 10,
7: 12,
}
# I only use these scales - feel free to add your own!
# Now the same thing, but to feed into Transpose:
Minor = [minors[i] - i for i in side]
MinHarm = [minharms[i] - i for i in side]
Major = [majors[i] - i for i in side]
Doric = [dorics[i] - i for i in side]
Phrygia... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Copyright (C) 2017 Francisco Acosta <francisco.acosta@inria.fr>
# 2017 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# d... | PER_SEC = 1000000
INTERNAL_JITTER = 0.05
EXTERNAL_JITTER = 0.15
class InvalidTimeout(Exception):
pass
def testfunc(child):
child.expect(u"Running test (\\d+) times with (\\d+) distinct sleep times")
RUNS = int(child.match.group(1))
SLEEP_TIMES_NUMOF = int(child.match.group(2))
try:
child | .expect_exact(u"Please hit any key and then ENTER to continue")
child.sendline(u"a")
start_test = time.time()
for m in range(RUNS):
for n in range(SLEEP_TIMES_NUMOF):
child.expect(u"Slept for (\\d+) us \\(expected: (\\d+) us\\) Offset: (-?\\d+) us")
sl... |
from flask import g
import re
from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound
from newparp.model import (
CharacterTag,
Tag,
)
special_char_regex = re.compile("[\\ \\./]+")
underscore_strip_regex = re.compile("^_+|_+$")
def name_from_alias(alias):
# 1. Change to lowercase.
#... | alias in form[tag_type].split(","):
alias = alias.strip()
if alias == "":
continue
name = name_from_alias(alias)
if name == "":
continue
tag_dict[(tag_type, name)] = alias
character_tags = []
used_ids = set()
for (... | and_(
Tag.type == tag_type, Tag.name == name,
)).one()
except NoResultFound:
tag = Tag(type=tag_type, name=name)
g.db.add(tag)
g.db.flush()
tag_id = (tag.synonym_id or tag.id)
# Remember IDs to skip synonyms.
if tag_id in us... |
manager(bulk=False)
def test_removal_through_specified_gfk_related_manager(self, bulk=True):
Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1)
droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1)
... | ple.
self.b1.authors(manager='fun_people').clear()
self.assertQuerysetEqual(
self.b1.authors(manager='boring_people').all(), [
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerysetEqual(
self.... | ), [
],
lambda c: c.first_name,
ordered=False,
)
def test_deconstruct_default(self):
mgr = models.Manager()
as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct()
self.assertFalse(as_manager)
self.assertEqual(mgr_path, 'django.db.... |
def hello | _world():
"Function that says hello."
print("Hello, world!")
| |
#!/usr/bin/env python
from runtest import | TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'abc', """
# DURATION TID FUNCTION
62.202 us [28141] | __cxa_atexit();
[28141] | main() {
[28141] | a() {
[28141] | b() {
[28141] | c() {
0.753 us [28141] |... | 3.005 us [28141] | } /* main */
""")
|
# -*- coding: utf8 -*-
"""
The ``dbs`` module
===================
Contain all functions to access to main si | te db or any sql-lite db, in a secure way
"""
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.au | tomap import automap_base
from sqlalchemy.sql import join
__all__ = ['join', 'create_engine_session', 'auto_map_orm']
def create_engine_session(engine_url, echo=True):
"""
Create a sql session
engine is the rfc1738 compliant url
http://docs.sqlalchemy.org/en/latest/dialects/index.html
:param eng... |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import __version__
from ansible.errors import AnsibleError
from distutils.version import LooseVersion
from operator import eq, ge, gt
from sys import version_info
try:
from __main__ ... | .0.0'
version_tested_max = '2.7.5'
python3_required_version = '2.5.3'
if version_info[0] | == 3 and not ge(LooseVersion(__version__), LooseVersion(python3_required_version)):
raise AnsibleError(('Ansible >= {} is required when using Python 3.\n'
'Either downgrade to Python 2 or update your Ansible version to {}.').format(python3_required_version, python3_required_version))
if not ge(LooseVersion... |
from gasistafelice.rest.views.blocks.base import BlockWithList
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy
#------------------------------------------------------------------------------#
# #
#------------------... | -----#
# #
#------------------------------------------------------------------------------#
# TODO fero CHECK
# THIS IS USEFUL FOR ADD/REMOVE NEW GAS
# def add_new_note(self,request, resource_type, resource_id):
# ... | #title = request.REQUEST.get('title');
# body = request.REQUEST.get('body');
#
# new_comment = Comment(content_object = resource
# ,site = DjangoSite.objects.all()[0]
# ,user = request.user
# ,user_na... |
import unittest
import os
from test.aiml_tests.client import TestClient
from programy.config.brain import BrainFileConfiguration
class BasicTestClient(TestClient):
def __init__(self):
TestClient.__init__(self)
def load_configuration(self, arguments):
super(BasicTestClient, self).load_configur... | th.dirname(__file__))
self.configuration.brain_configuration._person = os.path.dirname(__file__)+"/person.txt"
class PersonAIMLTests(unittest.TestCase):
@classmet | hod
def setUpClass(cls):
PersonAIMLTests.test_client = BasicTestClient()
def test_person(self):
response = PersonAIMLTests.test_client.bot.ask_question("test", "TEST PERSON")
self.assertIsNotNone(response)
self.assertEqual(response, "This is your2 cat")
|
#!/usr/bin/python
########################################################################
# 1 August | 2014
# Patrick Lombard, Centre for Stem Stem Research
# Core Bioinformatics Group
# University of Cambridge
# All right reserve | d.
########################################################################
import pychiptools.call_diff_bind
pychiptools.call_diff_bind.main()
|
from flask import request
from flask_restplus import Resource
from skf.api.security import security_headers, validate_privilege
from skf.api.checklist_category.business import update_checklist_category
from skf.api.checklist_category.serializers import checklist_type_update, message
from skf.api.kb.parsers import autho... | mport log, val_num, val_alpha, val_alpha_num, val_alpha_num_special
ns = api.namespace('checklist_category', description='Operations related to checklist items')
@ns.route('/update/<int:id>')
@api.doc(params={'id': 'The checklist category id'})
@api.response(404, 'Validation error', message)
class ChecklistCategoryUp... | checklist type.
* Privileges required: **edit**
"""
data = request.json
val_num(id)
val_alpha_num_special(data.get('name'))
val_alpha_num_special(data.get('description'))
validate_privilege(self, 'edit')
result = update_checklist_category(id, data)
... |
)`
#
class ApplyResult(object):
_worker_lost = None
_write_to = None
_scheduled_for = None
def __init__(self, cache, callback, accept_callback=None,
timeout_callback=None, error_callback=None, soft_timeout=None,
timeout=None, lost_worker_timeout=LOST_WORKER_TIMEOUT,
... | self._job = next(job_counter)
self._cache = cache
self._items = deque()
self._ | index = 0
self._length = None
self._ready = False
self._unsorted = {}
self._worker_pids = []
self._lost_worker_timeout = lost_worker_timeout
cache[self._job] = self
def __iter__(self):
return self
def next(self, timeout=None):
with self._cond:
... |
# coding: utf-8
# numpy_utils for Intro to Data Science with Python
# Author: Kat Chuang
# Created: Nov 2014
# --------------------------------------
import numpy
## Stage 2 begin
fieldNames = ['', 'id', 'priceLabel', 'name','brandId', 'brandName', 'imageLink',
'desc', 'vendor', 'patterned', 'materi... | yle.use('ggplot')
def plot_all_bars(prices_in_float, exported_figure_filename):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
| prices = list(map(int, prices_in_float))
X = numpy.arange(len(prices))
width = 0.25
ax.bar(X+width, prices, width)
ax.set_xlim([0, 5055])
fig.savefig(exported_figure_filename)
def create_chart_for_embed(sample, title):
prices = sorted(map(int, sample))
x_axis_ticks = list( range(len(sample... |
[dict(aa=1), dict(aa=3)])
def testCorrelated(self):
db = self.connect()
db.define_table(
"t1", Field("aa", "integer"), Field("bb"), Field("mark", "integer")
)
db.define_table("t2", Field("aa", "integer"), Field("cc"))
db.define_table("t3", Field("aa", "integer")... | (result[idx]["tmp"]["bb"], val[1])
# SQLite does not support aliasing target table in UPDATE/DELETE
# MyS | QL does not support subqueries with uncorrelated references
# to target table
class TestAddMethod(DALtest):
def testRun(self):
db = self.connect()
db.define_table("tt", Field("aa"))
@db.tt.add_method.all
def select_all(table, orderby=None):
return table._db(tab... |
"""Placeholder."""
import numpy as np
def rgb_to_hsi(im):
"""Convert to HSI the RGB pixels in im.
Adapted from
https://en.w | ikipedia.org/wiki/HSL_and_HSV#Hue_and_chroma.
"""
im = np.moveaxis(im, -1, 0)
if len(im) not in (3, 4):
raise ValueError("Expected 3-channel RGB or 4-channel RGBA image;"
" received a {}-channel image".format(len(im)))
im = im[:3]
hues = (np.arctan2(3**0.5 * (im[1] ... | im.mean(0)
saturations = np.where(
intensities, 1 - im.min(0) / np.maximum(intensities, 1e-10), 0)
return np.stack([hues, saturations, intensities], -1)
|
import LNdigitalIO
def switch_pressed(event):
event.chip.output_pins[event.pin_num].turn_on()
def switch_unpressed(event):
event.chip.output_pins[e | vent.pin_num].turn_off()
if __name__ == "__main__":
LNdigital = LNdigitalIO.LNdigitals()
listener = LNdigitalIO.InputEventListener(chip=LNdigital)
for i in range(4):
listener.register(i, LN | digitalIO.IODIR_ON, switch_pressed)
listener.register(i, LNdigitalIO.IODIR_OFF, switch_unpressed)
listener.activate()
|
leFactory
class AssignQuestionViewTest(BaseTest):
def setUp(self):
self.client = Client()
self.user = self.create_user(org="WHO")
self.region = None
self.assign('can_edit_questionnaire', self.user)
self.client.login(username=self.user.username, password='pass')
se... | , region="ASEAN",
org="WHO")
self.assign('can_edit_questionnaire', user_not_in_same_region)
self.client.logout()
self.client.login(username='asian_chic', password='pass')
response = self.client.get(self.url)
self.assertRedirects... | ccounts/login/?next=%s' % quote(self.url))
response = self.client.post(self.url)
self.assertRedirects(response, expected_url='/accounts/login/?next=%s' % quote(self.url))
def test_GET_with_hide_param_puts_list_of_only_unused_questions_in_context(self):
question1 = Question.objects.create(te... |
Invalid 1 == foo
==
Invalid 2 ==
== Invalid 3
==
==
Invalid 4
==
== Invalid | 5
foo ==
"""
expected = [
"Section with trailing spaces",
]
result = get_anchors(get_section_headings(snippet), pretty=True)
assert result == expect | ed
class test_ensure_flagged:
def test_add(self):
wikicode = mwparserfromhell.parse("[[foo]]")
link = wikicode.nodes[0]
flag = ensure_flagged_by_template(wikicode, link, "bar")
assert str(wikicode) == "[[foo]]{{bar}}"
def test_preserve(self):
wikicode = mwparserfromhell... |
dio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witho... | L = min(L1, L2)
#if True or abs(L1-L2) | > 1:
if False:
sys.stderr.write('delta = %2d: ntaps = %d interp = %d ilen = %d\n' % (L2 - L1, ntaps, interp, ilen))
#sys.stderr.write(' len(result_data) = %d len(expected_result) = %d\n' %
# (len(result_data), ... |
mpList = self.__loadLocal(cfg, lItem)
if tmpList and len(tmpList.rules) > 0:
successfullyScraped = self.__loadRemote(tmpList, lItem)
# autoselect
if tmpList and tmpList.skill.find('autoselect') != -1 and len(tmpList.items) == 1:
m = tmpList.items[0]
... | ame = filename
if filename.find('/') > -1:
srchFilename = srchFilename.split('/')[1]
| try:
cfg = findInSubdirectory(srchFilename, common.Paths.modulesDir)
except:
try:
cfg = findInSubdirectory(srchFilename, common.Paths.favouritesFolder)
except:
tr... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_mapcalc.py
------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
**********************************... | author__ = 'Médéric Ribreux'
__date__ = 'February 2016'
__copyright__ | = '(C) 2016, Médéric Ribreux'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
def checkParameterValuesBeforeExecuting(alg, parameters, context):
""" Verify if we have the right parameters """
if (alg.parameterAsString(parameters, 'expression', conte... |
# -*-coding:UTF-8 -*
import sqlite3 as sql
import json
from time import time, strftime
import settings
import logging as lgn
lgn.basicConfig(filename = '/db/db.log',level=lgn.DEBUG,\
format='%(asctime)s %(message)s')
def logit(string,*level):
if(len(level) == 0):
lgn.info(string)
else:
if(... | conn.commit()
#now let's delete all the listings older than max age
max_age = time() - settings.n_days_before_del * 86400
c.execute('''delete from listings where date_added <= ?''',(max_age,))
conn.commit()
def get_conn():
conn = sql. | connect("/db/spider_nest.db")
c = conn.cursor()
c.execute('''PRAGMA foreign_keys = ON''')
return conn,c
def add_error_listings(site,conn,c):
siteid = c.execute('select id from websites where url = ?',(site,)).fetchone()
searches = c.execute('select id from searches where websiteid = ?',siteid).fetc... |
t is None:
return None
if self.port:
return f"{self.host}:{self.port}"
return self.host
@property
def url(self) -> str:
"""
Convert self into a url
This function should more or less round-trip with :func:`.parse_url`. The
returned url may... | ='http', host='google.com', port=None, path='/mail/', ...)
print( urllib3.util.parse_url('google.com:80'))
# Url(scheme=None, host='google.com', port=80, path=None, ...)
print( urllib3.util.parse_url('/foo?bar'))
# Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
... | + url
scheme: Optional[str]
authority: Optional[str]
auth: Optional[str]
host: Optional[str]
port: Optional[str]
port_int: Optional[int]
path: Optional[str]
query: Optional[str]
fragment: Optional[str]
try:
scheme, authority, path, query, fragment = _URI_RE.match(url).... |
#!/usr/bin/env python
import argparse
import datetime
import os
import re
import requests
import subprocess
import sys
import time
import xively
DEBUG = os.environ["DEBUG"] or false
def read_temperature(from_file):
if DEBUG:
print "Reading temperature from file: %s" % from_file
temperature = None
with op... | m
def run():
parser = argparse.ArgumentParser(description = 'Push a metric to Xively')
parser.add_argument('--feed', type=str, required=True, help='your Xively feed ID')
parser.add_argument('--key', type=str, required=True, help='your Xively API key')
parser.add_argument('--name', type=str, default='temperatur... | ream name')
parser.add_argument('--file', type=str, required=True, help='the file from which to read the temperature')
args = parser.parse_args()
api = xively.XivelyAPIClient(args.key)
feed = api.feeds.get(args.feed)
datastream = get_datastream(feed, args.name)
datastream.max_value = None
datastream.mi... |
# Copyright 2015 CloudFounders NV
#
# 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 writ... | nse is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language | governing permissions and
# limitations under the License.
"""
This package contains Linux OS distribution extensions
"""
|
"""db migration
Revision ID: 373a21295ab
Revises: 21f5b2d3905d
Create Date: 2015-05-05 15:42:33.474470
"""
# revision identifiers, used by Alembic.
revision = '373a21295ab'
down_revision = '21f5b2d3905d'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.dr... | onupdate=sa.func.now(), nullable=False))
def downgrade():
op.drop_table('items')
op.create_table('items',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String(255), nullable=False),
sa.Column('is_bought', sa.Boolean, default=False, nullable=False),
sa.Col... | a.func.now()))
|
from ..library.base import number_t | o_list
def solve(bound: int=100):
maximal = 0
for a in range(bound):
for b in range(bound):
sum_digits = sum(number_to_list(a ** b))
if sum_digits > maximal:
maximal = sum_digits
return maxima | l
|
# (C) Copyright 2011 Nuxeo SAS <http://nuxeo.com>
# Author: bdelbosc@nuxeo.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it wil... | onitrored server chart | s."""
charts = []
Plugins = MonitorPlugins()
Plugins.registerPlugins()
Plugins.configure(self.getMonitorConfig(host))
for plugin in Plugins.MONITORS.values():
image_path = ('%s_%s' % (host, plugin.name)).replace("\\", "/")
charts.append((plugin.name, imag... |
# -*- enco | ding: utf-8 -*-
# Module iainfgen
from numpy import *
def iainfgen(f, Iab):
from iaunion import iaunion
from iadil import iadil
from ianeg import ianeg
A, Bc = Iab
y = iaunion( iadil(f, A), iadil( ianeg(f), Bc))
return y | |
tqueryGraph(self,graph=None):
self.queryGraph = graph
def setfullGraph(self,graph=None):
self.fullGraph = graph
def setexcludeAttic(self,state):
self.excludeAttic = state
def setmarkdownComments(self,state):
self.markdown = state
def doQuer... | eIncludes","inverseOf","supersedes","supersededBy","isPartOf"]
if not out:
return
writer = csv.writer( | out,quoting=csv.QUOTE_ALL,lineterminator='\n')
if header:
writer.writerow(cols)
return
if not graph:
graph = self.queryGraph
if term == None or graph == None:
return
row = [str(term)]
row.append(self.graphValueToCSV(subject=term,pre... |
transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase c... | s3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_co | nst=True)
## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application.h (module 'network'): void ns3::Application::SetNode(ns3... |
device_path, as_root=False): # pylint: disable=W0613
return self.mock_content
def GetProp(self, property_name):
return self.system_properties[property_name]
def SetProp(self, property_name, property_value):
self.system_properties[property_name] = property_value
class CloudStorageModuleStub(object):... | path, bucket=None):
remote_path = os.path.basename(local_path)
if bucket:
return CloudStor | ageModuleStub.GetHelper(self, bucket, remote_path,
local_path, True)
result = CloudStorageModuleStub.GetHelper(
self, self.PUBLIC_BUCKET, remote_path, local_path, True)
if not result:
result = CloudStorageModuleStub.GetHelper(
self, self.PART... |
mexit.py
#
# Display the exit_reason and its statistics of each vm exit
# for all vcpus of all virtual machines. For example:
# $./kvmexit.py
# PID TID KVM_EXIT_REASON COUNT
# 1273551 1273568 EXIT_REASON_MSR_WRITE 6
# 1274253 1274261 EXIT_REASON_EXTERNAL_INTERRUPT ... | id meets current pcpu_cache_array for the first time, save it.
cache_p->cache_pid_tgid = cur_pid_tgid;
bpf_probe_read(&cache_p->cache_exit_ct, sizeof(*tmp_info), tmp_info);
}
return 0;
}
return 0;
}
"""
# format output
exit_reasons = (
"EXCEPTION_NMI",
"EXTERNAL... | "N/A",
"HLT",
"INVD",
"INVLPG",
"RDPMC",
"RDTSC",
"N/A",
"VMCALL",
"VMCLEAR",
"VMLAUNCH",
"VMPTRLD",
"VMPTRST",
"VMREAD",
"VMRESUME",
"VMWRITE",
"VMOFF",
"VMON",
"CR_ACCESS",
"DR_ACCESS",
"IO_INSTRUCTION",
"MSR_READ",
"MSR_WRITE",
... |
re, clear_current)
return preset
def on_preset_stored(self, *args, **kwargs):
kwargs['backend'] = self
self.emit('on_preset_stored', *args, **kwargs)
def on_preset_active(self, instance, value, **kwargs):
self.emit('on_preset_active', backend=self, preset=instance, value=value)
... | prop = kwargs.get('property')
keys = kwargs.get('keys')
if keys is None:
keys = range(len(value))
feedback_prop = '{}s'.format(prop.name.split('_control')[0])
elock = self.emission_lock(feedback_prop)
if elock.held:
return
## | TODO: This is an internal implementation in python-dispatch and
## is subject to future changes.
aio_lock = elock.aio_locks.get(id(self.event_loop))
if aio_lock is not None and aio_lock.locked():
return
if value == getattr(self, feedback_prop):
return
... |
if child_nodes:
result = dict([
(child.tagName, self._parse_xml_node(child))
for child in child_nodes
])
else:
result = self.get_xml_text(node.childNodes)
return result
class CodebaseHQ(HostingService):
... | ss. We need to store all of this.
Args:
username (unicode):
The username to authorize.
password (unicode):
The API token used as a password.
| credentials (dict):
Additional credentials from the authentication form.
*args (tuple):
Extra unused positional arguments.
**kwargs (dict):
Extra unused keyword arguments.
Raises:
reviewboard.hostingsvcs.errors.Autho... |
tables for the closed world universe given by the identifier
print "Destroyed Close World Universe %s ( in SQLite database %s)"%(self.identifier,home)
db.commit()
c.close()
db.close()
os.remove(os.path.join(home,self.identifier))
def EscapeQuotes(self,qstr):
"""
... | gs.append("%s="%(tableName and '%s.object'%tableName or 'object')+"%s")
paramStrings.append(self.normaliz | eTerm(o.identifier))
else:
clauseStrings.append("%s="%(tableName and '%s.object'%tableName or 'object')+"%s")
paramStrings.append(self.normalizeTerm(o))
return '('+ ' or '.join(clauseStrings) + ')', paramStrings
elif isinstance(obj,(QuotedGraph... |
from __future__ import (absolute_import, division, print_function)
import unittest
import os
import testhelpers
from mantid.kernel import (ConfigService, ConfigServiceImpl, config,
std_vector_str, FacilityInfo, InstrumentInfo)
class ConfigServiceTest(unittest.TestCase):
__dirs_to_rm =... | testhelpers.assertRaisesNothing(self, config.setFileLogLevel, 4)
testhelpers.assertRaisesNothing(self, config.setConsoleLogLevel, 4)
def _setup_test_areas(self):
"""Create a new data search path string
"""
self.__init_dir_list = config['datasearch.directories']
# Set ne... | ectory so that I know where it is
test_path = os.path.join(os.getcwd(), "tmp")
try:
os.mkdir(test_path)
self.__dirs_to_rm.append(test_path)
except OSError:
pass
test_path_two = os.path.join(os.getcwd(), "tmp_2")
try:
os.mkdir(test_... |
# Wasp: Discrete Design with Grasshopper plug-in (GPL) initiated by Andrea Rossi
#
# This file is part of Wasp.
#
# Copyright (c) 2017, Andrea Rossi <a.rossi.andrea@gmail.com>
# Wasp is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the ... | ische Universitt Darmstadt
#########################################################################
## COMPONENT I | NFO ##
#########################################################################
"""
Export Wasp information for DisCo VR software
-
Provided by Wasp 0.5
Args:
NAME: Rule group name. It will be used to activate/deactivate the rules contained in DisCo
GR: Rule grammars to b... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
d | ef update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "choimirai.com",
"name": "Django Tutorial"
| }
)
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "example.com",
"name": "example.com"
}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.