prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
"""
WSGI config for django_rest_test project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLI... | n application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the sa | me mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "django_rest_test.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_rest_test.settings")
# This application object is used by any WSGI server configured... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..registration import MeasureImageSimilarity
def test_MeasureImageSimilarity_inputs():
input_map = dict(args=dict(argstr='%s',
),
dimension=dict(argstr='--dimensionality %d',
position=1,
),
envir... | ageSimilarity_outputs():
output_map = dict(similarity=dict(),
)
outputs = MeasureImageSimilarity.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits( | )[key], metakey) == value
|
import IMP
import IMP.test
import IMP.core
import IMP.atom
class Tests(IMP.test.TestCase):
def test_bonded(self):
"""Check close and destroy Hierarchy """
m = IMP.Model()
mh = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m)
nump = len(m.get_particle_indexes())
m... | sertEqual(0, len(m.get_particle_indexes()))
def test_destroy_child(self):
"""Destroy of a child should update the parent"""
m = IMP.Model()
mh = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m)
atoms = IMP.atom.get_by_type(mh, IMP.atom.ATOM_TYPE)
self.assertEqual(l... | is not removed from the parent residue
atoms = IMP.atom.get_by_type(mh, IMP.atom.ATOM_TYPE)
self.assertEqual(len(atoms), 67)
if __name__ == '__main__':
IMP.test.main()
|
ot "
"information.")
self.adjust_slot(session, logger,
dbmachine, dbchassis, slot, multislot)
elif slot is not None:
dbchassis = None
for dbslot in dbmachine.chassis_slot:
if dbchassis and dbslot... | achine.host:
for srv in dbmachine.host.services_provided:
si = srv.service_instance
plenaries.add(si, cls=PlenaryServiceInstanceToplevel)
update_primary_ip(session, logger, dbmachine, ip)
if dbmachine.location != old_location and dbmachine.hos... | location = dbmachine.location
session.flush()
# Check if the changed parameters still meet cluster capacity
# requiremets
if dbmachine.cluster:
dbmachine.cluster.validate()
if allow_metacluster_change and dbmachine.cluster.metacluster:
dbmachine.... |
function
import argparse
import array
import math
import os
import random
import sys
import subprocess
def create_graph(nodes, edges, verbose):
if verbose: print('Creating random graph with {} nodes and {} edges...'.format(nodes, edges))
n1 = [ random.randint(0, nodes - 1) for x in xrange(edges) ]
n2 = [ ... | gs.verbose)
else:
assert false
try:
os.mkdir(args.outdir)
except:
pass
assert os.path.isdir(args.outdir)
if args.metis:
assert os.path.isfile(args.metis_path)
metis_graph(G, args.metis_path, args.subgraphs, args.outdir, args.verbose)
sort_graph(G, args.... | h(G, args.problems, args.outdir, args.verbose)
|
#!/usr/bin/python
#
# Copyright 2015 Google Inc. 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 b... | nt()
# Get creative templates by statement.
while True:
response = creative_template_service.getCreativeTemplatesByStatement(
statement.ToStatement())
if 'results' i | n response:
# Display results.
for template in response['results']:
print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
'was found.' % (template['id'],
template['name'],
template['type']))
stateme... |
#!/usr/bin/python
"""
This example demonstrates several features of PyLaTeX.
It includes plain equations, tables, equations using numpy objects, tikz plots,
and figures.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
# begin-doc-include
import numpy as np
from pylate... | with doc.create(Section('The simple stuff')):
doc.append('Some regular text and some')
doc.append(italic('italic text. '))
doc.append('\nAlso some crazy characters: $&#{}')
with | doc.create(Subsection('Math that is incorrect')):
doc.append(Math(data=['2*3', '=', 9]))
with doc.create(Subsection('Table of something')):
with doc.create(Tabular('rc|cl')) as table:
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add... |
# -*- | coding: utf-8 -*-
from __future__ import unicode_lit | erals
from django.db import migrations
from corehq.form_processor.models import CaseTransaction
from corehq.sql_db.operations import RawSQLMigration, HqRunSQL
migrator = RawSQLMigration(('corehq', 'sql_accessors', 'sql_templates'), {
'TRANSACTION_TYPE_FORM': CaseTransaction.TYPE_FORM
})
class Migration(migrati... |
#!/usr/bin/python
import os
import psycopg2
import sys
import django_content_t | ype_mapping
file = open("/home/" + os.getlogin() + "/.pgpass", "r")
pgpasses = []
f | or line in file:
pgpasses.append(line.rstrip("\n").split(":"))
file.close()
for pgpass in pgpasses:
#print str(pgpass)
if pgpass[0] == "54.236.235.110" and pgpass[3] == "geonode":
src_pgpass = pgpass
if pgpass[0] == "54.197.226.56" and pgpass[3] == "geonode":
dst_pgpass = pgpass
src = psycopg2.conne... |
#coding=utf-8
# Copyright (C) 2014 by Víctor Romero Blanco <info at playcircular dot com>.
# http://playcircular.com/
# It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
# You can get copies of the licenses here: http://www.affero.org/oagpl.html
# AFFERO GENERAL PUBLIC LICENSE is also incl... | 'usuario', flat=True)
if request.user.is_superuser:
#El Superadmin puede publicar sin que pernezca a n | ingún grupo para que no lo controlen los Admin de los grupos
usuarios_qs = list(usuarios_qs) + [request.user.pk]
usuarios = User.objects.filter(pk__in=usuarios_qs).distinct()
else:
usuarios = User.objects.filter(pk=request.user.pk)
datos = list(usuarios) + list(categorias)
else:
datos = []
... |
"""Test the IPython.kernel public API
Authors
----- | --
* MinRK
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The | full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import nose.tools as nt
from IPython.testing import decorators as dec
from IPython.kernel import launcher, connect
from IPython import kernel
#---------------------... |
"""
"""
from traceback import format_exc as debug
from vyapp.stdout import Stdout
from vyapp.tools import exec_quiet, set_status_msg
from vyapp.ask import *
import sys
def redirect_stdout(area):
try:
sys.stdout.remove(area)
except ValueErr | or:
pass
sys.stdout.append(Stdout(area))
set_status_msg('Output redirected to %s' % area.index('insert'))
def install(area):
area.install(('NORMAL', '<Control-W>', lambda event: event.widget.tag_delete_ranges(Stdout.TAG_COD | E)),
('NORMAL', '<Control-Tab>', lambda event: sys.stdout.restore()),
('NORMAL', '<Key-W>', lambda event: event.widget.tag_delete(Stdout.TAG_CODE)),
('NORMAL', '<Control-w>', lambda event: exec_quiet(sys.stdout.remove, event.widget)),
('NORMAL', '<Tab>', lambda event: redirec... |
-in to getting access to it.
The context is useful as it can pass internal objects around and can
control special execution features such as reading data from
environment variables.
A context can be used as context manager in which case it will call
:meth:`close` on teardown.
.. versionadded:... | ntent_width = parent.max_content_width
#: The maximum width of formatted content (None implies a sensible
#: default which is 80 for most things).
self.max_content_width = max_con | tent_width
if allow_extra_args is None:
allow_extra_args = command.allow_extra_args
#: Indicates if the context allows extra args or if it should
#: fail on parsing.
#:
#: .. versionadded:: 3.0
self.allow_extra_args = allow_extra_args
if allow_inters... |
try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
import xml2nrn
# module names derived from the namespace. Add new tags in proper namespace
import neuroml
import metadata
import morphml
import biophysics
class FileWrapper:
def __init__(self, sou... | split('/')[-2]
tag = ns+'.'+tag[1] #namespace.element should correspond to module.func
f = None
try:
if event == 'start':
f = eval(tag)
elif event == 'end':
f = eval( | tag + '_end')
except:
pass
if f:
x2n.locator.lineno = fw.lineno
try:
f(x2n, node) # handle the element when it opens
except:
print tag,' failed at ', x2n.locator.getLineNumber()
elif event == 'start':
print 'ignore', node.tag # no function to handle the element
return 0
retur... |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
"""
Aggregate top level objects from all Scapy modules.
"""
from scapy.base_classes import *
from scapy.config import *
from ... | *
from scapy.route import *
from scapy.sendrecv import *
from scapy.sessions import *
from scapy.supersocket import *
from scapy.volatile import *
from scapy.as_resolvers import *
from scapy.automaton import *
from scapy.a | utorun import *
from scapy.main import *
from scapy.consts import *
from scapy.compat import raw # noqa: F401
from scapy.layers.all import *
from scapy.asn1.asn1 import *
from scapy.asn1.ber import *
from scapy.asn1.mib import *
from scapy.pipetool import *
from scapy.scapypipes import *
if conf.ipv6_enabled: # ... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.4.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x01\xf1\
\x00\
\x00\x09\x00\x78\x9c\xdd\x96\x51\x6f\x9b\x30\x10\xc7\xdf\xfb\x29\
\x3c\x1e\x9a\x4... | _struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00 | \x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
|
es)
class FakeBackend(BaseModel):
def __init__(self, instance_port):
self.instance_port = instance_port
self.policy_names = []
def __repr__(self):
return "FakeBackend(inp: %s, policies: %s)" % (self.instance_port, self.policy_names)
class FakeLoadBalancer(BaseModel):
def __ini... | ibute()
cross_zone_load_balancing.enabled = False
attributes.cross_zone_load_balancing = cross_zone_load_balancing
connection_draining = ConnectionDrainingAttribute()
connection_draining.enabled = False
attributes.connection_draining = connection_draining
access_log = A... | access_log.enabled = False
attributes.access_log = access_log
connection_settings = ConnectionSettingAttribute()
connection_settings.idle_timeout = 60
attributes.connecting_settings = connection_settings
return attributes
def add_tag(self, key, value):
if len(sel... |
from fbchat import GroupData, User
def test_group_from_graphql(session):
data = {
"name": "Group ABC",
"thread_key": {"thread_fbid": "11223344"},
"image": None,
"is_group_thread": True,
"all_participants": {
"nodes": [
{"messaging_actor": {"__typ... | {"__typename": "User", "id": "2345"}},
{"messaging_actor": {"__typename": "User", "id": "3456"}},
]
},
"customization_info": {
"participant_customizations": [],
"outgoing_bubble_color": None,
"emoji": "😀",
},
"thread_admin... | e_mode": {"mode": "0", "link": ""},
"event_reminders": {"nodes": []},
}
assert GroupData(
session=session,
id="11223344",
photo=None,
name="Group ABC",
last_active=None,
message_count=None,
plan=None,
participants=[
User(session... |
/// | <reference path="./testBlocks/enums.ts" />
enum EnumOfFlags {
W = 1,
X = 1 << 1,
Z = 1 << 3
}
let userDefinedTest7 = EnumOfFlag | s.W |
import itertools
import os
class TreeHasher():
"""uses BlockHasher recursively on a directory tree
Input and output generators are in the format: ( relative-filepath, chunk_nr, hexdigest)
"""
def __init__(self, block_hasher):
"""
:type block_hasher: BlockHasher
"""
... | e(self, start_path):
"""Use BlockHasher on every file in a tree, yielding the results
note that it only checks the contents of actual files. It ignores metadata like permissions and mtimes.
It also ignores empty directories, symlinks and s | pecial files.
"""
def walkerror(e):
raise e
for (dirpath, dirnames, filenames) in os.walk(start_path, onerror=walkerror):
for f in filenames:
file_path=os.path.join(dirpath, f)
if (not os.path.islink(file_path)) and os.path.isfile(file_p... |
# Microcosmos: an antsy game
# Copyright (C) 2010 Cyril ADRIAN <cyril.adrian@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 Software Foundation, version 3 exclusively.
#
# This program is distrib... | t will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Ge | neral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
The Bugs model package provides bugs and their specific behaviour.
"""
from net.cadrian.microcosmos.model.bugs.antFemales import A... |
sheet()
elif event.notice == 'add_image':
pass
elif event.notice == 'del_image':
pass
elif event.notice == 'add_character':
self.add_character()
elif event.notice == 'del_character':
self.del_character()
elif event.notice == 'add_an... | ith same name , overwrite ?
filename = dialogs.open_sheet(self.parent)
if filename is not None:
dia = dial | ogs.AddSheetDialog(None, -1, "Insert sheet details",
self.resources)
result = dia.ShowModal()
if result == wx.ID_OK:
self.settings = dia.GetSettings()
try:
self.resources.add_resource(
... |
#!/usr/bin/env python
# Thu, 13 Mar 14 (PDT)
# bpf-filter.rb: Create a packet filter,
# use it to print udp records from a trace
# Copyright (C) 2 | 015, Nevil Brownlee, U Auckland | WAND
from plt_testing import *
t = get_example_trace('anon-v4.pcap')
filter = plt.filter('udp port 53') # Only want DNS packets
t.conf_filte | r(filter)
t.conf_snaplen(500)
#t.conf_promisc(True)
# Remember: on a live interface, must sudo to capture
# on a trace file, can't set promicuous
nfp = 0; offset = 12
for pkt in t:
nfp += 1
udp = pkt.udp
test_println("%4d:" % (nfp), get_tag())
print_udp(pkt.udp, offset, get_tag("nfp:"... |
eration number, which is only incremented
when learning is enabled
bucketIdx: the bucket index to store
Save duty cycle by normalizing it to the same iteration as
the rest of the duty cycles which is lastTotalUpdate.
This is done to speed up computation in inference since all of the... | te__(self, state):
version = 0
if "_version" in state:
version = state["_version"]
# Migrate from version 0 to version 1
if version == 0:
stats = state.pop("_stats")
assert isinstance(stats, dict)
maxBucket = max(stat | s.iterkeys())
self._stats = array.array("f", itertools.repeat(0.0, maxBucket + 1))
for (index, value) in stats.iteritems():
self._stats[index] = value
elif version == 1:
state.pop("_updateDutyCycles", None)
elif version == 2:
pass
else:
raise Exception("Error while dese... |
rg/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitatio... | se primitives.
Internally, seconds, with microsecond granularity, are stored as
timeutil.Timestamp and timeutil.Duration objects. This is done to avoid
precision errors that would occur with floating point representations.
Custom windowing function classes can be created, by subclassing from
WindowFn.
"""
from __fut... | ort object
from builtins import range
from functools import total_ordering
from future.utils import with_metaclass
from google.protobuf import duration_pb2
from google.protobuf import timestamp_pb2
from apache_beam.coders import coders
from apache_beam.portability import common_urns
from apache_beam.portability impor... |
graphics.icon import Icon, CellRendererIcon
from jarabe.controlpanel.sectionview import SectionView
from jarabe.model.update import updater
from jarabe.model import bundleregistry
_DEBUG_VIEW_ALL = True
class ActivityUpdater(SectionView):
def __init__(self, model, alerts):
SectionView.__init__(self)
... | pacing(style.DEFAULT_PADDING)
self.set_border_width(style.DEFAULT_SPACING * 2)
self._progress = Gtk.ProgressBar()
self.pack_start(self._progress, True, True, 0)
self._progress.show()
self._label = Gtk.Label()
self._label.set_line_wrap(True)
self._label.set_prope... | self._label.modify_fg(Gtk.StateType.NORMAL,
style.COLOR_BUTTON_GREY.get_gdk_color())
self.pack_start(self._label, True, True, 0)
self._label.show()
alignment_box = Gtk.Alignment.new(xalign=0.5, yalign=0.5,
xscale=0, ys... |
#### NOTICE: THIS FILE IS AUTOGENER | ATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/loot_schematic/shared_death_watch_mandalorian_belt_schematic.iff"
result.attribute_template_id = ... | orian_belt")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
If not, see <http://www.gnu.org/licenses/>.
#
from collections import OrderedDict
import xml.etree.E | lementTree as etree
class Introspectable:
| class Element(object):
""" This is a basic introspectable object. This class will make
sure that the given xml element is of correct type and provide
some helper functions to simplify work of the children.
Children objects must implement TagName attribute, which contains
... |
from src.pla | tform.jboss.interfaces import JMXInterface
class FPrint(JMXInterface):
def __init__(self):
super(FPrint, self).__init__()
self.version = "5 | .0"
|
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodisco | ver()
urlpatterns = patterns('',
| (r'^profiles/', include('easy_profiles.urls')),
(r'^admin/', include(admin.site.urls)),
)
|
path[5+int(path[0]=="/"):])) #yay for dirty hacks
def fullPathToIcon(path):
p = os.path.normpath(os.path.abspath(path))
return p[len(MODFOLDER)-5:].replace('\\','/')
def getIcon(name):
img = os.path.join(util.CACHE_DIR, name)
if os.path.isfile(img):
logger.debug("Using cached preview image for... | png file (or whatever the extension of dest is"""
logger.debug("Creating png thumnail for %s to %s" % (sourcename, destname))
try:
img = bytearray()
buf = bytearray(16)
file = open(sourcename,"rb")
file.seek(128) # skip header
while file.readinto(buf):
img +... | /3) ** (1.0/2))
imageFile = QtGui.QImage(img,size,size,QtGui.QImage.Format_RGB888).rgbSwapped().scaled(100,100,transformMode = QtCore.Qt.SmoothTransformation)
imageFile.save(destname)
except IOError:
return False
if os.path.isfile(destname):
return True
else:
return ... |
"""
series.py
:copyright: (c) 2014-2015 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows how to use **SeriesReader** to get the data in various ways
But you can use them with **Reader** class as well
"""
import os
from pyexcel.ext import ods3
from pyexcel import SeriesReader
fro... | sional array but stack columns
data = to_array(reader.columns())
print(data)
# [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
# get a two dimensional array but stack columns
# in reverse order
data = to_array(reader.rcolumns())
print(data)
#[[7.0, 8.0, 9.0], [4.0, 5.0, 6.0], [... | r(OddRowFilter())
reader.filter(EvenColumnFilter())
data = to_dict(reader)
print(data)
# {u'Column 3': [8.0], u'Column 1': [2.0]}
# and you can write the filtered results
# into a file
w = Writer("example_series_filter.xls")
w.write_reader(reader)
w.close()
if __name__ == '__m... |
#!/usr/bin/env py | thon
print( | "Hello world!")
|
# Copyright 2014-2015 ARM Limited
#
# Licensed under the Ap | ache 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
# distribut | ed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from wlauto import LinuxDevice, Parameter
class OdroidXU3LinuxDevice(LinuxDevic... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import | migrations, models
class Migration(migrations.Migration):
dependencies = [
('customers', '0009_recipient_type'),
]
operations = [
migrations.AlterModelOptions(
name='recipient',
options={'ordering': [ | 'last_name'], 'verbose_name_plural': 'Recipients'},
),
]
|
'''
Given: A positive integer N≤100000, a number x between 0 and 1, and a DNA string s of length at most 10 bp.
Return: The probability that if N random DNA strings having the same length as s are constructed with GC-content x
(see “Introduction to Random Strings”), then at least one of the strings equals s.
We allo... | }
prob = 1
# probability of exactly equals to s
for b in s:
prob *= s_construct[b]
return 1 - (1 - prob) ** N
if __name__ == "__main__":
with open("data/rosalind_rstr.txt", "r") as f:
lines = f.readlines()
N = int(lines[0].rstr | ip().split(" ")[0])
x = float(lines[0].rstrip().split(" ")[1])
s = lines[1].rstrip()
with open("data/output_rstr.txt", "w") as o:
o.write(str(random_motif_match(N, x, s)))
print(random_motif_match(N, x, s))
|
#! /usr/bin/env python
"""Show file statistics by extension."""
import os
import sys
class Stats:
def __init__(self):
self.stats = {}
def statargs(self, args):
for arg in args:
if os.path.isdir(arg):
self.statdir(arg)
elif os.path.isfile(arg):
... | with("~"):
continue# Skip Emacs backup files
| full = os.path.join(dir, name)
if os.path.islink(full):
self.addstats("<lnk>", "links", 1)
elif os.path.isdir(full):
self.statdir(full)
else:
self.statfile(full)
def statfile(self, file):
head, ext = os.path.splitext(fil... |
return list(data)
else:
return [data]
HEX_ELEM = '[0-9A-Fa-f]'
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
HEX_ELEM + '{4}', HEX_ELEM + '{4}',
HEX_ELEM + '{12}'])
# Note: In order to ensure that the MAC address is unicast the first ... | _address': _validate_mac_address,
'type | :mac_address_or_none': _validate_mac_address_or_none,
'type:nameservers': _validate_nameservers,
'type:non_negative': _validate_non_negative,
'type:range': _validate_range,
'type:regex': _validate_regex,
'type:regex_or_none': _validate_regex_or_none,... |
#### | NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/food/shared_dish_cho_nor_hoola.iff"
result.attribute_template_... | S ####
return result |
rg/XML/1998/namespace'}
tag_ns = '{http://www.tei-c.org/ns/1.0}'
xml_ns = '{http://www.w3.org/XML/1998/namespace}'
def __init__(self, file_path):
tree = etree.parse(file_path)
self.__root = xpath(tree.getroot(), './tei:text/tei:body', self.ns)[0]
@classmethod
def _words(self, text_... | :param root: The root directory for this corpus. (default points to location in multext config file)
| :param fileids: A list or regexp specifying the fileids in this corpus. (default is oana-en.xml)
:param enconding: The encoding of the given files (default is utf8)
"""
TaggedCorpusReader.__init__(self, root, fileids, encoding)
def __fileids(self, fileids):
if fileids is None: file... |
#!/usr/bin/env python
from setuptools import setup
NAME = 'coinshot'
DESCRIPTION = 'simple python module for pushover.net'
VERSION = open('VERSION').read().strip()
LONG_DESC = open('README.rst').read()
LICENSE = "MIT License"
setup(
name=NAME,
version=VERSION,
author='Charles Thomas',
author_email='ch... | install_requires=["simplejson >= 3.3.0"],
scripts=['bin/shoot'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
... | ge :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Communications',
'Topic :: Software Development :: Libraries :: Python Modules']
)
|
import os
import tweepy
from query_db import query_db, send_user_queries_to_db, read_in_bb_file
from our_keys.twitter_keys import my_keys
from itertools import chain, repeat
u"""Reads in a file of cities and their bounding boxes. Queries the
database to get a list of all unique users who have tweeted from that
city. ... | eated_at.strftime('%m/%d/%Y, %H:%M')
location = tweet.geo
location_lat = None
| location_lng = None
if location:
location_lat = location['coordinates'][0]
location_lng = location['coordinates'][1]
hashtags = []
# if location:
tweet = (
screen_name, text, location_lat, location_lng,
created_at, hashtags, city
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Agent that gets the local keyboard input in the act() function.
Applies safety classifier(s) to process user and par... | Add command-line arguments sp | ecifically for this agent.
"""
agent = parser.add_argument_group('Safe Local Human Arguments')
agent.add_argument(
'--safety',
type=str,
default='all',
choices={'none', 'string_matcher', 'classifier', 'all'},
help='Apply safety filterin... |
ython
import roslib
roslib.load_manifest('human_model')
import rospy
import json
import tf
import numpy
from abc import ABCMeta,abstractmethod
from tf.transformations import quaternion_multiply as quatMult,quaternion_conjugate
from collections import deque,defaultdict,OrderedDict
"""Module for converting tf data to co... | "
cross=numpy.cross(v1,v2)
return normalize(numpy.append(cross,(1+numpy.dot(v1,v2),)))
class AveragePosition(object):
"""Example Position Class
Calculates the average of the last n positions lazily
Calculated value can be accessed or changed via pos attribute:
p=AveragePosition(10)
p.pos+=Vec(1,2,3)
print(p.po... | e functions,
must be defined in class:
@property
def pos(self):
...
@pos.setter
def pos(self,p):
...
def append(self,p):
...
"""
def __init__(self,n=100):
self.transformations=deque((Vec(0,0,0),),n)
self.calculated=None
@property
def pos(self):
if self.calculated is None:
self.calculated=numpy.av... |
#!/usr/bin/env python3
#
# This file generates an estimation of window size for the
# two queues for _each_ sample. It will not be exact, and
# it's correctness will vary with the variation of queue delay
# in the queue.
#
# The results are saved to:
# - derived/window
# each line formatted as: <sample id> <window ec... | n ms
rtts.append((queue_avg / 1000 + base_rtt) / 1000)
return rtts
def calc_window(rates, rtts_s):
windows = []
# all data should have same amount of samples
for i, rate in enumerate(rates):
rtt = r | tts_s[i] # rtt in seconds
windows.append(rate * rtt)
return windows
def write_window(file, window_ecn_list, window_nonecn_list):
with open(file, 'w') as f:
f.write('#sample_id window_ecn_in_bits window_nonecn_in_bits\n')
for i, window_ecn in enumerate(window_ecn_list):
... |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
import copy
import json
import re
from svtplay_dl.error import ServiceError
from svtplay_dl.fetcher.hls import hlsparse
from svtplay_dl.fetcher.http import HTTP
from svtplay_dl.service import OpenGraphThumbMixin
from svtplay_dl.se... | match_cfg_url:
player_url = match_cfg_url.group(1).replace("&", "&")
elif match_clip_page_cfg:
page_config = json.loads(match_clip_page_cfg.group(1))
player_url = page_config["p | layer"]["config_url"]
else:
yield ServiceError(f"Can't find video file for: {self.url}")
return
player_data = self.http.request("get", player_url).text
if player_data:
jsondata = json.loads(player_data)
if ("hls" in jsondata["request"]["files"]... |
# Copyright (c) 2013 eBay Inc.
# Copyright (c) 2012 OpenStack Foundation
# 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/lice... | free = float('inf')
else:
free = math.floor(host_state.free_capacity_gb * (1 - reserved))
return free
class All | ocatedCapacityWeigher(weights.BaseHostWeigher):
def _weight_multiplier(self):
"""Override the weight multiplier."""
return CONF.allocated_capacity_weight_multiplier
def _weigh_object(self, host_state, weight_properties):
# Higher weights win. We want spreading (choose host with lowest
... |
from PyQt4 import QtCore
import acq4.Manager
import acq4.util.imageAnalysis as imageAnalysis
run = True
man = acq4.Manager.getManager()
cam = man.getDevice('Camera')
frames = []
def collect(frame):
global frames
frames.append(frame)
cam.sigNewFrame.connect(collect)
def measure():
if len(frames)... | 0])
# conve | rt sigma to full width at 1/e
fit[0][3] *= 2 * 2**0.5
print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um"
print " fit:", fit
else:
global frames
frames = []
QtCore.QTimer.singleShot(2000, measure)
measure()
|
"""
This version of julian is currently in d | evelopment and is not considered s | table.
""" |
import timeit
import pyximport; pyximport.install()
from mod2 import cysum, cysum2
def pysum(start, step, count):
ret = sta | rt
for i in range(count):
ret += step
return ret
print('Python',
timeit.timeit('pysum(0, 1, 100)', 'from __main__ import pysum'))
print('Cython', timeit.timeit('cysum(0, 1, 100)', 'from __main__ import cysum'))
print( | 'Cython with types',
timeit.timeit('cysum2(0, 1, 100)', 'from __main__ import cysum2'))
|
# Copyright (C) 2008 LibreSoft
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ... | )
def __get_files_for_repository(self, repo_id, cursor):
query = "SELECT ft.file_id from file_types ft, files f " + \
"WHERE f.id = ft.file_id and f.repository_id = ?"
cursor.execute(statement(query, self.db.place_holder), (repo_id,))
files = [res[0] for res in cursor.fetch... | h is not None:
repo_uri = repo.get_uri_for_path(path)
else:
repo_uri = uri
cnn = self.db.connect()
cursor = cnn.cursor()
cursor.execute(statement("SELECT id from repositories where uri = ?",
db.place_holder), (repo_uri,)... |
# Copyright (c) 2018 PaddlePaddle 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... | 'OutScales': np.zeros(self.attrs['window_size']).astype("float32"),
'OutMovingScale':
np.array([self.scale['abs_max']]).astype("float32"),
'OutCurrentIter': np.zeros(1).astype("float32")
}
def test_check_output(self):
self.check_output()
if __name__ == "__mai... | unittest.main()
|
# -*- | coding: utf-8 -*-
import re
class StringParser(object):
@staticmethod
def removeCFU(stringToParse):
updatedString = re.sub('\s?[0-9] CFU.*', '', stringToParse)
return updatedString
@staticmethod
def startsWithUpper(stringToParse):
stringToPar | se = stringToParse[0].upper()+stringToParse[1:]
return stringToParse |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-22 14:42
from __future__ impo | rt unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0002_event'),
]
operations = [
migrations.AddField(
model_name='event',
name='publish_date',
field=models.DateTimeField(defa... | ]
|
st of fractional coordinates of kpoints as arrays or list of
Kpoint objects for BANDS mode calculation (standard path of
high symmetry k-points is automatically set as default)
tmax:
Maximum temperature (K) for calculation (default=1300)
tgrid:
... | set symprec to None.
cb_cut: by default 10% of the highest conduction bands are
removed because they are often not accurate.
Tune cb_cut to change the percentage (0-100) of bands
that are removed.
timeout: overall time limit (in seconds): mainly to... | oop when trying to find Fermi levels.
"""
self.lpfac = lpfac
self._bs = bs
self._nelec = nelec
self.dos_type = dos_type
self.energy_grid = energy_grid
self.error = []
self.run_type = run_type
self.band_nb = band_nb
self.spin = spin
... |
from seth import versioning
from seth.tests import IntegrationTestBase
from seth.classy.rest import generics
class DefaultVersioningResource(generics.GenericApiView):
def get(self, **kwargs):
return {}
class NotShowVersionResource(generics.GenericApiView):
display_version = False
def get(self,... | default_version = '22.0'
def get_allowed_version(self):
return ['5.0']
class CheckQueryParamsResourceSecond(generics.GenericApiView):
versioning_policy = AllowVersionOnePolicy
def get(self, **kwargs):
return {}
config.regi... | elf.app.get('/test_query_params')
self.assertEqual(r.status_int, 200)
def test_wrong_version_in_query_params_all_versions_allowed(self):
r = self.app.get('/test_query_params?version=2.0')
self.assertEqual(r.status_int, 200)
def test_correct_version_in_query_params_all_versions_allowed(... |
INATE = 0x8
SEL_SCOPE = 0x10
SEL_ | DIR_LTR = 0x20
SEL_DIR_RT | L = 0x40
SEL_IN_RANGE = 0x80
SEL_OUT_OF_RANGE = 0x100
SEL_DEFINED = 0x200
SEL_PLACEHOLDER_SHOWN = 0x400
class Immutable(object):
"""Immutable."""
__slots__ = ('_hash',)
def __init__(self, **kwargs):
"""Initialize."""
temp = []
for k, v in kwargs.items():
... |
order, copy=copy)
if dtype is not None:
assert_equal(X_checked.dtype, dtype)
else:
assert_equal(X_checked.dtype, X.dtype)
if order == 'C':
assert_true(X_checked.flags['C_CONTIGUOUS'])
assert_false(X_checked.flags['F_CONTIGUOUS'])
elif order... | imensions even if this is
# not mandatory
assert_raise_message(ValueError, msg, check_X_y, X, y,
ensure_min_samples=2, ensure_2d=False)
# Simulate a model that would require at least 3 features (e.g. SelectKBest
# with k=3)
X = np.ones((1 | 0, 2))
y = np.ones(2)
msg = "2 feature(s) (shape=(10, 2)) while a minimum of 3 is required."
assert_raise_message(ValueError, msg, check_X_y, X, y,
ensure_min_features=3)
# Only the feature check is enabled whenever the number of dimensions is 2
# even if allow_nd is enable... |
#!/usr/bin/env python
# Copyright (c) 2016 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
# pylint: d... | self.asse | rtTrue(mock_method.called)
def test_env_show(self):
with mock.patch.object(self._env, 'show') as mock_method:
result = self.runner.invoke(cli_base.env_show)
self.assertEqual(result.exit_code, 0)
self.assertTrue(mock_method.called)
def test_testcase_list(self):
... |
from pylayers.antprop.antenna import *
from pylayers.antprop.antvsh import *
import matplotlib.pylab as plt
from numpy import *
import pdb
"""
Th | is test :
1 : loads a measured antenna
2 : applies an electrical delay obtained from data with getdelay method
3 : evaluate the antenna vsh coefficient with a downsampling factor of 2
4 : evaluates the relative er | ror of reconstruction (vsh3) for various values of order l
5 : display the results
"""
filename = 'S1R1.mat'
A = Antenna(filename,'ant/UWBAN/Matfile')
B = Antenna(filename,'ant/UWBAN/Matfile')
#plot(freq,angle(A.Ftheta[:,maxPowerInd[1],maxPowerInd[2]]*exp(2j*pi*freq.reshape(len(freq))*electricalDelay)))
freq =... |
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 Softwa... | current_idx = None
for i, item in enumerate(items):
if item.active:
if current_idx is not None:
raise ValueError("Multiple active items ({} and {}) "
"found!".format(current_idx, i))
else:
current_idx = i
if i... | current_idx = 0
### Source/WebKit/qt/Api/qwebhistory.cpp operator<<
stream.writeInt(HISTORY_STREAM_VERSION)
stream.writeInt(len(items))
stream.writeInt(current_idx)
for i, item in enumerate(items):
_serialize_item(i, item, stream)
user_data.append(item.user_data)
stream.device... |
"""
@brief test tree node (time=50s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder, ExtTestCase
from pyquickhelper.pycode.venv_helper import create_virtual_env
class TestVenvHelper(ExtTestCase):
def test_venv_empty(self):... | _name__ != "__main__":
# does not accept virtual environment
return
temp = get_temp_folder(__file__, "temp_venv_empty")
out = create_virtual_env(temp, fLOG=fLOG)
fLOG("-----")
fLOG(out)
fLOG("-----")
pyt = os.path.join(temp, "Scripts")
sel... | == "__main__":
unittest.main()
|
ath(root)
self.show_hidden = show_hidden
self.base_path = base_path.rstrip("/")
def propfind(self, path, depth, request_xml):
# TODO implement support for allprop
paths = self._build_paths(path, depth)
return multi_status.MultiStatus(self._get_properties(paths, request_xml... | V:}quota-used-bytes":
prop_stat.add_quota_used_bytes((fs | _st.f_blocks - fs_st.f_bavail) * fs_st.f_frsize)
else:
print "Request for not supported property %s" % property_
href = self.base_path + p[len(self.root):]
result.append(multi_status.Response(href, prop_stat))
return result
def _build_displayn... |
# Copyright (c) 2012-2015 The GPy authors (see AUTHORS.txt)
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import scipy
from ..util.univariate_Gaussian import std_norm_cdf, std_norm_pdf
import scipy as sp
from ..util.misc import safe_exp, safe_square, safe_cube, safe_quad, safe_three_ti... | def d3transf_df3(se | lf,f):
ef = safe_exp(f)
ef2 = safe_square(ef)
three_times_ef = safe_three_times(ef)
r_val = np.exp(f-ef)*(1.-three_times_ef + ef2)
return r_val
class Log(GPTransformation):
"""
.. math::
g(f) = \\log(\\mu)
"""
def transf(self,f):
return safe_exp... |
def dev_nav(active=None):
from uliweb import settings
out = "<span>"
for i in settings.MENUS_DEVELOP.nav:
if active!=i["name"]:
out += "<a href='%s'>%s<a> "%(i["link"],i["title"])
else:
out += "<strong>%s</strong> "%(i["title"])
out += "</span>"
| return out
| |
import os
f | rom traits.api import HasTraits
from traitsui.api import View, Item
from enable.savage.trait_defs.ui.svg_button import SVGButton
pause_icon = os.path.join(os.path.dirname(__file__), 'player_pause.svg') |
resume_icon = os.path.join(os.path.dirname(__file__), 'player_play.svg')
class SVGDemo(HasTraits):
pause = SVGButton('Pause', filename=pause_icon,
toggle_filename=resume_icon,
toggle_state=True,
toggle_label='Resume',
toggle_... |
if sock is not None:
sock.close()
def exithook(self):
"override for specific exit action"
os._exit(0)
def debug(self, *args):
if not self.debugging:
return
s = self.location + " " + str(threading.current_thread().name)
for a in args:
... | :%d:call getresponse(): " % seq)
response = self.getresponse(seq, wait=0.05)
self.debug(("asyncreturn:%d:response: " % seq), response)
return self.decoderesponse(response)
def decoderesponse(self, response):
how, what = response
if how == "OK":
return what
... | if how == "EXCEPTION":
self.debug("decoderesponse: EXCEPTION")
return None
if how == "EOF":
self.debug("decoderesponse: EOF")
self.decode_interrupthook()
return None
if how == "ERROR":
self.debug("decoderesponse: Internal ERROR:... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import easyiceconfig as EasyIce
import jderobotComm as comm
import sys, signal
sys.path.append('/usr/local/share/jderobot/python/visualHFSM_py')
import traceback, threading, time
from automatagui import AutomataGui, QtGui, GuiSubautomata
from jderobot import MotorsPrx
from jd... | .newGuiNode(1, 0, 69, 163, 1, 'GoForward')
guiSubautomata1.newGuiNode(2, 0, 255, 117, 0, 'GoBack')
guiSubautomata1.newGuiTransition((69, 163), (255, 117), (139, 78), 1, 1, 2)
guiSubautomata1.newGuiTransition((255, 117), (69, 163), (189, 196), 2, 2, 1)
guiSubautomataList.append(guiSubautomat | a1)
return guiSubautomataList
def shutDown(self):
self.run1 = False
def runGui(self):
app = QtGui.QApplication(sys.argv)
self.automataGui = AutomataGui()
self.automataGui.setAutomata(self.createAutomata())
self.automataGui.loadAutomata()
self.startThreads()
self.automataGui.show()
app.exec_()
... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS IoT Analytics"
prefix = "iotanalytics"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
... | atchPutMessage = Action("BatchPutMessage")
CancelPipelineReprocessing = Action("CancelPipelineReprocessing")
CreateChannel = Action("CreateChannel")
CreateDataset = Action("CreateDataset")
CreateDatasetContent = Action("CreateDatasetContent")
CreateDatastore = A | ction("CreateDatastore")
CreatePipeline = Action("CreatePipeline")
DeleteChannel = Action("DeleteChannel")
DeleteDataset = Action("DeleteDataset")
DeleteDatasetContent = Action("DeleteDatasetContent")
DeleteDatastore = Action("DeleteDatastore")
DeletePipeline = Action("DeletePipeline")
DescribeChannel = Action("Describ... |
IN | STALLED_APPS= ["django_nose"]
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-xunit',
'--xunit-file=jenkins/n | osetests.xml',
]
|
import os
from anchore_engine.analyzers.syft.handlers.common import save_entry_to_findings
from anchore_engine.analyzers.utils import dig
def save_entry(findings, engine_entry, pkg_key=None):
if not pkg_key:
pkg_name = engine_entry.get("name", "")
pkg_version = engine_entry.get(
"vers... | hon",
"cpes": artifact.get("cpes", []),
}
# inject the artifact docu | ment into the "raw" analyzer document
save_entry(findings, pkg_value, pkg_key)
|
# Copyright 2014-2016 OpenMarket Ltd
#
# 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 w... | eypad(0)
curses.echo()
curses.endwin()
class Callbac | k:
def __init__(self, stdio):
self.stdio = stdio
def on_line(self, text):
self.stdio.print_line(text)
def main(stdscr):
screen = CursesStdIO(stdscr) # create Screen object
callback = Callback(screen)
screen.set_callback(callback)
stdscr.refresh()
reactor.addReader(scre... |
TextSearch(self.auth, terms)
else:
# Note: I don't want to bother with `maxNumResults` so we set
# it to a big number.
BIG = 1000000
issues = self.server.jira1.getIssuesFromTextSearchWithProject(
self.auth, project_keys, terms, BIG)
if ... | ches) > 1:
raise JiraShellError(
"'%s' is ambiguous: matching resolutions: \"%s\"" % (
name, '", "'.join([r["name"] for r in matches])))
if | not resolutionObj:
raise JiraShellError("no resolution found matching %r" % name)
return resolutionObj["id"]
def resolve(self, key):
"""Resolve the given issue.
TODO: what is the result when the workflow change is illegal?
"""
# 5 === "Resolved". Is that true f... |
#!/usr/bin/env python
# runTests.py -- Portage Unit Test Functionality
# Copyright 2006-2017 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
import os, sys
import os.path as osp
import grp
import platform
import pwd
import signal
def debug_signal(signum, frame):
import pdb
pdb.s... | viron["PORTAGE_USERNAME"] = pwd.getpwuid(os.getuid()).pw_name
os.environ["PORT | AGE_GRPNAME"] = grp.getgrgid(os.getgid()).gr_name
# Insert our parent dir so we can do shiny import "tests"
# This line courtesy of Marienz and Pkgcore ;)
repoman_pym = osp.dirname(osp.dirname(osp.dirname(osp.realpath(__file__))))
sys.path.insert(0, repoman_pym)
# Add in the parent portage python modules
portage_pym ... |
import os
import | py
import pytest
import numpy as np
import openpnm as op
from openpnm.models.misc import from_ne | ighbor_pores
@pytest.mark.skip(reason="'netgen' is only available on conda")
class STLTest:
def setup_class(self):
np.random.seed(10)
self.net = op.network.Cubic(shape=[2, 2, 2])
self.net["pore.diameter"] = 0.5 + np.random.rand(self.net.Np) * 0.5
Dt = from_neighbor_pores(target=se... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 Anso Labs, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# ... | ==============
.. automodule:: nova
:platform: Unix
:synopsis: Infrastructure-as-a-Service Cloud platform.
.. moduleauthor:: Jesse Andrews <jesse@ansolabs.com>
.. moduleauthor:: | Devin Carlen <devin.carlen@gmail.com>
.. moduleauthor:: Vishvananda Ishaya <vishvananda@yahoo.com>
.. moduleauthor:: Joshua McKenty <joshua@cognition.ca>
.. moduleauthor:: Manish Singh <yosh@gimp.org>
.. moduleauthor:: Andy Smith <andy@anarkystic.com>
"""
from exception import * |
"""
EtcUdevRules - file ``/etc/udev/rules.d/``
==========================================
This module is similar to the :py:mod:`insights.parsers.udev_rules`
but parse .rules files under ``/etc/ude/rules.d/`` directory instead.
The parsers included in this module are:
UdevRules40Redhat - file ``/etc/udev/rules.d/40-... | supposed to check the syntax of some specific line, so here the
:class:`insights.core.LogFileOutput` is the base class.
Sample input::
# do not edit this file, it will be overwritten on update
# CPU hotadd request
SUBSYSTEM=="cpu", ACTION=="add", TEST=="online", ATTR{online}... | equest
SUBSYSTEM!="memory", ACTION!="add", GOTO="memory_hotplug_end"
PROGRAM="/bin/uname -p", RESULT=="s390*", GOTO="memory_hotplug_end"
LABEL="memory_hotplug_end"
Examples:
>>> 'LABEL="memory_hotplug_end"' in udev_rules.lines
True
"""
def __init__(self, *args, **kw... |
import numpy as np
import theano
from theano import tensor as T
from generateTrainDataonText import createTrain
from neuralmodels.utils import permute
from neuralmodels.loadcheckpoint import *
from neuralmodels.costs import softmax_loss
from neuralmodels.models import *
from neuralmodels.predictions import OutputMaxPro... | p_labels):
N = p_labels.shape[1]
T = p_labels.shape[0]
text_output = []
for i in range(N):
t = ''
for j in p_labels[:,i]:
t = t + class_ids_reverse[j]
text_output.append(t)
return text_output
if __name__ == '__main__':
num_samples = 10000
num_validation = 100
num_train = num_samples - num_validation
... | y_after=5
[X,Y,num_classes,class_ids_reverse] = createTrain('shakespeare_input.txt',num_samples,len_samples)
inputD = num_classes
outputD = num_classes
permutation = permute(num_samples)
X = X[:,permutation]
Y = Y[:,permutation]
X_tr = X[:,:num_train]
Y_tr = Y[:,:num_train]
X_valid = X[:,num_train:]
Y_vali... |
import getpass
import json
import getopt
from genericpath import isfile
from os.path import sep
from pingdumb.main_module import url_type
def read_config():
f_path = "." + sep + "pingdumb.json"
if not isfile(f_path):
f = open(f_path, 'w')
conf = {
"url": "jellyms.kr",
... | n conf:
del conf['smtpPw']
f_path = "." + sep + "pingdumb.json"
f = open(f_path, 'w')
f.truncate()
f.write(json.dumps(conf))
f.close()
def input_conf(message, default):
value = input(message)
if not value:
return default
return value
def set_config():
configure = ... | = input_conf(
"Receive mail? (" + configure["toEmail"] + ")",
configure["toEmail"]
)
s_server = input_conf(
"SMTP server? (" + configure["smtpServer"] + ")",
configure["smtpServer"]
)
s_user = input_conf(
"SMTP Server username? (" + configure["smtpUser"] + ")",
... |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import cStringIO
import difflib
import os
import sys
import unittest
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD... | ""
struct Foo {
std::string name;
int problems[99];
};"""
self._RunTest(template, expected, {
'name': 'Foo',
'fields': [
{'name': 'name', 'type': 'std::string'},
{'name': 'problems', 'type': 'array', 'basetype': 'int', 'size': 99}]})
def testModulo(s | elf):
self._RunTest('No expression %', 'No expression %', {})
self._RunTest('% before {{3 + 4}}', '% before 7', {})
self._RunTest('{{2**8}} % after', '256 % after', {})
self._RunTest('inside {{8 % 3}}', 'inside 2', {})
self._RunTest('Everywhere % {{8 % 3}} %', 'Everywhere % 2 %', {})
if __name__ =... |
"""
WSGI config for Tuteria-Application-Test project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WS... | he Django one. For | example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
from django.core.wsgi import get_wsgi_application
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsg... |
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
clusters = kmeans.fit_predict(digits.data)
print kmeans.cluster_centers_.shape
#------------------------------------------------------------
# visualize the cluster centers
fi | g = plt.figure(figsize=(8, 3))
for | i in range(10):
ax = fig.add_subplot(2, 5, 1 + i)
ax.imshow(kmeans.cluster_centers_[i].reshape((8, 8)),
cmap=plt.cm.binary)
from sklearn.manifold import Isomap
X_iso = Isomap(n_neighbors=10).fit_transform(digits.data)
#------------------------------------------------------------
# visualize the ... |
from typing import List
from collections import defaultdict, Counter
class Solution:
def shortestCompletingWordV1(self, licensePlate: str, words: List[str]) -> str:
# build the signature of licensePlate
sig = defaultdict(int)
for c in licensePlate.upper():
if c.isalpha():
... | cu = c.upper()
if cu not in wsig:
continue
wsig[cu] -= 1
if wsig[cu] == 0:
del wsig[cu]
if len(wsig) == 0 and (len(word) < len(ans) or ans == ''):
ans = word
break
... | tingWordV2(self, licensePlate: str, words: List[str]) -> str:
"""
In first line, just filter out all none letters from the plate and make sure all letters are lower case.
In second line, produce Counter of each words and use Counter operater & (intersection) to extract the count of shared letter... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-04-28 15:02
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Mi | gration):
dependencies = [
('base', '0106_auto_20170428_111 | 9'),
]
operations = [
migrations.AddField(
model_name='learningunit',
name='learning_container',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='base.LearningContainer'),
),
]
|
ne,
)
)
log_str = (
"\n"
+ "=" * 80
+ "\n"
+ "DAG File Processing Stats\n\n"
+ tabulate(formatted_rows, headers=headers)
+ "\n"
+ "=" * 80
)
self.log.info(log_str)
def get_pid(se... | de
:return: the PID of the process processing the given file or None if
the specified file is not being processed
:rtype: int
"""
if file_path in self._processors:
return self._processors[file_path].pid
return None
def get_all_pids(self):
"""
... | turn: a list of the PIDs for the processors that are running
:rtype: List[int]
"""
return [x.pid for x in self._processors.values()]
def get_last_runtime(self, file_path):
"""
:param file_path: the path to the file that was processed
:type file_path: unicode
... |
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
r | eturn socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:1 | 5])
)[20:24])
>>> get_ip_address('lo')
'127.0.0.1'
>>> get_ip_address('eth0')
'38.113.228.130'
|
],
24,
background="#555555"
),
left=bar.Gap(16),
right=bar.Gap(20),
x=0, y=0, width=600, height=480
),
Screen(
top=bar.Bar(
[
widget.GroupBox(),
... | == 'xclock'
# width/height unchanged
assert qtile.c.window.info()['width'] == | 164
assert qtile.c.window.info()['height'] == 164
# x is shifted by 600, y is shifted by 0
assert qtile.c.window.info()['x'] == 616
assert qtile.c.window.info()['y'] == 0
assert qtile.c.window.info()['group'] == 'a'
assert qtile.c.group.info()['floating_info']['clients'] == ['xclock']
# mov... |
# Copyright (C) 2015 https://github.com/thof
#
# This file is part of decapromolist.
#
# decapromolist 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
# any later version.
#... | subId = url[start:url.find('-', start)]
# subId = cat.attrib['data-sec | ondary-category-id']
subName = cat.text
data = {'subId': int(subId), 'url': Utils.getConfig()['siteURL'] + url, 'subName': subName}
dataCat.append(data)
return dataCat
def getCategories(self):
categories = []
catUrl = []
content = urllib2.urlopen(... |
f | rom django.db.backends import BaseDatabaseIntrospection
class DatabaseIntrospection(BaseDatabaseIntrospection):
def get_table_list(self, cursor):
"Returns a list of table names in the current database."
curs | or.execute("SHOW TABLES")
return [row[0] for row in cursor.fetchall()]
|
"""
2x2 plotting anal | ysis for 2 datasets pluggin
| ------------- | ------------- |
| contours from | pcolor from |
| both datasets | dataset 1 | |
| ------------- | ------------- |
| pcolor diff | pcolor from |
| both datasets | dataset 2 |
| ------------- | ------------- |
colorbar location = bottom
"""
class SampleException(Exception):
pass
_NDATASETS = 2
_NPANNELS = 4
def run(cases, compares, domain, **kwargs):
"""... |
# import logging
from ast.visit import visit as v
from ast.node import Node
from ast.body.methoddeclaration import MethodDeclaration
from ast.stmt.minrepeatstmt import MinrepeatStmt
class Desugar(object):
def __init__(self):
self._cur_mtd = None
@v.on("node")
def visit(self, node):
"""... |
@v.when(MinrepeatStmt)
def visit(self, node):
raise NotImplementedError
# Old impl
# @v.when(Statement)
# def visit(self, node):
# if node.kind == C.S.MINREPEAT:
# b = '\n'.join(map(str, node.b))
# body = u""
# for i in xrange(9): # TODO: pa... | ""
# if (??) {{ {} }}
# """.format(b)
# logging.debug(
# "desugaring minrepeat @ {}".format(self._cur_mtd.name))
# return to_statements(self._cur_mtd, body)
# return [node]
|
# -*- coding: utf-8 -*-
# Simple script to test sending UTF8 text with the GrowlNotifier class
import loggi | ng
logging.basicConfig(level=logging.DEBUG)
from gntp.notifier import GrowlNotifier
import platform
growl = GrowlNotifier(notifications=['Testing'],password='password',hostname='ayu')
growl.s | ubscribe(platform.node(),platform.node(),12345)
|
from __future__ import absolute_import
from unittest import TestCase, skip
from ..goodman_ccd import get_args, MainApp
class MainAppTest(TestCase):
def setUp(self):
self.main_app = MainApp()
def tes | t___call__(self):
self.assertRaises( | SystemExit, self.main_app)
def test___call___show_version(self):
arguments = ['--version']
args = get_args(arguments=arguments)
self.assertRaises(SystemExit, self.main_app, args)
|
# | !flask/bin/python
from gb import app
app.run(debug=True) | |
_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: postgresql_schema
short_description: Add or remove PostgreSQL schema from a remote host
description:
- Add or r... | ry)
return True
else:
schema_info = get_schema_info(cursor, schema)
if owner and owner != schema_info['owner']:
return set_owner(cursor, schema, owner)
else:
return False
def schema_matches(cursor, schema, owner):
if not schema_exists(cursor, schema):
... | turn False
else:
return True
# ===========================================
# Module execution.
#
def main():
module = AnsibleModule(
argument_spec=dict(
login_user=dict(default="postgres"),
login_password=dict(default="", no_log=True),
login_host=di... |
{
"uri": "*",
"publish": True,
"subscribe": True,
"call": True,
"register": True
... | },
{
"type": "guest",
"executable": sys | .executable,
"arguments": [os.path.join(self.code_location, "myapp.py")]
}
]
}
myapp = """#!/usr/bin/env python
print("Loaded the component!")
"""
self._start_run(config, myapp, expected_stdout, expected_stderr,
_check)
... |
# Copyright 2017 Huawei Technologies Co.,LTD.
# 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
#
# Unl... | mport rest
class APIBase(wtypes.Base):
created_at = wsme.wsattr(datetime.datetime, readonly=True)
"""The time in UTC at which the object is created"""
updated_at = wsme.wsattr(datetime.datetime, readonly=True)
"""The time in UTC at which the object is updated"""
def as_dict(self):
"""R | ender this object as a dict of its fields."""
return dict((k, getattr(self, k))
for k in self.fields
if hasattr(self, k) and getattr(self, k) != wsme.Unset)
class CyborgController(rest.RestController):
def _handle_patch(self, method, remainder, request=None):
... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(ker | nel):
result = Intangible()
result.template = "object/draft_schematic/space/chassis/shared_hu | tt_medium_s02.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# note: we use 127.0.0.1 rather than localhost because on some platforms
# localhost might not be correctly configured as an alias for the loopback
# address. (ahem: Windows)
SERVER_HOST = '127.0.0.1'
def ShouldEnableTernCompleter():
"""Returns whether or not the tern completer is 'installed'. That is whether
or... | tFolders( starting_directory ):
tern_project = os.path.join( folder, '.tern-project' )
if os.path.exists( tern_project ):
return tern_project
# As described here: http://ternjs.net/doc/manual.html#server a global
# .tern-config file is also supported for the Tern server. This can pro | vide
# meaningful defaults (for libs, and possibly also for require paths), so
# don't warn if we find one. The point is that if the user has a .tern-config
# set up, then she has deliberately done so and a ycmd warning is unlikely
# to be anything other than annoying.
tern_config = os.path.expanduser( '~/.te... |
import csv
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
from scipy.optimize import curve_fit
def countKey(key,listDataDicts):
outDict = {}
for row in listDataDicts:
try:
outDict[row[key]] += 1
except KeyError:
outDict[row[key]] = 1
... | )
print "Drug First Use Age vs Usage Frequency Linear Regression"
print "Slope: %f, Intercept: %f, | RSQ-Value: %f, P-Value: %f, Standard Error: %f,\n 95%% Confidence Interval: %f +- %f\n" %(slope,intercept,rValue*rValue,pValue,stdErr, slope, 1.96*stdErr)
'''# Curve fit with a power law
xfit = range(90)
popt1, pcov1 = curve_fit(powerLaw, xdata, ydata)
print "Power Law Curve fit: ",popt1,np.sqrt(np.diag(pcov1)),"\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.