prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
modules
import pygame
from pygame.locals import *
#see if we can load more than standard BMP
if not pygame.image.get_extended():
raise SystemExit("Sorry, extended image module r | equired")
#game constants
MAX_SHOTS = 2 #most player bullets onscreen
ALIEN_ODDS = 22 #chances a new alien appears
BOMB_ODDS = 60 #chances a new bomb will drop
ALIEN_RELOAD | = 12 #frames between new aliens
SCREENRECT = Rect(0, 0, 640, 480)
SCORE = 0
main_dir = os.path.split(os.path.abspath(__file__))[0]
def load_image(file):
"loads an image, prepares it for play"
file = os.path.join(main_dir, 'data', file)
try:
surface = pygame.image.load... |
turned: always
type: str
sample: 'CREATE INDEX CONCURRENTLY foo_idx ON test_table USING BTREE (id)'
storage_params:
description: Index storage parameters.
returned: always
type: list
sample: [ "fillfactor=90" ]
valid:
description: Index validity.
returned: always
type: bool
sample: true
'''
import ... | sibleModule(
ar | gument_spec=argument_spec,
supports_check_mode=True,
)
if not HAS_PSYCOPG2:
module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
idxname = module.params["idxname"]
state = module.params["state"]
concurrent = module.params["concurrent"]
table = modu... |
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('morphology', parent_package, top_... | ort setup
setup(maintai | ner='scikit-image Developers',
author='Damian Eads',
maintainer_email='scikit-image@googlegroups.com',
description='Morphology Wrapper',
url='https://github.com/scikit-image/scikit-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todi... |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman --<mozman@gmx.at>
# Purpose: test svg element
# Created: 25.09.2010
# Copyr | ight (C) 2010, Manfred Moitzi
# License: MIT License
import sys
import unittest
from svgwrite.container import SVG, Symbol
class TestSVG(unittest.TestCase):
def test_constructor(self):
svg = SVG(insert=(10,20), size=(100,200))
self.assertTrue(isinstance(svg, Symbol))
self.assertEqual(svg.... | subsvg = SVG(id='subsvg')
svg.add(subsvg)
self.assertEqual(svg.tostring(), '<svg id="svg"><defs /><svg id="subsvg"><defs /></svg></svg>')
if __name__=='__main__':
unittest.main()
|
from __fu | ture__ import absolute_import
from .dev import Dev # noqa
try:
from .production import Prod | uction # noqa
except ImportError:
pass
|
#!/u | sr/bin/env python
# -*- coding: utf-8 -*-
from .randomproxy im | port ProxyDownloaderMiddleware
|
from flask import Flask
import config
from db import db_from_config
from address_deduper.views import init_views
from address_normalizer.deduping.near_duplicates import *
def create_app(env, **kw):
app = Flask(__name__)
specified_config = kw.g | et('config')
if specified_config:
__import__('address_normalizer.' + specified_config)
config.current_env = env
conf = config.valid_configs.get(env)
if not conf:
sys.exit('Invalid config, choices are [%s]' % ','.join(valid_configs.keys()))
app.config.from_object(conf)
app.u... | init_views(app)
return app
|
import base64
import pathlib
import pickle
import textwrap
from docutils.nodes import FixedTextElement, General, SkipNode
from uqbar.book.extensions import Extension
from uqbar.strings import normalize
from supriya.ext import websafe_audio
from supriya.io import Player
class RenderExtension(Extension):
template... | ).decode()
)
)
node = self.render_block(code, code)
return [node]
@classmethod
def render(cls, node, output_path):
output_path.mkdir(exist_ok=True)
renderable, render_kwargs = pickle.loads(
base64.b64decode("".join(node[0].split()))
... | safe_audio(
renderable.__render__(render_directory_path=output_path, **render_kwargs)
)
@staticmethod
def visit_block_html(self, node):
absolute_file_path = RenderExtension.render(
node, pathlib.Path(self.builder.outdir) / "_images"
)
relative_file_path =... |
__doc__ = """Random number array generators for numarray.
This package was ported to numarray from Numeric's RandomA | rray and
provides functions to generat | e numarray of random numbers.
"""
from RandomArray2 import *
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-01-29 16:08
from __ | future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0013_auto_20181002_1939'),
]
operations = [
migrations.CreateModel(
... | True, primary_key=True, serialize=False, verbose_name='ID')),
('value', django.contrib.postgres.fields.ArrayField(base_field=models.FloatField(), size=None)),
('key', models.CharField(help_text='Metric Key', max_length=30)),
('mjd', models.FloatField(help_text='MJD', null... |
#20140125 Cui.Yingyun
#Convert C style code to Char style
import sys
file = sys.stdin
if len(sys.argv) > 1:
file = open(s | ys.argv[1])
else:
print "Input argument which specify shader program"
sys.exit(0);
lines = file.readlines()
print '\"\\'
for line in lines[:-1]:
print line.rstrip() + '\\n\\'
print lines[-1].rstrip( | ) + '\\n\"'
file.close()
|
#************************************************************************
# Codelet Tuning Infrastructure
# Copyright (C) 2010-2015 Intel Corporation, CEA, GENCI, and UVSQ
#
# 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
# th... | .plugin_uid)},
db,
"category",
fields=["entry_info.entry_uid", "category.name"]
| )
for r in result:
print r[0] + ":" + r[1]
#---------------------------------------------------------------------------
# By pass the authentification system
# Needed by the doc plugin
def check_passwd(self):
return True
#----------------------... |
response.title = settings.title
response.subtitle = settings.subtitle
re | sponse.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
(T('Index'),URL('default','index')==URL(),URL('default','index'),[]),
(T('Video'),URL('default','video')==URL(),URL('default','video'),[])... | (T('Info'), False, "http://www.oarstack.com/2015/04/oarstack-analysis/", []),
]
response.google_analytics_id="UA-52135133-2"
|
def vault(args):
parser = argparse.ArgumentPar | ser()
subparsers = parser.add_subparsers()
if __name__ == "__main_ | _":
vault(sys.argv)
|
# -*- coding: utf-8 -*-
#
# phaxio-python documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 8 20:17:15 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | io-pythondoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersiz | e': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (s... |
# Copyright 2013 dotCloud 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 t... | KeyError, Va | lueError) as e:
# Likely missing new Docker config file or it's in an
# unknown format, continue to attempt to read old location
# and format.
log.debug(e)
log.debug("Attempting to parse legacy auth file format")
try:
data = []
with open(config_file) as f:
... |
def foo(a, b=None) | :
pas | s
foo("a", "b")
foo("a")
foo("a", b="b")
foo("a", None)
|
edFloatField,
EncryptedEmailField,
EncryptedBooleanField,
)
from keyczar import keyczar, readers
# Test class that encapsulates some Keyczar functions.
# Requirements are to implement __init__, decrypt(), encrypt()
class TestCrypter(object):
def __init__(self, keyname, *args, **kwargs):
self.keyd... | t_unicode_encrypted(self):
plaintext = u'Oh hi, test reader! 🐱'
model = TestModel()
model.char = plaintext
m | odel.save()
ciphertext = self.get_db_value('char', model.id)
self.assertNotEqual(plaintext, ciphertext)
self.assertTrue('test' not in ciphertext)
fresh_model = TestModel.objects.get(id=model.id)
self.assertEqual(fresh_model.char, plaintext)
def test_short_char_field_encry... |
# -*- coding: UTF-8 -*-
'''
series9 scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import re,traceback,urllib,urlparse
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules i... | url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
url = urllib.urlencode(url)
return url
except:
failure = traceback.format_exc()
log_utils.log('Series9 - Exception: \n' + str(failure))
| return
def searchShow(self, title, season, aliases, headers):
try:
title = cleantitle.normalize(title)
search = '%s Season %01d' % (title, int(season))
url = urlparse.urljoin(self.base_link, self.search_link % cleantitle.geturl(search))
r = client.r... |
#!/usr/bin/env python
#
# Copyright (c) 2011, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# n... | > met | rics[:])
# o = open('graph.dot', 'w')
# print >>o, plasm.viz()
# o.close()
# print "\n", plasm.viz(), "\n"
return (plasm, metrics)
def test_st(niter, n_nodes):
(plasm, metrics) = makeplasm(n_nodes)
#sched = ecto.Scheduler(plasm)
#sched.execute(niter)
sched = ecto.Scheduler(plas... |
# -*- coding: utf-8 -*-
# This file is a part of MediaDrop (http://www.mediadrop.net),
# Copyright 2009-2014 MediaDrop contributors
# For the exact contribution history, see the git revision log.
# The source code in this file is dual licensed under the MIT license or
# the GPLv3 or (at your option) any later version.
... | .query_result_proxy import StaticQuery
from mediadrop.lib.test.pythonic_testcase import * |
class StaticQueryTest(PythonicTestCase):
def setUp(self):
self.query = StaticQuery([1, 2, 3, 4, 5])
def test_can_return_all_items(self):
assert_equals([1, 2, 3, 4, 5], self.query.all())
def test_can_return_all_items_with_iteration(self):
assert_equals([1, 2, 3, 4, 5], li... |
#!/us | r/bin/python35
def add(x, y):
return x + y
def dec(x, y):
return x - y
def div(x, y):
if y == 0:
return 0
return x / y
def mult(x, y):
return x * y
if __name__ == | '__main__':
print('Module: Calc')
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-11-01 20:02
from __future__ import unicode_literals
f | rom django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('phone_numbers', '0001_initial'),
('sims', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='phonenum... | gnKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='phone_numbers', to='sims.Sim'),
),
]
|
# -*- coding: utf-8 -*-
"""
**********
Exceptions
**********
Base exceptions and errors for NetworkX.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult(dschult@colgate.edu)\nLoïc Séguin-C. <loicseguin@gmail.com>"""
# Copyright (C) 2004-2016 by
# Aric Hagberg <hagberg... | n):
"""Base class for exceptions in NetworkX."""
class NetworkXError(NetworkXException):
"""Exception for a serious error in NetworkX"""
class NetworkXPointlessConcept(NetworkXException):
"""Harary, F. and Read, R. "Is the Null Graph a Pointless Concept?"
In Graphs and Combinatorics Conference, Geor | ge Washington University.
New York: Springer-Verlag, 1973.
"""
class NetworkXAlgorithmError(NetworkXException):
"""Exception for unexpected termination of algorithms."""
class NetworkXUnfeasible(NetworkXAlgorithmError):
"""Exception raised by algorithms trying to solve a problem
instance that has no feasi... |
na | me = "hello_world"
version = "1.0.0"
authors = [
"ajohns"
]
description = \
"""
Python-based hello world example package.
"""
tools = [
"hello"
]
requires = [
"python"
]
uuid = "examples.hello_world_py"
build_command = 'python {root}/build.py {install}'
def commands():
env.PYTHONPATH... | |
from netfields import InetAddressField, CidrAddressField
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from nodeshot.core.base.models import BaseAccessLevel
from ..managers import NetAccessLevelM... | code__(self):
return '%s: %s' % (self.protocol, self.address)
def clean(self, *args, **kwargs):
""" TODO """
# netaddr.IPAddress('10.40.2.1') in netaddr.IPNetwork('10.40.0.0/24')
pass
def save(self, *args, **kwargs):
"""
Determines ip protocol version automatica... | ss.version
# save
super(Ip, self).save(*args, **kwargs)
# TODO: do we really need this?
# save shortcut on interfaces
#ip_cached_list = self.interface.ip_addresses
## if not present in interface shorctus add it to the list
#if str(self.address) not in ip_cached_l... |
def ternary(cond1, result1, result2):
if cond1:
return result1
e | lse:
| return result2
|
.7]],
... evidence=[('X', 0)],
... evidence_card=2)
>>> z_trans_cpd = TabularCPD(('Z', 1), 2, [[0.4, 0.7],
... [0.6, 0.3]],
... evidence=[('Z', 0)],
... ... |
Parameters:
----------
variables: list
list of variables for which y | ou want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
Examples:
--------
>>> from pgmpy.factors import TabularCPD
>>> from pgmpy.models import DynamicBayesianNetwork as DBN
>>... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | arameters.
:type parameters: ``dict``
"""
if not trigger_type_ref:
| return None
if trigger_type_ref not in SYSTEM_TRIGGER_TYPES:
# Not a system trigger, skip validation for now
return None
parameters_schema = SYSTEM_TRIGGER_TYPES[trigger_type_ref]['parameters_schema']
cleaned = util_schema.validate(instance=parameters, schema=parameters_schema,
... |
#!/usr/bin/env python
"""
Extract minor planet orbital elements and discovery dates to json.
Orbital elements are extracted from the file MPCORB.DAT:
https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT
Discovery dates are extracted from the file NumberedMPs.txt:
https://minorplanetcenter.net/iau/lists/NumberedMPs.txt
... | dt = dt - datetime(2000, 1, 1)
return dt.days + (dt.seconds + dt.microseconds / 1000000) / 86400 + 2451544.5
# Packed date to Datetime
def pd2dt(pd):
y = int(str(int(pd[0], 36)) + pd[1:3])
m = int(pd[3], 36)
d = int(pd[4], 36)
retur | n datetime(y, m, d)
# Packed to Julian date
def pd2jd(pd):
dt = pd2dt(pd)
return dt2jd(dt)
def main(argv):
# Parse argumanets
parser = argparse.ArgumentParser(description='Parse orbital and discovery data to json.')
parser.add_argument('amount', metavar='N', type=int, nargs='?', help='maximum numb... |
# -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | OrdreRelacherGouvernail(matelot, navire)
ordres.append(relacher)
| ordres.append(self.revenir_affectation(matelot))
self.ajouter_ordres(matelot, ordres)
def crier_ordres(self, personnage):
"""On fait crier l'ordre au personnage."""
msg = "{} s'écrie : relâchez la barre !".format(
personnage.distinction_audible)
self.navire.envo... |
from trifle.server.views.frontend import frontend
f | rom trifle.server.views.api import api
from trifle.server.views.monitor impor | t monitor
from trifle.server.views.configure import configure
|
"""
Mail.ru OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/mailru.html
"""
from hashlib import md5
from social.p3 import unquote
from social.backends.oauth import BaseOAuth2
class MailruOAuth2(BaseOAuth2):
"""Mail.ru authentication backend"""
name = 'mailru-oauth2'
ID_KEY = 'uid'... | 'fullname': fullname,
'first_name': first_name,
'last_name': last_name}
def user_data(self, access_token, *args, **kwargs):
"""Return user data from Mail.ru REST API"""
key, secret = self.get_key_and_secret()
data = {'method': 'users.getInfo',
... | 'session_key': access_token,
'app_id': key,
'secure': '1'}
param_list = sorted(list(item + '=' + data[item] for item in data))
data['sig'] = md5(
(''.join(param_list) + secret).encode('utf-8')
).hexdigest()
return self.get_json('http://www.a... |
# Halley provider definition
# Mandatory imports
from .Provider import Provider
from rfeed import *
# Optional imports
import requests, mimetypes, logging
logging.basicConfig(level=logging.INFO)
from bs4 import BeautifulSoup as bs
# Halley provider class inherit from the Provider one defined in providers/Provider.py... | n Item(
title = document["Oggetto Atto"],
link = single_page_url,
description = document["Oggetto Atto"],
pubDate = self.format_datetime(document.get("Data Atto") or document.get("Data Inizio Pubblicazione")),
guid = Guid(single_page_url),
categori... | "item-category-uid",
category = "%s/%s" % (document["Anno di Pubblicazione"], document["Numero Pubblicazione"])
),
Category(
domain = self.specs_base_url + "#" + "item-category-type",
category = document["Tip... |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
Swagger model
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMa | p: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'kind': 'str',
'api_version': 'str',
'metadata': 'V1ListMeta',
'items': 'list[V1PersistentVolumeClaim]'
}
se... |
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
os.environ['DJANGO_SETTINGS_MODUL... | Project.objects.filter(code__in=self.projects)
def get_filetype(self, name):
try:
return Format.objects.get(name=name)
| except Format.DoesNotExist:
raise CommandError("Unrecognized filetype '%s'" % name)
def handle_all(self, **options):
filetype = self.get_filetype(options["filetype"])
from_filetype = (
options["from_filetype"]
and self.get_filetype(options["from_filetype"])
... |
#!/usr/bin/env python
"""
MaTiSSe.py, Markdown To Impressive Scientific Slides
"""
from __future__ import print_function
import argparse
import os
import sys
from matisse_config import MatisseConfig
from presentation import Presentation
__appname__ = "MaTiSSe.py"
__description__ = "MaTiSSe.py, Markdown To Impressive S... |
cliparser.add_argument('--print-options', required=False, action='store_true', default=None, help='Print the available options for each presentation element')
cliparser.add_ | argument('--print-highlight-styles', required=False, action='store_true', default=None, help='Print the available highlight.js style (default github.css)')
cliparser.add_argument('--print-themes', required=False, action='store_true', default=None, help='Print the list of the builtin themes')
cliparser.add_argument(... |
ve(*args, **kwargs)
def is_english(self):
if self.language == ENGLISH:
return True
return False
def is_spanish(self):
if self.language == SPANISH:
return True
return False
def is_vietnamese(self):
if self.language == VIETNAMESE:
... | vote_id):
status = "RETRIEVE_QUICK_INFO_FOUND_WITH_OFFICE_WE_VOTE_ID"
quick_info_on_stage = QuickInfo.objects.get(
contest_office_we_vote_id=contest_office_we_vote_id)
quick_info_id = quick_info_on_stage.id
success = True
el... | tus = "RETRIEVE_QUICK_INFO_FOUND_WITH_CANDIDATE_WE_VOTE_ID"
quick_info_on_stage = QuickInfo.objects.get(
candidate_campaign_we_vote_id=candidate_we_vote_id)
quick_info_id = quick_info_on_stage.id
success = True
elif positive_value_exists(po... |
# -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2020 PyBuilder Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# y | ou may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WAR... | ations under the License.
from unittest import TestCase
from pybuilder.graph_utils import Graph
class GraphUtilsTests(TestCase):
def test_should_find_trivial_cycle_in_graph_when_there_is_one(self):
graph_with_trivial_cycle = Graph({"a": "a"})
self.assertIsNotNone(graph_with_trivial_cycle.assert_... |
#!/usr/bin/env python
from __future__ import division
import math
import optparse
import sys
#-------------------------------------------------------------------------------
# Illumicone simulator, based on code from: https://github.com/zestyping/openpixelcontrol
NUM_STRINGS = 48
PIXELS_PER_STRING = 100
SCALE = 7 ... | Use 7 for cone_med, 10 for cone_lg.
print "scale: " + str(SCALE)
PIXEL_DISTANCE = SCALE / PIXELS_PER_STRING
print "\npixel distance: " + s | tr(PIXEL_DISTANCE)
HEIGHT = math.sqrt(SCALE * SCALE / 2)
print "\ncone height: " + str(HEIGHT)
MIN_RADIUS = HEIGHT * .1 # i.e. the radius of the little circle on top
print "\nmin radius: " + str(MIN_RADIUS)
#-------------------------------------------------------------------------------
result = ['[']
theta = 0
for s... |
# coding=utf-8
from __future__ import unicode_literals
from collections import OrderedDict
from .. import BaseProvider
localized = True
class Provider(BaseProvider):
all_colors = OrderedDict((
("AliceBlue", "#F0F8FF"),
("AntiqueWhite", "#FAEBD7"),
("Aqua", "#00FFFF"),
("Aquamarin... | ("PaleGoldenRod", "#EEE8AA"),
("PaleGreen", "#98FB98"),
("PaleTurquoise", "#AFEEEE"),
("PaleVioletRed", "#DB7093"),
("PapayaWhip", "#FFEFD5"),
("PeachPuff", "#FFDAB9"),
("Peru", "#CD853F"),
("Pink", "#FFC0CB"),
("Plum", "#DDA0DD"),
("PowderBlue"... | FF0000"),
("RosyBrown", "#BC8F8F"),
("RoyalBlue", "#4169E1"),
("SaddleBrown", "#8B4513"),
("Salmon", "#FA8072"),
("SandyBrown", "#F4A460"),
("SeaGreen", "#2E8B57"),
("SeaShell", "#FFF5EE"),
("Sienna", "#A0522D"),
("Silver", "#C0C0C0"),
("Sk... |
#-*- coding: utf-8 -*-
import traceback
from libcommon import ut | ils
from libcommon import commonlib
from libcommon.logger import stsdebug
#----------------------------------
# 获取san服务是否运行
#----------------------------------
def get_san_status():
san_status = False
try:
retcode,proc = utils.cust_popen([commonlib.ISCSI_SCST,'status'])
result = proc.stdout.read... | except:
stsdebug.write(stsdebug.get_line(),"stssan",traceback.print_exc())
return san_status
|
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def norm_col_init(weights, std=1.0):
x = torch.randn(weights.size())
x *= std / torch.sqrt((x**2).sum(1, keepdim=True))
return x
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') !=... | shape[0]
w_bound = np.sqrt(6. / (fan_in + fan_out))
m.weight.data.uniform_(-w_bound, w_bound)
m.bias.data.fill_(0)
elif classname.find('Linear') != -1:
weight_shape = list(m.weight.data.size())
fan_in = weight_shape[1]
fan_out = weight_shape[0]
w_bound = np.sq... | m.bias.data.fill_(0)
class A3Clstm(torch.nn.Module):
def __init__(self, num_inputs, action_space):
super(A3Clstm, self).__init__()
# convolutional neural networks
self.conv1 = nn.Conv2d(num_inputs, 32, 5, stride=1, padding=2)
self.maxp1 = nn.MaxPool2d(2, 2)
self.conv2 =... |
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
def eval_attr13(self, attr_value, this):
#===============... | nt node's attribute value by: attr_value.
# You can access any attribute x of this node by: this['x'].
| # If the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
... |
#
# Copyright (c) SAS Institute 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
#
# U | nless 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.
#
fil... | ))
|
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
from booth.views impor | t HomepageView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('allauth.urls')),
url(r'^', include('booth.urls', namespace='booth')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url("^$", HomepageView.as_view(), name="homepag... | l(r'^__debug__/', include(debug_toolbar.urls)),
)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
| # vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Test function from the generation of figures."""
import math
import gsd.hoomd
from hypothesis import given
from | hypothesis.strategies import floats
from statdyn.analysis.order import compute_voronoi_neighs
from statdyn.figures import colour
from statdyn.figures.configuration import plot, snapshot2data
@given(floats(min_value=-math.pi, max_value=math.pi))
def test_colour_orientation(orientation):
"""Ensure hex values being... |
.OneToOneField', [],
{'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True',
'to': "orm['cms.Page']"}),
'publisher_state': ('django.db.models.fields.SmallIntegerField', [],
{'default': '0', 'db_index': 'True'}),
're... | related.ForeignKey', [],
{'to': "orm['auth.User']"})
},
'cms.pagemoderatorstate': {
'Meta': {'ordering': "('page', 'action', '-created')",
| 'object_name': 'PageModeratorState'},
'action': ('django.db.models.fields.CharField', [],
{'max_length': '3', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [],
{'auto_now_add': 'True', 'blank': 'True... |
EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
# Standard library
from __future__ import print_function
import threading
import hashlib
import socket
import time
import sys
import re
# Third-party modules
from PyQt4 import QtCore, QtGui
# Local modules
import connection
import window
# FIXME: internatio... | end it, and returns a unique hash, used to identify
replies to this command."""
hash_ = hashlib.sha1(str(time.time()) + command).hexdigest()
command = '%s: %s\n' % (hash_, unicode(command).encode('utf8 | ', 'replace'))
self._sock.send(command)
return hash_
def stop(self):
"""Stops the loop."""
self._timer.stop()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
connection = Connection()
|
"""
# Pytess
Pure Python tessellation of points into polygons, including
Delauney/Thiessin, and Voronoi polygons. Built as a
convenient user interface for Bill Simons/Carson Farmer python port of
Steven Fortune C++ version of a Delauney triangulator.
## Platforms
Tested on Python version 2.x.
## Dependencies
Pu... | Python, no dependencies.
## Installing it
Pytess is installed with pip from the commandline:
pip install pytess
## Usage
To triangulate a set of points, simply do:
import pytess
points = [(1,1), (5,5), (3,5), (8,1)]
triangles = pytess.triangulate(points)
And for voronoi diagrams:
import p... | (8,1)]
voronoipolys = pytess.voronoi(points)
## More Information:
- [Home Page](http://github.com/karimbahgat/Pytess)
- [API Documentation](http://pythonhosted.org/Pytess)
## License:
This code is free to share, use, reuse,
and modify according to the MIT license, see license.txt
## Credits:
I just mad... |
def | load_text_file(text_file: str) -> str:
wit | h open(text_file, 'r') as f:
return f.read()
|
# -*- coding: utf-8 -*-
from qiniu import config
from qiniu import http
class PersistentFop(object):
"""持久化处理类
该类用于主动触发异步持久化操作,具体规格参考:
http://developer.qiniu.com/docs/v6/api/reference/fop/pfop/pfop.html
Attributes:
auth: 账号管理密钥对,Auth对象
bucket: 操作资源所在空间
pipeline: ... | data['pipeline'] = self.pipeline
if self.notify_url:
data['notifyURL'] = self.notify_url
if force == 1:
data['force'] = 1
url = 'http://{0}/pfop'.format(config.get_default('default_api_host'))
return http._post_with_auth(url, data, self.auth) | |
################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | _like in [l, tuple(l)]:
converted = TypeConverters.to_list_string(lst_like)
self.assertEqual(type(converted), list)
self.assertListEqual(converted, l)
def test_float(self):
data = 1.45
converted = TypeConverters.to_float(data)
self.assertEqual(type(conver... | t_int(self):
data = 1234567890
converted = TypeConverters.to_int(data)
self.assertEqual(type(converted), int)
self.assertEqual(converted, data)
def test_string(self):
data = "1234567890"
converted = TypeConverters.to_string(data)
self.assertEqual(type(convert... |
# Copyright 2021 The Google Earth Engine Community Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/L | ICENSE-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.
# [START ear... |
written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
##... | rgs['docstring']
else:
self._docstring = None
if 'shape' in kwargs:
self._shape = kwargs['shape']
del kwargs['shape']
else:
self._shape = None
DBPortSpec.__init__(self, *args, **kwargs)
if sum(1 for container in (self.por | t_spec_items, signature, sigstring)
if container) > 1:
raise ValueError("Please specify only one of portSpecItems,"
" signature, or sigstring kwargs.")
self.create_spec_items(self.port_spec_items, signature, sigstring,
defau... |
=========================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
#
# pyfa 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 la... | gePattern" else "")
box.Add(lbl, 0, wx.ALIGN_CENTER)
setattr(self, "labelResistance%sEhp | " % tankType.capitalize(), lbl)
sizerResistances.Add(box, wx.GBPosition(row, col), wx.GBSpan(1, 1), wx.ALIGN_CENTER)
row += 1
col = 0
self.stEHPs.SetToolTip(wx.ToolTip("Click to toggle between effective HP and raw HP"))
def toggleEHP(self, event):
wx.PostEvent(s... |
""" Benchmark functions for fftpack.pseudo_diffs module
"""
from numpy import arange, sin, cos, pi, exp, tanh, sign
from .common import Benchmark, safe_import
with safe_import():
from scipy.fftpack import diff, fft, ifft, tilbert, hilbert, shift, fftfreq
def direct_diff(x, k=1, period=None):
fx = fft(x)
... | )
if period is None:
period = 2*pi
w = fftfreq(n)*h*2*pi/period*n
w[0] = 1
w = 1j/tanh(w)
w[0] = 0j
return ifft(w*fx)
def direct_hilbert(x):
fx = fft(x)
n = len(fx)
w = fftfreq(n)*n
w = 1j*sign(w)
return ifft(w*fx)
def | direct_shift(x, a, period=None):
n = len(x)
if period is None:
k = fftfreq(n)*1j*n
else:
k = fftfreq(n)*2j*pi/period*n
return ifft(fft(x)*exp(k*a)).real
class Bench(Benchmark):
params = [
[100, 256, 512, 1000, 1024, 2048, 2048*2, 2048*4],
['fft', 'direct'],
]
... |
import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def setUp(self):
self.data = MockData()
def tes | t_random_data(self):
data = MockData()
| a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main() |
#%%
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | T_data/", one_hot=True)
print(mnist.tra | in.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable... |
try:
import openeye
# These can only be imported if openeye tools are available
| from smarty.atomtyper import *
from smarty.sampler import *
from smarty.utils import *
from smarty.sampler_smirky import *
ex | cept Exception as e:
print(e)
print('Warning: Cannot import openeye toolkit; not all functionality will be available.')
from smarty.score_utils import *
|
#####################################################################
#
# core.py
#
# Copyright (c) 2015, Eran Egozy
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
import kivy
from kivy.app import App
from kivy.core.window... | :
Clock.schedule_interval(self._update, 0)
def _key_down(self, keyboard, keycode, text, modifiers):
if not keycode[1] in self.down_keys:
self.down_keys.append(keycode[1])
self.on_key_down(keycode, modifiers)
| def _key_up(self, keyboard, keycode):
if keycode[1] in self.down_keys:
self.down_keys.remove(keycode[1])
self.on_key_up(keycode)
def _close(self, *args):
self.on_close()
def _update(self, dt):
self.on_update()
g_terminate_funcs = []
def register_terminate_func(f) :
globa... |
# -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.binding.datatypes as xsd
import pyxb.utils.domutils
from xml.dom import Node
import os.path
schema_path = os.path.abspath(os.path.join(os.path.dirname(... | efinition, xsd.string))
self.assertEqual(2, clause1_1._TypeDefinition._CF_minLength.value())
self.assertEqual(4, clause1_1._TypeDefinition._CF_maxLength.value())
def testClause1_2 (self):
self.assertTrue(clause1_2._IsSimpleTypeContent())
self.assertTrue(issubclass( | clause1_2, clause4))
self.assertTrue(issubclass(clause1_2._TypeDefinition, xsd.string))
self.assertEqual(6, clause1_2._TypeDefinition._CF_length.value())
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/python
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | res = create_item(maas, desired)
if res['error']:
module.fail_json(msg=res['status'])
else:
module.exit_json(changed=True, item=res['status'])
else:
# If this should be absent, then we are done and in the desired state
module.... | exist
if state == 'query':
# If this is a query, return the item
module.exit_json(changed=False, found=True, item=item)
elif state == 'present':
# If we want this to exists check to see if this is different and
# needs updated
if different(item, desired):
res ... |
from .utils import do, do_ex, trace
from .version import meta
from os.path import abspath, realpath
FILES_COMMAND = 'git ls-files'
DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*'
def parse(root, describe_command=DEFAULT_DESCRIBE):
real_root, _, ret = do_ex('git rev-parse --show-toplevel', ro... | root)
if ret:
return meta('0.0')
rev_node = rev_node[:7]
out, err, ret = do_ex(describe_command, root)
if '-' not in out and ' | .' not in out:
revs = do('git rev-list HEAD', root)
count = revs.count('\n')
if ret:
out = rev_node
return meta('0.0', distance=count + 1, node=out)
if ret:
return
dirty = out.endswith('-dirty')
if dirty:
out = out.rsplit('-', 1)[0]
tag, numbe... |
y:
if conn:
conn.close() # close in case of errors
return result
def _file_url(filepath, url):
"""Return URL for the given `filepath` in the DAV collection `url`."""
basename = os.path.basename(filepath)
return urlparse.urljoin(url.rstrip('/') + '/', basename)
def _dav_put(filep... | e = int(repo_params.get("overwrite", "0"), 10)
# TODO: Add ability to enter missing password via terminal
# auth_handler = PromptingPasswordMgr(login)
# Special handling for integration test code
if "integration-test" in cli_params:
import pprint
print "upload ... | gress")))
print "host config = ",
pprint.pprint(host_config)
print "host arguments = ",
pprint.pprint(cli_params)
else:
# TODO: "bintray" REST API support
# POST /packages/:subject/:repo
# POST /packages/:subject/:repo/:pack... |
#-*- coding: utf-8 -*-
# This file based on MIT licensed code at: https://github.com/imwilsonxu/fbone
from functools import wraps
from | flask import abort
from flask.ext.login import current_user
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_admin():
ab | ort(403)
return f(*args, **kwargs)
return decorated_function
|
# coding=utf-8
# Copyright (C) Duncan Macleod (2015)
#
# This file is part of the GW DetChar python package.
#
# GW DetChar 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 vers | ion 3 of the License, or
# (at your option) any later version.
#
# GW DetChar 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GW DetChar. If not, see <http://www.gnu.org/licenses/>.
"""Me... |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'DESCRIPTION.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='jestocke-mangopaysdk',
version='3.0.6',
description='A clie... | license='MIT',
classifiers=[
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming La | nguage :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
keywords='mangopay api development emoney sdk',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
install_requires=['requests', 'simplejson', 'blinker', 'six' ],
... |
#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
syst_names = ['nominal','lightdown','lightup','ckv','calibneg','calibpos','calibshape']
flists = [syst_name+'.txt' for syst_name in syst_names]
def process_dataset(ds_idx):
flist = flists[ds_idx]
fns = []
with open(... | slin'
out_path = os.path.join(out_base,'numuccinc','evt_matched_cafs',syst_names[ds_idx])
if not os.path.exists(out_path):
os.makedirs(out_path)
for fn in fns:
bashout = subprocess.check_output('samweb locate-file {}'.format(fn), shell=True)
bashout = bashout.split('\n')
for... | format(os.path.join(location, fn), out_path)
os.system(cmd)
if __name__ == '__main__':
for i in range(len(syst_names)):
process_dataset(i) |
# -*- coding: utf-8 -*-
#
# HnTool rules - php
# Copyright (C) 2009-2010 Candido Vieira <cvieira.br@gmail.com>
#
# This program is free | software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwar | e Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Lice... |
_branch:
description:
- Clone only the history leading to the tip of the specified I(branch).
type: bool
default: 'no'
version_added: '2.11'
track_submodules:
description:
- If C(yes), submodules will track the latest commit on their
mas... | ion is to use the option accept_hostkey. Another solution is to
add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling
the git module, with the following command: ssh-keyscan -H remote_host.com >> /etc/ssh/s | sh_known_hosts."
- Supports C(check_mode).
'''
EXAMPLES = '''
- name: Git checkout
ansible.builtin.git:
repo: 'https://foosball.example.org/path/to/repo.git'
dest: /srv/checkout
version: release-0.22
- name: Read-write git checkout from github
ansible.builtin.git:
repo: git@github.com:mylogin/... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... | ss from which messages are received (default %default)")
parser.add_option("-m", "--messages", type="int", default=100,
help="number of messages to r | eceive; 0 receives indefinitely (default %default)")
parser.add_option("-i", "--id", default="client-d",
help="client's connection identifier (default %default)")
parser.add_option("-s", "--subscription", default="subscription-d",
help="client's subscription identifier (default %defa... |
# coding=utf-8
# Copyright 2014 Pants project c | ontributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.build_graph.build_graph import sort_targets
from pants.t... | ""
@classmethod
def register_options(cls, register):
super(SortTargets, cls).register_options(register)
register('--reverse', action='store_true', default=False,
help='Sort least-dependent to most-dependent.')
def console_output(self, targets):
sorted_targets = sort_targets(targets)
... |
import numpy as np
from pyraf import iraf
from pyraf.iraf import kepler
'''
Useful functions for Kepler light curve processing
Use this with the program 'makelc.py'
Originally by Jean McKeever
Edited and improved by Meredith Rawls
'''
# calculate orbital phase
# times must be a list of observation times in the same un... | me MEDIAN level
# operates on a list of arrays (multiple quarters) all at once
def normalize_qtr_med(flux):
sumflux = 0
npts = 0
for arr in flux:
sumflux += np.nansum(arr)
npts += len(arr)
avgflux = sumflux/npts # overall average for all quarters
for arr in flux:
med_arr = np.median(arr) # median for an indi... | maskstart, maskend):
diffs = np.zeros(len(time) - 1)
for i in range(0,len(time) - 1): # loop through quarters
# calculate differences between flux points at quarter start/end
start = 0
end = -1
for idx, mask in enumerate(maskstart):
while (time[i][end] > maskstart[idx] and time[i][end] < maskend[idx]):
... |
overrides from NEP-18."""
import collections
import functools
import os
import textwrap
from numpy.core._multiarray_umath import (
add_docstring, implement_array_function, _get_implementing_args)
from numpy.compat._inspect import getargspec
ARRAY_FUNCTION_ENABLED = bool(
int(os.environ.get('NUMPY_EXPERIMENT... |
def decorator(implementation):
if verify:
| verify_matching_signatures(implementation, dispatcher)
if docs_from_dispatcher:
add_docstring(implementation, dispatcher.__doc__)
# Equivalently, we could define this function directly instead of using
# exec. This version has the advantage of giving the helper function a
... |
"""
Support to interact with a Music Player Daemon.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.mpd/
"""
import logging
import socket
import voluptuous as vol
from homeassistant.components.media_player import (
MEDIA_TYPE_MUSIC, SUP... | volume >= 0:
self.cli | ent.setvol(current_volume - 5)
def media_play(self):
"""Service to send the MPD the command for play/pause."""
self.client.pause(0)
def media_pause(self):
"""Service to send the MPD the command for play/pause."""
self.client.pause(1)
def media_next_track(self):
"""... |
lf.assertIn(addr, ['127.0.0.1', '::1'])
self.assertTrue(port, 80)
handler.send(True)
while True:
buf = sock.recv(65535)
if buf.endswith(b'\r\n\r\n'):
break
sock.sendall(b'HTTP/1.1 200 OK\r\n'
b... | next(handler)
self._start_server(request_handler)
proxy_url = "socks5h://%s:%s" % (self.host, self.port)
pm = socks.SOCKSProxyManager(proxy_url, username='user',
password='badpass')
self.addCleanup(pm.clear)
try:
pm.re... | ue("SOCKS5 authentication failed" in str(e))
else:
self.fail("Did not raise")
def test_source_address_works(self):
expected_port = _get_free_port(self.host)
def request_handler(listener):
sock = listener.accept()[0]
self.assertEqual(sock.getpeername()[0]... |
ermissions = ignore_permissions
self.user = user or frappe.session.user
self.update = update
self.user_settings_fields = copy.deepcopy(self.fields)
if user_settings:
self.user_settings = json.loads(user_settings)
if query:
result = self.run_custom_query(query)
else:
result = self.build_and_run()
... | mission(doctype)):
frappe.flags.error_message = _('Insufficient Permission for {0}').format(frappe.bold(doctype))
raise frappe.PermissionError(doctype)
def set_field_tables(self):
'''If there are more than one table, the fieldname must not | be ambigous.
If the fieldname is not explicitly mentioned, set the default table'''
if len(self.tables) > 1:
for i, f in enumerate(self.fields):
if '.' not in f:
self.fields[i] = '{0}.{1}'.format(self.tables[0], f)
def set_optional_columns(self):
"""Removes optional columns like `_user_tags`, `_comm... |
###########################################################################
#
# This program is part of Zenoss Core, an open source monitoring platform.
# Copyright (C) 2008, Zenoss Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License versi... | OR,
license = LICENSE,
# This is the version spec which indicates what versions of Zenoss
# this ZenPack is compatible with
compatZenossVers = COMPAT_ZENOSS_VERS,
# previousZenPackName is a facility for telling Zenoss that the name
# of this ZenPack has changed. If no ZenPack with the current... | me if installed will be upgraded.
prevZenPackName = PREV_ZENPACK_NAME,
# Indicate to setuptools which namespace packages the zenpack
# participates in
namespace_packages = NAMESPACE_PACKAGES,
# Tell setuptools what packages this zenpack provides.
packages = find_packages(),
# Tell setupto... |
s PivocramConnetcTest(base.TestCase):
def setUp(self):
self.connect = pivocram.Connect('PIVOTAL_TEST_TOKEN')
def test_should_have_the_pivotal_api_url(self):
self.connect.PIVOTAL_URL.should.be.equal('https://www.pivotaltracker.com/services/v5')
def test_should_have_header_with_token(self):
... | f test_should_update_story(self):
self.connect.put = self.mock.MagicMock(return_value='req-response')
self.connect.project_story_url = self.mock.MagicMock(return_value='url-stories')
self.connect.update_story(123, 1234, {'data': 'value'}).should.be.equal('req-response')
self.connect.put.... | .connect.project_story_url.assert_called_with(123, 1234)
def test_should_update_story_task(self):
self.connect.put = self.mock.MagicMock(return_value='req-response')
self.connect.project_story_task_url = self.mock.MagicMock(return_value='url-stories')
self.connect.update_story_task(123, 123... |
""" Function | s and classes dealing with commands. | """
|
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbFindHydratedProjectsByTeam(BaseType):
def __init__(self, find_projects=None, org_id=None, name=None, id=None):
required = {
"find_projects": False,
"org_id": False,
| "name": False,
"id": False,
}
self.find_projects = find_projects
self.org_id = org_id
self.name = name
self.id = id
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format(k))
@staticmethod
def from_json(d):
from .... | projects', None)
if tmp is not None:
d['find_projects'] = ModeldbFindProjects.from_json(tmp)
tmp = d.get('org_id', None)
if tmp is not None:
d['org_id'] = tmp
tmp = d.get('name', None)
if tmp is not None:
d['name'] = tmp
tmp = d.get('id', None)
if tmp is not None:
d['... |
# -*- coding: utf-8 -*-
# darwinvpnlauncher.py
# Copyright (C) 2013 LEAP
#
# 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 versio... | def is_kext_loaded(kls):
"""
Checks if the needed kext is loaded before launching openvpn.
:returns: True if kext is loaded, False otherwise.
:rtype: bool
"""
return bool(commands.getoutput('kextstat | grep "leap.tun"'))
@classm | ethod
def _get_icon_path(kls):
"""
Returns the absolute path to the app icon.
:rtype: str
"""
resources_path = os.path.abspath(
os.path.join(os.getcwd(), "../../Contents/Resources"))
return os.path.join(resources_path, "bitmask.tiff")
@classmethod
... |
# coding: utf-8
"""
MINDBODY Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
impo... | Get contact logs on a client's account. # noqa: E501
"""
pass
def test_client_get_cross_regional_client_associations(self):
"""Test case for client_get_cross_regional_client_associations
Get a client's cross regional si | te associations. # noqa: E501
"""
pass
def test_client_get_custom_client_fields(self):
"""Test case for client_get_custom_client_fields
Get a site's configured custom client fields. # noqa: E501
"""
pass
def test_client_get_required_client_fields(self):
... |
import sys
from services.housing import HouseTemplate
from engine.resources.scene import Point3D
def setup(housingTemplates):
houseTemplate = HouseTemplate("object/tangible/deed/player_house_deed/shared_corellia_house_large_st | yle_02_deed.iff", "object/buildi | ng/player/shared_player_house_generic_large_style_02.iff", 5)
houseTemplate.addBuildingSign("object/tangible/sign/player/shared_house_address.iff", Point3D(float(-13.4), float(3), float(9.1)))
houseTemplate.addPlaceablePlanet("corellia")
houseTemplate.addPlaceablePlanet("talus")
houseTemplate.setDefaultItemLimit(... |
or full net: ('[label]', '[netdef]', 'fullnet')
('soumith1', '3i128-96c11', 'layer'),
('soumith2', '64i64-128c9', 'layer'),
('soumith3', '128i32-128c9', 'layer'),
('soumith4', '128i16-128c7', 'layer'),
('soumith5', '384i13-384c3', 'layer'),
('maddison-convolve', '128i19-128c3', 'layer'),
(... | d gradients to
# this layer
print( net.asString() )
if 'c' in layer_string:
num_filters, filter_size = map(lambda x: int(x), layer_string.split('c'))
net.addLayer( PyDeepCL.ConvolutionalMaker().numFilters(num_filters)
.filterSize( | filter_size).biased() )
elif 'n' in layer_string:
num_neurons = int(layer_string.split('n')[0])
net.addLayer( PyDeepCL.FullyConnectedMaker().numPlanes(num_neurons).imageSize(1).biased() )
else:
raise Exception('layer_string {layer_string} not recognized'.format(
layer_string=... |
# -*- coding: utf-8 -*-
u"""
.. module:: organizations
"""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render... | ',
args=[slugify(org.name), org.id]
)
)
else:
message | s.error(
request,
u"Należy wypełnić wszystkie pola formularza."
)
return render(
request,
"organizations/organization_form.html",
{'organization': org},
)
@correct_slug(Organization, 'organization_view', 'name')
def organization_view(request... |
class Post(object):
def _ | _init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
return iter(self.__d | ict__)
|
from flask.ext.restplus import Namespace
from app.api.tickets import ORDER, TICKET
from app.helpers.ticketing import TicketingManager
from app.api.helpers.helpers import (
requires_auth,
can_access, replace_event_id)
from app.api.helpers.utils import POST_RESPONSES
from app.api.helpers.utils import Resource
f... | scription='Attendees', path='/')
ATTENDEE = api.model('TicketHolder', {
'id': fields.Integer(),
'firstname': fields.String(),
'lastname': fields.S | tring(),
'email': fields.Email(),
'checked_in': fields.Boolean(),
'order': fields.Nested(ORDER, allow_null=False),
'ticket': fields.Nested(TICKET, allow_null=False)
})
@api.route('/events/<string:event_id>/attendees/')
class AttendeesList(Resource):
@requires_auth
@replace_event_id
@can_ac... |
#!/usr/bin/env python
'''
Component to handle data storage and search of all commands run
'''
from framework.dependency_management.dependency_resolver import BaseComponent
from framework.dependency_management.interfaces import CommandRegisterInterface
from framework.lib.general import cprint
from framework.db import m... | self.register_in_service_locator()
self.config = self.get_component("config")
self.db = self.get_component("db")
self.plugin_output = None
self.target = None
def init(self):
self.target = self.get_component("target")
self.plugin_output = self.get_component("p... | success=Command['Success'],
target_id=Command['Target'],
plugin_key=Command['PluginKey'],
modified_command=Command['ModifiedCommand'].strip(),
original_command=Command['OriginalCommand'].strip()
))
self.db.session.commit()
def DeleteCommand(self, C... |
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.layers import Flatten, Reshape
from keras import regularizers
from plotly import offline as py
import plotly.graph_objs as go
... | encoder.summary()
input_img = Input(shape=(input_dim,))
encoder_layer = autoencoder.layers[0]
encoder = Model(input_img, encoder_layer(input_img))
encoder.summary()
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.fit(x_t | rain, x_train,
epochs=50,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
num_images = 10
np.random.seed(42)
random_test_images = np.random.randint(x_test.shape[0], size=num_images)
encoded_imgs = encoder.predict(x_test)
decoded_imgs = a... |
# OCF 1.0 doesn't define unique groups, they ar | e defined since OCF 1.1. Pcs
# transforms OCF 1.0 agents to OCF 1.1 structure and therefore needs to create
# a group name for OCF 1.0 unique at | trs. The name is: {this_prefix}{attr_name}
DEFAULT_UNIQUE_GROUP_PREFIX = "_pcs_unique_group_"
|
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... | cense 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.
#
""" Using absolute import, do from module imports.
"""
| from __future__ import absolute_import, print_function
from foobar import util
from . import local # pylint: disable=unused-import
class Foobar(object):
def __init__(self):
print(util.someFunction())
|
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class Mailer(threading.Thread):
"""
Mailer
:desc: Class that sends an email
Exte | nds Thread
"""
def __init__(self):
"""
| __init__
:desc: Constructor function that calls parent
"""
Thread.__init__(self)
def run(self, stri, dictio):
"""
run
:desc : Function that does the heavy lifting
:params : The string to be mailed and a dict
containing config options necessary fo... |
from ert_gui.ide.keywords.definitions import ProperNameFormatArgument
from ecl.test import ExtendedTestCase
class ProperNameFormatArgumentTest(ExtendedTest | Case):
def test_proper_name_format_argument(self):
argument = ProperNameFormatArgument()
self.assertTrue(argument.validate("NAME%d"))
| self.assertTrue(argument.validate("__NA%dME__"))
self.assertTrue(argument.validate("<NAME>%d"))
self.assertTrue(argument.validate("%d-NAME-"))
self.assertFalse(argument.validate("-%dNA ME-"))
self.assertFalse(argument.validate("NAME*%d"))
|
er = HeaderParser()
|
if not header_lines:
header_lines = [
| '##fileformat=VCFv4.2',
'##FILTER=<ID=LowQual,Description="Low quality">',
'##INFO=<ID=MQ,Number=1,Type=Float,Description="RMS Mapping Quality">',
'##INFO=<ID=CNT,Number=A,Type=Integer,Description="Number of times '\
'this allele was found in external db">',
... |
import urwid
from mitmproxy import http
from mitmproxy.tools.console import common, searchable
from mitmproxy.utils import human
from mitmproxy.utils import strutils
def maybe_timestamp(base, attr):
if base is not None and getattr(base, attr):
return human.format_timestamp_with_milli(getattr(base, attr))... | a:")]))
text.extend(common.format_keyvals(parts, indent=4))
if sc is not None and sc.ip_address:
text.append(urwid.Text([("head", "Server Connection:")]))
parts = [
("Address", human.format_address(sc.address)),
]
| if sc.ip_address:
parts.append(("Resolved Address", human.format_address(sc.ip_address)))
if resp:
parts.append(("HTTP Version", resp.http_version))
if sc.alpn_proto_negotiated:
parts.append(("ALPN", sc.alpn_proto_negotiated))
text.extend(
... |
import numpy as np
from get_params import get_params
import os
import pickle
""" Returns mAP for each query. """
def relnotrel( fileGT, id_q, rankingShots ):
'''Takes ground truth file (fileGT), query name (id_q) and ranking (rankingShots) in order to create a vector of 1's and 0's to compute Average Pre... | nd the number of relevant samples and computes the average precision'''
accu = 0
numRel = 0
for k in range(min(len(relist),1000)):
if relist[k] == 1:
numRel = numRel + 1
acc | u += float( numRel )/ float(k+1)
return (accu/nRelTot)
def rerank(ranking,baseline):
new_ranking = []
for shot in ranking:
if shot in baseline:
new_ranking.append(shot)
return new_ranking
if __name__ == '__main__':
params = get_params()
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | elif api_version == '2.1':
base_url = '{endpoint}/formrecognizer/v2.1'
else:
raise ValueError("API version {} is not available".format(api_version))
self._config = FormRecognizerClientConfiguration(credential, endpoint, **kwargs)
self._client = AsyncPipelineClient(... | ion,
profile=profile
)
@classmethod
def _models_dict(cls, api_version):
return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)}
@classmethod
def models(cls, api_version=DEFAULT_API_VERSION):
"""Module depends on the API version:
... |
#!/usr/bin/env python
# BEGIN_COPYRIGHT
#
# Copyright 2009-2018 CRS4.
#
# 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 ap... | def close(self):
self.file.close()
s | elf.file.fs.close()
def emit(self, key, value):
self.file.write("%r%s%s%s" % (key, self.sep, value, "\n"))
def __main__():
pipes.run_task(pipes.Factory(
mapper_class=Mapper,
record_writer_class=Writer,
))
if __name__ == "__main__":
__main__()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.