prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from lib.font import *
import sys
import fcntl
import termios
import struct
class progress_bar(object):
def __init__(self, tot=100, lenght=10):
self.cp='/-\|'
self.bar_lenght = lenght
self.tot = tot
def startprogress(self, title):
"""Creates a progress bar 40 chars long on the console
and moves cursor ba... | beginning | with BS character"""
sys.stdout.write(title + ": [" + "-" * self.bar_lenght + "]" + chr(8) * (self.bar_lenght+1))
sys.stdout.flush()
def progress(self, x):
"""Sets progress bar to a certain percentage x.
Progress is given as whole percentage, i.e. 50% done
is given by x = 50"""
y = int(x)%4
z = int((x/f... |
def _types_gen(T):
yield T
if hasattr(T, 't'):
for l in T.t:
yield l
if hasattr(l, 't'):
for ll in _types_gen(l):
yield ll
class Type(type):
""" A rudimentary extension to `type` that provides polymorphic
types for run-time type checking of JSON data types. IE:
assert type... | gs)
return self
def kind(self, t):
if type(t) is Type:
return t
ty = lambda t: type(t)
if type(t) is type:
ty = lambda t: t
return reduce(
lambda L, R: R if (hasattr(R, 't') and ty(t) == R) else L,
filter(lambda T: T is not Any,
_types_gen(self)))
def decode(sel... | lambda L, R: R if (str(R) == n) else L,
_types_gen(self))
# JSON primatives and data types
Object = Type('Object', (object,), {}).I(dict).N('obj')
Number = Type('Number', (object,), {}).I(int, long).N('num')
Boolean = Type('Boolean', (object,), {}).I(bool).N('bit')
String = Type('String', (object,), {}).I(st... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | is missing.'}, error_code=400)
d = json.loads(request.POST['job'])
job = client.Job.from_dict(d)
try:
c = client.SqoopClient(conf.SERVER_URL.get(), request.user.username, request.LANGUAGE_CODE)
response['job'] = c.create_job(job). | to_dict()
except RestException, e:
response.update(handle_rest_exception(e, _('Could not create job.')))
except SqoopException, e:
response['status'] = 100
response['errors'] = e.to_dict()
return HttpResponse(json.dumps(response), mimetype="application/json")
@never_cache
def update_job(request, job)... |
Base>############################################################
def Base(A):
B=[] #inicializa la matriz B. esta matriz contiene las ORDENADAS posiciones de la base canonica
CB=[] #Contiene las posiciones de la base ordenadas de derecha a izquierda
for j in range(len(A[1])-1,0,-1) : #Recorremos la... | la matriz canonica
B.append(j)
return B
##</Identificar la Base>##################### | #######################################
##<Identificar variables de entrada y salida>############################################################
def EntradaSalida(A,ZC,XB,min_max) :
entrada = 0 #iniciamos la entrada, es decir el valor j en cero
salida = 0
if min_max == "M" :
for i in range(1,len(ZC)) : ... |
imp | ort pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 20, ar_order | = 0); |
# Copyright 2018 Flight Lab 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | ermissions and
# limitations under the License.
"""Library for network related helpers."""
import socket
def get_ip():
"""Get primary IP (the one with a default route) of local machine.
This works on both Linux and Windows platforms, and doesn't require | working
internet connection.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
return s.getsockname()[0]
except:
return '127.0.0.1'
finally:
s.close()
|
LASS: FuelCellEngDclDataParticleRecovered
}
}
self._telemetered_parser_config = {
DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.fuelcell_eng_dcl',
DataSetDriverConfigKeys.PARTICLE_CLASS: None,
DataSetDriverConfigKeys.PARTICLE_CLASSES_DICT: {... | ""
Read file and verify that all expected particles can be read.
Verify that the expected number of particles are produced.
Only one test is run as the content of the input files is the
same for recovered or telemetered.
"""
log.debug('===== START TEST BIGFILE =====')
... | .log'), 'rU') as file_handle:
parser = FuelCellEngDclParser(self._recovered_parser_config,
file_handle,
self.exception_callback)
particles = parser.get_records(num_particles_to_request)
self.assert... |
"""
Github Authentication
"""
import httplib2
from django.conf import settings
from django.core.mail import send_mail
from oauth2client.client import OAuth2WebServerFlow
from helios_auth import utils
# some parameters to indicate that status updating is not possible
STATUS_UPDATES = False
# display tweaks
LOGIN_ME... | itHub not verified")
return {
'type': 'github',
'user_id': user_id,
'name': '%s (%s)' % (user_id, user_name),
'info': {'email': user_email},
'token': {},
}
def do_logout(user):
return None
def update_status(token, message):
pass
def send_message(user_id, name, user_info, subject, body):
... | eligibility, user_info):
pass
#
# Election Creation
#
def can_create_election(user_id, user_info):
return True
|
result = self.initialize()
if result['OK']:
self.valid = True
else:
gLogger.error("Keystone initialization failed: %s" % result['Message'])
def initialize(self):
""" Initialize the Keystone object obtaining the corresponding token
:return: S_OK/S_ERROR
"""
self.log.debug("In... | "protocol": 'mapped'}}}}
if self.parameters.get('Proxy'):
authArgs['cert' | ] = self.parameters.get('Proxy')
elif appcred_file:
# The application credentials are stored in a file of the format:
# id secret
ac_fd = open(appcred_file, 'r')
auth_info = ac_fd.read()
auth_info = auth_info.strip()
ac_id, ac_secret = auth_info.split(" ", 1)
ac_fd.close()
... |
from pymemcache.client.hash import HashClient
from pymemcache.client.base import Client, PooledClient
from pymemcache.exceptions import MemcacheError, MemcacheUnknownError
from pymemcache import pool
from .test_client import ClientTestMixin, MockSocket
import unittest
import pytest
import mock
import socket
class Te... | (b'key3', b'value2', noreply=False)
result = client.get_many([b'key1', b'key3'])
assert result == {}
def test_gets_many(self):
client = self.make_client(*[
[b'STORED\r\n', b'VALUE key3 0 6 1\r\nvalue2\r\nEND\r\n', ],
[b'STORED\r\n', b'VALUE key1 0 6 1\r\nvalue1\r\nEN... | return client.clients['127.0.0.1:11012']
else:
return client.clients['127.0.0.1:11013']
client._get_client = get_clients
assert client.set(b'key1', b'value1', noreply=False) is True
assert client.set(b'key3', b'value2', noreply=False) is True
resu... |
oman_first_name'
db.delete_column('people_persontranslation', 'roman_first_name')
# Deleting field 'PersonTranslation.roman_last_name'
db.delete_column('people_persontranslation', 'roman_last_name')
# Deleting field 'PersonTranslation.non_roman_first_name'
db.delete_column('peo... | : ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length' | : '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.mod... |
import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
""... | the mount manager for unmounting the selected URI"""
pass
def focus_object(self):
"""Method called b | y the mount manager for focusing main object"""
pass
@classmethod
def get_features(cls):
"""Returns set of features supported by extension"""
return cls.features
|
"""
Basic building blocks for generic class based views.
We don't bind behaviour to http method handlers yet,
which allows mixin classes to be composed in interesting ways.
"""
from __future__ import unicode_literals
from django.http import Http404
from rest_framework import status
from rest_framework.response import... | :
created = False
save_kwargs = {'force_update': True}
su | ccess_status_code = status.HTTP_200_OK
serializer = self.get_serializer(self.object, data=request.DATA,
files=request.FILES, partial=partial)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(**save... |
import cv2
import numpy as np
import os
from vilay.core.Descriptor import MediaTime | , Shape
from vilay.detectors.IDete | ctor import IDetector
from vilay.core.DescriptionScheme import DescriptionScheme
class FaceDetector(IDetector):
def getName(self):
return "Face Detector"
def initialize(self):
# define haar-detector file
print os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_frontalfac... |
ty': Quality.SDDVD, 'status': common.DOWNLOADED,
'unaired': False, 'manual': True}, []),
({'upgradeonce': True, 'quality': Quality.SDDVD, 'status': common.ARCHIVED,
'unaired': False, 'manual': True}, []),
# HDTV (between init qualities)
({'u... | ': Quality.HDWEBDL, 'status': common.DOWNLOADED,
'unaired': False, 'manual': True}, []),
({'upgradeonce': True, 'quality': Quality.HDWEBDL, 'status': common.ARCHIVED,
'unaired': False, 'manual': True}, []),
# FULLHDWEBDL (above init quality + unwanted)
... | deonce': True, 'quality': Quality.FULLHDWEBDL, 'status': common.SNATCHED,
'unaired': False, 'manual': True}, []),
({'upgradeonce': True, 'quality': Quality.FULLHDWEBDL, 'status': common.SNATCHED_PROPER,
'unaired': False, 'manual': True}, []),
({'upgradeonc... |
def decode_args(s, delimiter="|", escapechar="\\"):
args = []
escaping = False
current_arg = ""
for c in s:
if escaping:
current_arg += c
| escaping = False
elif c == escapechar:
escaping = True
elif c == delimiter:
args.append(current_arg)
current_arg = | ""
else:
current_arg += c
args.append(current_arg)
return args
def encode_args(args, delimiter="|", escapechar="\\"):
encoded_args = ""
for idx, arg in enumerate(args):
if idx > 0:
encoded_args += delimiter
if not isinstance(arg, str):
arg =... |
#
# Python module to parse OMNeT++ vector files
#
# Currently only suitable for small vector files since
# everything is loaded into RAM
#
# Authors: Florian Kauer <florian.kauer@tuhh.de>
#
# Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology
# All rights reserved.
#
# Redistribution and use ... | ime)
self.maxtime = max(self.maxtime,time)
self.dataValues[vect | or].append(float(m.group(4)))
else:
# vector 7 Net802154.host[0].ipApp[0] referenceChangeStat:vector ETV
m = re.search("vector *([0-9]*) *([^ ]*) *(.*):vector",line)
if m:
number = int(m.group(1))
module = m.group(2)
... |
# Copyright (c) 2013-2016 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# di... | et setting value [#channel]".')
return
# Check that this channel is in our config
if len(m.line) <= 3:
chan = m.location
e | lif len(m.line) == 4:
if m.line[3][0] != "#":
m.bot.private_message(m.location, 'Poorly-formatted command. '
'Use "!set setting value [#channel]".')
return
chan = m.line[3]
if not chan in m.bot.configuration["chans"]:
m.bo... |
if unsupervisedMethod is None:
self.unsupervisedMethod = self.dataMgr.module["Unsupervised_Decomposition"].unsupervisedMethod
else:
self.unsupervisedMethod = self.dataMgr.module["Unsupervised_Decomposition"].unsupervisedMethod = unsupervisedMethod
if numComponents is not ... | gv)
self.numComponents = 5
self.testProject = UnsupervisedDecompositionTestProject("sims_aligned_s7_32.h5", UnsupervisedDecompositionPLSA, self.numComponents)
def test_WholeModule(self):
t = QtCore.QTimer()
| t.setSingleShot(True)
t.setInterval(0)
self.app.connect(t, QtCore.SIGNAL('timeout()'), self.mainFunction)
t.start()
self.app.exec_()
def mainFunction(self):
# fix random seed
from ilastik.core.randomSeed import RandomSeed
RandomSeed.se... |
from django.utils.translation import ugettext_lazy as _ugl
default_app | _config = 'django_sendgrid_ | parse.apps.DjangoSendgridParseAppConfig'
|
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | t)
if lineno_value:
frame_handle | = context.getFrameHandle()
return "%s->m_frame.f_lineno = %s;" % (frame_handle, lineno_value)
else:
return ""
def getErrorLineNumberUpdateCode(context):
(
_exception_type,
_exception_value,
_exception_tb,
exception_lineno,
) = context.variable_storage.getEx... |
"pychemqt", "Equilibrium"),
QApplication.translate("pychemqt", "Kinetic"),
QApplication.translate("pychemqt", "Catalitic")]
TEXT_PHASE = [QApplication.translate("pychemqt", "Global"),
| QApplication.translate("pychemqt", "Liquid"),
QApplication.translate("pychemqt", "Gas")]
TEXT_BASE = [QApplication.translate("pychemqt", "Mole"),
QApplication.translate("pychemqt", "Mass"),
QApplication.translate("pychemqt", "Partial pressure")]
def... | h index of reaction components
coef: array with stequiometric coefficient for each component
fase: Phase where reaction work
0 - Global
1 - Liquid
2 - Gas
key: Index of key component
base
0 - ... |
g
*meta.customfilename* to False for each object.
Extensions like *.html* are not stored. Path matching works independent
from extensions.
"""
maxlength = 55 # max path length
containerNamespace = True # unique filenames for container or global
extension = None
def Init(self)... | Extension for nive root objects to handle alternative url names
"""
extension = None
# system functions -----------------------------------------------------------------
def __getitem__(self, id):
"""
Traversal lookup based on object.pool_filename and object.id. Trailing extensions
... | n the current object to map file downloads.
"""
if id == "file":
raise KeyError(id)
if self.extension is None:
id = id.split(".")
if len(id)>2:
id = (".").join(id[:-1])
else:
id = id[0]
try:
id ... |
# Copyright (C) 2016 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.com>
# This file is part of the sos project: https://github.c | om/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the so | urce distribution for further information.
from sos.plugins import Plugin, RedHatPlugin
class Dracut(Plugin, RedHatPlugin):
""" Dracut initramfs generator """
plugin_name = "dracut"
packages = ("dracut",)
def setup(self):
self.add_copy_spec([
"/etc/dracut.conf",
"/et... |
# #######
# Copyright (c) 2018-2020 Cloudify Platform 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
#
# Unless... | en=None,
client_id=self.auth['client_id'],
client_secret | =self.auth['client_secret'],
refresh_token=self.auth['refresh_token'],
token_expiry=None,
token_uri=GOOGLE_TOKEN_URI,
user_agent='Python client library'
)
return credentials
def get(self):
raise NotImplementedError()
def create(self):
... |
#### 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 = Tangible()
result.template = "object/tangible/ship/compon | ents/armor/shared_arm_reward_alderaan_elite.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","armor_reward_alderaan_elite")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATION | S ####
return result |
#!/usr/bin/env python
#
# This code is a part of `ardrone_autopilot` project
# which is distributed under the MIT license.
# See `LICENSE` file for details.
#
"""
This node is based on `base.py`. See there a documentation.
Inputs
------
* in/image -- main picture stream.
Outputs
-------
* out/image -- result imag... | t rospy
import cv2
import tf
from tf.transformations import quaternion_matrix
import numpy as np
import image_geometry
import math
from base import BaseStreamHandler
class Show(BaseStreamHandler):
def __init_ | _(self, *args, **kwargs):
self.tf = tf.TransformListener()
self.camera_model = image_geometry.PinholeCameraModel()
super(Show, self).__init__(*args, **kwargs)
def on_image(self, img):
if self.info is None:
return
self.camera_model.fromCameraInfo(self.info)
... |
1da4,
0x1da5, 0x1da6, 0x1da7, 0x1da8, 0x1da9, 0x1daa,
0x1dab, 0x1dac, 0x1dad, 0x1dae, 0x1daf, 0x1db0,
0x1db1, 0x1db2, 0x1db3, 0x1db4, 0x1db5, 0x1db6,
0x1db7, 0x1db8, 0x1db9, 0x1dba, 0x1dbb, 0x1dbc,
0x1dbd, 0x1dbe, 0x1dbf, 0x2071, 0x207f, 0x2090,
0x2091, 0x2092, 0x2093, 0x2094, 0x2095, 0x2096,
... | RROW-9504
arr = pa.chunked_array | ([
[
"a",
"b",
"c",
"d",
"e"
],
[
"f",
"g",
"h",
"i",
"j"
]
])
indices = np.array([0, 5, 1, 6, 9, 2])
result = arr.take(indices)
expected = pa.chunked_... |
import base64
import json
import responses
from mapbox.services.datasets import Datasets
username = 'testuser'
access_token = 'pk.{0}.test'.format(
base64.b64encode(b'{"u":"testuser"}').decode('utf-8'))
def test_class_attrs():
"""Get expected class attr values"""
serv = Datasets()
assert serv.api_... | ken=access_token).read_dataset('test')
assert response.status_code == 200
assert response.json()['name'] == 'things'
assert response.json()['description'] == 'a collection of things'
@responses.activate
def test_dataset_update():
"""Updating dataset name and description works."""
def request_callb... | :
payload = json.loads(request.body.decode())
resp_body = {
'owner': username,
'id': 'foo',
'name': payload['name'],
'description': payload['description'],
'created': '2015-09-19',
'modified': '2015-09-19'}
headers = {}
... |
# encoding=utf-8
from tsundiary import app
app.jinja_env.globals.update(theme_nicename = {
'classic': 'Classic Orange',
'tsun-chan': 'Classic Orange w/ Tsundiary-chan',
'minimal': 'Minimal Black/Grey',
'misato-tachibana': 'Misato Tachibana',
'rei-ayanami': 'Rei Ayanami',
'rei-ayanami-2': 'Rei A... | uu.net/image/34277/">Saya source</a>. Artist: 中央東口 (Chuuou Higashiguchi).',
'yuno': '<a href="http://xyanderegirl.deviantart.com/art/Yuno-Gasai-Render-293856645">Yuno source</a>.',
'kyoko-sakura': '<a href="http://3071527.deviantart.com/art/kyoko-sakura-376238110">Kyoko source</a>.'
})
app.jinja | _env.globals.update(theme_colors = [
('Red', '0,100,100'),
('Orange', '35,100,100'),
('Yellow', '50,100,100'),
('Green', '120,100,80'),
('Cyan', '180,100,80'),
('Blue', '215,100,100'),
('Purple', '270,100,100'),
('Black', '0,0,0'),
('Grey', '0,0,70'),
('White', '0,0,100'),
])
|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... |
# wrong type comparision
self.assertNotEqual(p0, | 1)
def test_RECT_hash(self):
"""Test RECT is hashable"""
r0 = RECT(0)
r1 = RECT(1)
d = { "r0": r0, "r1": r1 }
self.assertEqual(r0, d["r0"])
self.assertEqual(r1, d["r1"])
self.assertNotEqual(r0, r1)
def test_RECT_repr(self):
"""Test RE... |
ng
import os
from ftplib import FTP as FTPClient
from paramiko import SFTPClient, Transport as SFTPTransport
ALLOWED_BACKEND_TYPES = ['ftp', 'sftp']
DEFAULT_BACKEND_TYPE = 'ftp'
from wok_hooks.misc import Configuration as _Configuration
class Configuration(_Configuration):
def __init__(self, path, **kwargs):
... | xcept:
missing_dirlist.append(current_dirlist.pop())
missing_dirlist.reverse()
for dirname in missing_dirlist:
dir_contents = self.session.listdir()
if not dirname in dir_contents:
self.session.mkdir(dirname)
... | self.state == self.STATE_DISCONNECTED:
raise self.ConnectionException('SFTP is %s' % self.state)
else:
raise NotImplementedError()
def put_file(self, path, file_handle):
if self.state == self.STATE_CONNECTED:
dirpath = '/'.join(path.split('/')[:-1])
s... |
from datetime import datetime
from email.mime import text as mime_text
from unittest.mock import MagicMock
from unittest.mock import Mock
from unittest.mock import patch
import cauldron as cd
from cauldron.session import reloading
from cauldron.test import support
from cauldron.test.support import scaffolds
from cauld... | @patch('cauldron.session.reloading.os.path')
@patch('cauldron.session.reload | ing.importlib.reload')
def test_do_reload_error(self, reload: MagicMock, os_path: MagicMock):
"""Should fail to import the specified module and so return False."""
target = MagicMock()
target.__file__ = None
target.__path__ = ['fake']
os_path.getmtime.return_value = 10
... |
#!/usr/bin/python
# -*- coding: utf8 -*-
"""
Copyright (C) 2012 Xycl
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pr... | ", #"roadmap","satellite","hybrid","terrain" (opt)
"language":"",
#Feature Parameters:
"markers" :"color:red|label:P|%s",#(opt)
#markers=color:red|label:P|lyon|12%20rue%20madiraa|marseille|Lille
... | th" : "", #(opt)
"visible" : "", #(opt)
#Reporting Parameters:
"sensor" : "false" #is there a gps on system ? (req)
}
param_dic["markers"]=param_dic["markers"]%self.place
request_headers = { 'User-Agent': 'Moz... |
from random import randint
import gobject
import clutter
import mxpy as mx
sort_set = False
filter_set = False
def sort_func(model, a, b, data):
return int(a.to_hls()[0] - b.to_hls()[0])
def filter_func(model, iter, data):
color = iter.get(0)[0]
h = color.to_hls()[0]
return (h > 90 and h < 180)
def ... | = not sort_set
elif event.keyval == keysyms.f:
if not filter_set:
model.set_filter(filter_func)
else:
model.set_filter(None, None)
filter_set = not filter_set
if __name__ == '__main__':
stage = clutter.Stage()
stage.connect('destroy', clutter.main_quit)
... | ge.set_color((255, 255, 255, 255))
stage.set_size(320, 240)
color = clutter.Color(0x0, 0xf, 0xf, 0xf)
scroll = mx.ScrollView()
scroll.set_size(*stage.get_size())
stage.add(scroll)
view = mx.ItemView()
scroll.add(view)
model = clutter.ListModel(clutter.Color, "color", float, "size")
... |
# Copyright 2010-2011, Sikuli.org
# Released under the MIT License.
from org.sikuli.script import VDictProxy
import java.io.File
##
# VDict implements a visual dictionary that has Python's conventional dict
# interfaces.
#
# A visual dictionary is a data type for storing key-value pairs using
# images as keys. Using... | ##
# Returns the number of keys in this visual dictionary.
#
def __len__(self):
return self.size()
##
# Maps the specified key to the specified item in this visual dictionary.
#
def __setitem__(self, key, item):
self.insert(key, item)
self._keys[key] = item
##
# Tests if ... | rn len(self.get(key)) > 0
##
# Returns all values to which the specified key is fuzzily matched in
# this visual dictionary with the default similarity.
# <br/>
# This is a wrapper for the {@link #VDict.get get} method.
def __getitem__(self, key):
return self.get(key)
##
# Deletes the k... |
ajectory. scalar float or ndarray of shape (ndim,)
:param length:
The length of this trajectory, integer.
:param lnP0: optional
The lnprob value of the initial position (can be used to save a call to lnprob)
:param grad0: optional
The gradients of the lnpr... | elif self.ndim_mass == 1:
v = self.inverse_mass_matrix * p
#v = p
else:
#v = np.dot | (self.cho_factor, p)
v = np.dot(self.inverse_mass_matrix, p)
return v
def kinetic_energy(self, p):
"""Get the kinetic energy given momenta
"""
if self.ndim_mass == 0:
K = np.dot(p, p)
elif self.ndim_mass == 1:
K = np.dot(p, self.inverse_ma... |
#!/usr/bin/python2
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
A script to check that the (Linux) executables produced by gitian only contain
allowed gcc, glibc and libstdc++ ve... | e):
if library_name not in ALLOWED_LIBRARIES:
print('%s: NEEDED library | %s is not allowed' % (filename, library_name.decode('utf-8')))
retval = 1
exit(retval)
|
from __future__ import unicode_literals
__all__ = (
'Key',
'Keys',
)
class Key(object):
def __init__(self, name):
#: Descriptive way of writing keys in configuration files. e.g. <C-A>
#: for ``Control-A``.
self.name = name
def __repr__(self):
return '%s(%r)' % (self.... | <C-E>')
ControlF = Key('<C-F>')
ControlG = Key('<C-G>')
ControlH = Key('<C-H>')
ControlI = Key('<C-I>') # Tab
ControlJ = Key('<C-J>') # Enter
ControlK = Key('<C-K>')
ControlL = Key('<C-L>')
ControlM = Key('<C-M>') # Enter
ControlN = Key('<C-N>')
ControlO = Key('<C-O>')
Con... | trolT = Key('<C-T>')
ControlU = Key('<C-U>')
ControlV = Key('<C-V>')
ControlW = Key('<C-W>')
ControlX = Key('<C-X>')
ControlY = Key('<C-Y>')
ControlZ = Key('<C-Z>')
ControlSpace = Key('<C-Space>')
ControlBackslash = Key('<C-Backslash>')
ControlSquareClose = Key('<C-SquareClo... |
from django.core.urlresolvers import resolve, Resolver404
from django.test import TestCase
from conman.routes import views
class RouteRouterViewTest(TestCase):
"""Test the route_router view."""
def assert_url_uses_router(self, url):
"""Check a url resolves to the route_router view."""
resolve... | esolved using views.route_router."""
self.assert_url_uses_router('/slug/')
def test_nested_child_url(self):
"""A nested child url is resolved using views.route_router."""
self.assert_url_uses_router('/foo/bar/')
def | test_numerical_url(self):
"""A numeric url is resolved using views.route_router."""
self.assert_url_uses_router('/meanings/42/')
def test_without_trailing_slash(self):
"""A url without a trailing slash is not resolved by views.route_router."""
with self.assertRaises(Resolver404):
... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', 'apps.neo_graph_test.views.create_graph', name='crea | te_graph'),
url(r'^', include('apps.citizens. | urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import re
import os
from urllib.request import urlretrieve
from urllib.request import urlopen
from urllib.request import build_opener, HTTPCookieProcessor
from urllib.parse import urlencode, quote
from http.cookiejar import CookieJar
from configparser import SafeCo... | )
illust = json_result.illust
if "original" in illust.image_urls:
| imageLocs.append(illust.image_urls.original)
elif "meta_pages" in illust and len(illust.meta_pages)!=0:
for i in illust.meta_pages:
imageLocs.append(i.image_urls.original)
elif "meta_single_page" in illust:
imageLocs.append(illust.meta_single_page.original_i... |
import Gears as gears
from .. import *
from ..Pif.Base import *
class Min(Base) :
def applyWit | hArgs(
self,
spass,
functionName,
*,
pif1 : 'First operand. (Pif.*)'
= Pif.Solid( color = 'white' ),
pif2 : 'Second operand. (Pif.*)'
= Pif.Solid( color = 'white' )
) :
... | s = spass.getStimulus()
pif1.apply(spass, functionName + '_op1')
pif2.apply(spass, functionName + '_op2')
spass.setShaderFunction( name = functionName, src = self.glslEsc( '''
vec3 @<pattern>@ (vec2 x, float time){
return min( @<pattern>@_op1(x), @<pattern>@_... |
from | biohub.core.plugins import PluginC | onfig
class BadPluginConfig(PluginConfig):
name = 'tests.core.plugins.bad_plugin'
title = 'My Plugin'
author = 'hsfzxjy'
description = 'This is my plugin.'
def ready(self):
raise ZeroDivisionError
|
from util.tipo import tipo
class S_PARTY_MEMBER_INTERVAL_POS_UPDATE(object):
def | __init__(self, tracker, time, direction, opcode, data):
print(str(type(self)).split('.')[3 | ]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])
|
ry_user.get(), entry_pass.get()))
for namerow in cur.fetchall(): # print all the first cell
fn = namerow[0] #store firstname
ln = namerow[1] #store lastname
rlb1 = Label(middleFrame, text='\nWelcome %s %s\n' % (fn, ln), font="Arial 14")
... | 10, columnspan=2)
####################################DATABASE Check if Username is available, check if passwords Matc | h -> if so SIGN UP!!!!!!!!!!!!!!!
def get_Signup_input():
var = dbConnect()
dbconn = mysql.connect(host=var.host, user=var.user, password=var.password, db=var.db)
cur = dbconn.cursor() # Cursor object - required to execute all queries
cur.execute("SELECT usernam... |
"""
Copy RWIS data from iem database to its final resting home in 'rwis'
The RWIS data is partitioned by UTC timestamp
Run at 0Z and 12Z, provided with a timestamp to process
"""
import | datetime
import sys
import psycopg2.extras
from pyiem.util import get_dbconn, utc
def main(argv):
"""Go main"""
iemdb = get_dbconn("iem")
rwisdb = get_dbconn("rwis")
ts = utc(int(argv[1]), int(argv[2]), int(argv[3]))
ts2 = ts + datetime.timedelta(hours=24)
rcursor = rwisdb.cursor()
# Rem... | s for this UTC date
for suffix in ["", "_soil", "_traffic"]:
rcursor.execute(
f"DELETE from t{ts.year}{suffix} WHERE valid >= %s and valid < %s",
(ts, ts2),
)
rcursor.close()
# Always delete stuff 3 or more days old from iemaccess
icursor = iemdb.cursor()
icu... |
IR, None)
if not src: src = getattr(Utils.g_module, SRCDIR, None)
if not src: src = getattr(Utils.g_module, 'top', None)
if not src:
src = '.'
incomplete_src = 1
src = os.path.abspath(src)
bld = getattr(Options.options, BLDDIR, None)
if not bld: bld = getattr(Utils.g_module, BLDDIR, None)
if not bld: bld = ... | all the files
try:
proj = Environment.Environment(Optio | ns.lockfile)
except IOError:
raise Utils.WafError("Project not configured (run 'waf configure' first)")
bld.load_dirs(proj[SRCDIR], proj[BLDDIR])
bld.load_envs()
info("Waf: Entering directory `%s'" % bld.bldnode.abspath())
bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]])
# execute something imme... |
import time
from pymongo import MongoClient
from datetime import datetime, timedelta
import json
from bson import Binary, Code
from bson.json_util import dumps
client = MongoClient('localhost', 27017)
db = client['election-2016']
def dumpData(yesterdayStr):
collectionName = 't' + yesterdayStr
cursor = db[... |
for document in cursor:
doc = dumps(document)
file.write(doc)
if (i != count - 1):
file.write(',\n')
else:
| file.write('\n]')
i = i + 1
print('data for ' + yesterdayStr + ' successfully dumped at ' + str(now))
# Run following code when the program starts
if __name__ == '__main__':
currentDate = str(datetime.now().month) + '_' + str(datetime.now().day)
#get now and yesterday strings
no... |
"""
Settings for testing the application.
"""
import os
DEBUG = True
DJANGO_RDFLIB_DEVELOP = True
DB_PATH = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'rdflib_django.db'))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_PATH,
'USER': '',
... | ib.admindocs',
'rdflib_django',
)
ROOT_URLCONF = 'rdflib_django.urls'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'simple': {
'format': '%(levelname)s %(mes | sage)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
'loggers': {
'': {
'handlers': ['console'],
'propagate': True,
'level':... |
from vint.ast.traversing import traverse, register_traverser_extension
from vint.ast.parsing import Parser
from vint.ast.node_type import NodeType
REDIR_CONTENT = 'VINT:redir_content'
class RedirAssignmentParser(object):
""" A class to make redir assignment parseable. """
def process(self, | ast):
def enter_handler(node):
node_type = NodeType(node['type'])
if node_type is not NodeType.EXCMD:
return
is_redir_command = node['ea']['cmd'].get('name') == 'redi | r'
if not is_redir_command:
return
redir_cmd_str = node['str']
is_redir_assignment = '=>' in redir_cmd_str
if not is_redir_assignment:
return
parser = Parser()
redir_content_node = parser.parse_redir(node)
... |
# Used for when precision or recall == 0 to supress warnings
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
import numpy as np
import sklearn_crfsuite
from sklearn.metrics import make_scorer, confusion_matrix
from sklearn_crfsuite import metrics
from sklearn_crfsuite.utils import flatten
from... | ", "CoreComposition", "Precursor", "ReducingAgent", "Solvent", "Stabilizer"]))
print(conf_mat)
print("Top positive:")
print_state_features(Counter(crf.state_features_).most_common(30))
print("\nTop negative:")
print_state_features(Counter(crf.state | _features_).most_common()[-30:])
def extract_chem_entities(sents):
document_text = [[str(w[0]) for w in s] for s in sents]
document_text = [" ".join(s) for s in document_text]
document_text = " ".join(document_text)
paragraph = Paragraph(document_text)
chem_entities = paragraph.cems
chem_entit... |
'''Biblioteca que contém as rotinas de coversão dos diferentes tipos
de máquinas.
Autor: Lucas Possatti
'''
import re
import collections
def mealy_to_moore(me):
'''Converte o parâmetro 'me' (que deve ser uma máquina Mealy) para
uma máquina de Moore, que é retornada.
'''
# Verifica se a máquina recebida, realemen... | o for do estado inicial, precisamos adicionalemente
# acrescenta-la como transição do estado 'qe'
if mealy_trans_stage[0] == moo[4][1]:
mealy_trans.append(['qe'] + mealy_trans_stage[1:])
# E adiciona ao conjunto de transições da máquina mealy.
mealy_trans.append(mealy_trans_stage)
# Coloca as transações d... | rint('moo[1]', moo[1])
#!# print('moo[2]', moo[2])
#!# print('moo[3]', moo[3])
#!# print('moo[4]', moo[4])
#!# print('moo[5]', moo[5])
#!# print('moo[6]', moo[6])
#!# print('moo[7]', moo[7][0:-1])
#!# print(':END DEBUG')
return me
|
# -*- encoding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
from enocean.protocol.eep import EEP
eep = EEP()
# profiles = eep.
def test_first_range():
offset = -40
values = range(0x01, 0x0C)
for i in range(len(values)):
minimum = float(i * 10 + off... | i in range(len(values)):
minimum = float(i * 10 + offset)
maximum = minimum + 80
profile = eep.find_profile([], 0xA5, 0x02, values[i])
assert minimum == float(profile.find('value', {'shortcut': 'TMP'}).find('scale').find('min').text)
assert maximum == float(profile.find('value',... | st_rest():
profile = eep.find_profile([], 0xA5, 0x02, 0x20)
assert -10 == float(profile.find('value', {'shortcut': 'TMP'}).find('scale').find('min').text)
assert +41.2 == float(profile.find('value', {'shortcut': 'TMP'}).find('scale').find('max').text)
profile = eep.find_profile([], 0xA5, 0x02, 0x30)
... |
jaccard = 2.
else:
jaccard = float(j["intersection"]) / float(j["union"])
return [[1. - jaccard]]
def recall_dist_fn(graph1, graph2, options):
""" assymmetric version of above to compute recall of graph1 on graph2
return recall to be consistent with other functions where similar is ... |
def save_vcfeval_stats(out_path, fn_table, fp_table, tp_table):
""" write some summary counts from the vceval vcf output """
def write_table(t, name):
| with open(os.path.join(out_path, "comp_counts_{}.tsv".format(name)), "w") as f:
for line in t:
f.write("{}\t{}\t{}\t{}\n".format(line[0], line[1], line[2], line[3]))
write_table(fn_table, "fn")
write_table(fp_table, "fp")
write_table(tp_table, "tp")
def load_vcf... |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""Python 2<->3 compatibility module"""
import sys
def print_(template, *args, **kwargs):
template = str(template)
if args:
template ... | 'rais | e t, e, tb', dict(t=t, e=e, tb=tb))
else:
basestring = str
from configparser import ConfigParser
from urllib.parse import unquote
iteritems = lambda d: d.items()
dictkeys = lambda d: list(d.keys())
def reraise(t, e, tb):
raise e.with_traceback(tb)
|
place this file in the same folder as your ghdata folder.
#to run this, type "python pythonBlameHistoryTree.py" into the command prompt
#You will see some output about running on 127.0.0.1:5000 in the command prompt
#Open a web browser and navigate to 127.0.0.1:5000.
#This page will load for quite a while. At least ... | tackoverflow.com/questions/2853723/whats-the-python-way-for-recursively-setting-file-permissions
if os.path.exists(repo_path):
for root, directories, files in os.walk(repo_path):
for directory in directories:
os.chmod(os.path.join(root, directory), stat.S_IWRITE)
... | #delete the old ghdata
shutil.rmtree(repo_path)
#connect to the database username:password@hostname:port/databasename
db = sqlalchemy.create_engine('mysql+pymysql://root:password@localhost:3306/msr14')
schema = sqlalchemy.MetaData()
schema.reflect(bind=db)
#Get the ghdata r... |
# Copyright (c) 2014 Ahmed H. Ismail
# 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 t | he License at
# http://www.apache.org/licenses/LICEN | SE-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 Licens... |
#!/usr/bin/env python
# -*- coding: ascii -*-
from subprocess import Popen, PIPE
import threading
import select
import logging
import fcntl
import time
import sys
import os
TTY_OPTS="-icrnl -onlcr -imaxbel -opost -isig -icanon -echo line 0 kill ^H min 100 time 2 brkint 115200"
READERS = []
WRITERS = []
SELECT_TO = 0.1... | ass TTYReader(TTYWorker):
"""Reads tty output to file"""
def run(self):
tty_out_path = os.sep.join([self.root, "%s.log" % se | lf.tty])
logging.info("tty_out_path(%s)" % tty_out_path)
while self.keep_running:
err = not os.path.exists(self.dev)
if err:
logging.error("dev(%s) does not exist" % self.dev)
time.sleep(1)
continue
err = not os.path.... |
from __future__ import division, absolute_import, print_function,\
unicode_literals
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup, Extension
from distutils.core import Extension
from distutils.errors import DistutilsError
from distutils.command.bui... | print()
print("Exception was : %r" % (e,))
print()
print(
"If you need the extensions (they may be faster than "
"alternative on some"
)
print(" platforms) check you have a compiler configured with all"
... | 'cygwin'):
_lib = ctypes.windll.nanoconfig
else:
_lib = ctypes.cdll.LoadLibrary('libnanoconfig.so')
except OSError:
# Building without nanoconfig
cpy_extension = Extension(str('_nanomsg_cpy'),
sources=[str('_nanomsg_cpy/wrapper.c')],
libraries... |
# -*- coding: utf-8 -*-
"""The application's model objects"""
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
# from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
# Global session manager: DBSession() returns the Thread-... | ome typing.
# You can have a query property on all your model classes by doing this:
# DeclarativeBase.query = DBSession.query_property()
# Or you can use a session-aw | are mapper as it was used in TurboGears 1:
# DeclarativeBase = declarative_base(mapper=DBSession.mapper)
# Global metadata.
# The default metadata is the one from the declarative base.
metadata = DeclarativeBase.metadata
# If you have multiple databases with overlapping table names, you'll need a
# metadata for each ... |
# -*- coding: utf8 -*-
# This file is part of Mnemosyne.
#
# Copyright (C) 2013 Daniel Lombraña González
#
# Mnemosyne is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by |
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mnemosyne is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY | or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Mnemosyne. If not, see <http://www.gnu.org/licenses/>.
"""
Package for creating the Flask application.
This exports:
- create_... |
from django.contrib.contenttypes.models import ContentType
from lfs.core.utils import import_symbol
from lfs.criteria.models import Criterion
import logging
logger = logging.getLogger(__name__)
# DEPRECATED 0.8
def is_valid(request, object, product=None):
"""
Returns True if the given object is valid. This ... | riteria.utils.get_criteria: this function is deprecated. Please use the Criteria class instead.")
content_type = ContentType.objects.get_for_model(object)
criteria = []
for criterion in Criterion.objects.filter(content_id=object.id, content_type=content_type):
criteria.append(criterion.get_content_... |
"""
Returns the first valid object of given objects.
Passed object is an object which can have criteria. At the moment these are
discounts, shipping/payment methods and shipping/payment prices.
"""
for object in objects:
if object.is_valid(request, product):
return object
... |
"""
Load the CCGOIS datasets into a CKAN instance
"""
import dc
import json
import slugify
import ffs
def make_name_from_title(title):
# For some reason, we're finding duplicate names
name = slugify.slugify(title).lower()[:99]
if not name.startswith('ccgois-'):
name = u"ccgois-{}".format(name)
... | metadata['resources']]
metadata['title'] = u'CCGOIS - {}'.format(metadata['title'])
metadata['name'] = make_name_from_title(metadata['title'])
print u'Creating {}'.format(metadata['name'])
dc.Dataset.create_or_update(
name=metadata['name'],
title=metadata['title'... | iption'],
origin='https://indicators.ic.nhs.uk/webview/',
tags=dc.tags(*metadata['keyword(s)']),
resources=resources,
#frequency=[metadata['frequency'], ],
owner_org='hscic',
extras=[
dict(key='frequency', value=metadata.get('freque... |
# 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 ... | },
'status': {'key': 'properties.status', 'type': 'str'},
'created_at': {'key': 'properties.createdAt', 'type': 'iso-8601'},
'service_bus_endpoint': {'key': 'properties.serviceBusEndpoint', 'type': 'str'},
'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'},
's... | .scaleUnit', 'type': 'str'},
'enabled': {'key': 'properties.enabled', 'type': 'bool'},
'critical': {'key': 'properties.critical', 'type': 'bool'},
'namespace_type': {'key': 'properties.namespaceType', 'type': 'NamespaceType'},
}
def __init__(self, location, tags=None, sku=None, namespac... |
# Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
# Copyright (c) 2015, Google, Inc.
#
# 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
... | S 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 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
... | ERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy
def uniform(min_val, max_val, point_count):
grid =... |
io_handler.write_line("No service provides '{0}'", specification)
return False
else:
# Print'em all
io_handler.write(self._utils.make_table(headers, lines))
io_handler.write_line("{0} services registered", len(lines))
def __extract_help(self, method... | xtract documentation
args, doc = self._ | _extract_help(self._commands[namespace][cmd_name])
# Print the command name, and its arguments
if args:
io_handler.write_line("- {0} {1}", cmd_name, args)
else:
io_handler.write_line("- {0}", cmd_name)
# Print the documentation line
io_handler.write_line... |
from .depth import *
from .camera import *
from .contact impor | t *
from .imagefeature impor | t *
from .arduino import *
|
# -*- coding: utf-8 -*-
"""
# This is authentication backend for Django middleware.
# In settings.py you need to set:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
...
)
AUTHENTICATION_BACKENDS = (
'kob... | ETTINGS_MODULE <project>.s | ettings
PythonDebug On
</Location>
<Location "/auth/krb5login">
AuthType Kerberos
AuthName "<project> Kerberos Authentication"
KrbMethodNegotiate on
KrbMethodK5Passwd off
KrbServiceName HTTP
KrbAuthRealms EXAMPLE.COM
Krb5Keytab /etc/httpd/conf/http.<hostname>.keytab
KrbSaveCredentia... |
from distutils.core im | port setup
from setuptools import setup, find_packages
setup(
name = 'gooeydist',
packages = find_packages(), # this must be the same as the name above
version = '0.2',
description = 'Gooey Language',
author = 'Gooey Comps',
author_email = 'harrise@carleton.edu',
url = 'https://github.com/GooeyComps/gooey-dist',... | itrary keywords
classifiers = [],
) |
# - | *- coding: utf-8 -*-
from loading import load_plugins, register_plugin
from plugz import PluginTypeBase
from plugintypes import StandardPluginType
__author__ = 'Matti Gruener'
__email__ = 'matti@mistermatti.com'
__version__ = '0.1.5'
__ALL__ = [load_plugins, | register_plugin, StandardPluginType, PluginTypeBase]
|
'''
go list comprehensions
'''
def main():
a = []i | nt(x for x in range(3))
TestError( len(a)==3 )
TestError( a[0]==0 )
TestError( a[1]==1 )
TestError( a[2]== | 2 )
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2017-09-14 23:53
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration): |
dependencies = [
('organization', '0004_teacher_image'),
('courses', '0006_auto_20170914_2345'),
]
operations = [
migrations.AddField(
model_name='course',
name='teacher',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models... | n.Teacher', verbose_name='\u8bb2\u5e08'),
),
]
|
l, rtag
end
"""
def testSendECS(self):
# First send an ECS query with routingTag
self.setRoutingTag('foo')
expected1 = dns.rrset.from_text(nameECS, ttlECS, dns.rdataclass.IN, 'TXT', '192.0.2.0/24')
ecso = clientsubnetoption.ClientSubnetOption('192.0.2.1', 32)
query = dns.mes... | .question[0].name | == dns.name.from_text(nameECS) and request.question[0].rdtype == dns.rdatatype.NS:
answer = dns.rrset.from_text(nameECS, ttlECS, dns.rdataclass.IN, 'NS', 'ns1.ecs-echo.example.')
response.answer.append(answer)
additional = dns.rrset.from_text('ns1.ecs-echo.example.', 15, dns.rdatacla... |
###################### | #########################################################
# _*_ coding: utf-8
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from __future__ import unicode_literals
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
|
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'utf8_03.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' ... |
.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | ),
math_ops.cast(self._l1_regularization_strength_tensor,
var.dtyp | e.base_dtype),
math_ops.cast(self._adjusted_l2_regularization_strength_tensor, |
# File: setup.py
# Version: 3
# Description: Setup for SHA2017 badge
# License: MIT
# Authors: Renze Nicolai <renze@rnplus.nl>
# Thomas Roos <?>
import ugfx, badge, appglue, dialogs, easydraw, time
def asked_nickname(value):
if value:
badge.nvs_set_str("owner", "name", value)
# Do the ... | badge.nvs_set_u8('badge', 'setup.state', newState)
# Show the user that we are done
easydraw.msg("Hi "+value+"!", 'Your nick has been stored to flash!')
time.sleep(0.5)
else:
badge.nvs_set_u8('badge', 'setup.state', 2) # Skip the sponsors
badge.nvs_set_u8('sponsors', ... | text("Nickname", nickname, cb=asked_nickname)
|
import os
from home.models import ReplicaSet, WhatTorrent, WhatFulltext
def run_checks():
errors = []
warnings = []
# Check WhatFulltext integrity
def check_whatfulltext():
w_torrents = dict((w.id, w) for w in WhatTorrent.objects.defer('torrent_file').all())
w_fulltext = dict((w.id, ... | is a master
if replica_set.is_master:
files_in_dir = os.listdir(m_torrent.path)
if not any('.torrent' in f for f in files_in_dir):
errors.append(u'Missing .torrent file for {0} at {1}'
.f | ormat(m_torrent, instance))
if not any('ReleaseInfo2.txt' == f for f in files_in_dir):
errors.append(u'Missing ReleaseInfo2.txt for {0} at {1}'
.format(m_torrent, instance))
for hash, t_torrent in i_t_torrents.items():
... |
import asposecellscloud
from asposecellscloud.CellsApi import CellsApi
from asposecellscloud.CellsApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify App SID
apiServer = "http://api.aspose.com/v1.1"
data_fol... | pi = StorageApi(storage_apiClient)
#Instantiate Aspose Cells API SDK
api_client = asposecellscloud.ApiClient.ApiClient(apiKey, appSid, True)
cellsApi = CellsApi(api_client);
#set input file name
filename = "Sample_Test_Book.xls"
sheetName = "Sheet1"
range = "A1:A12"
#upload file to aspose cloud storage
storageApi.Put... | a_folder + filename)
try:
#invoke Aspose.Cells Cloud SDK API to clear cells formatting in a worksheet
response = cellsApi.PostClearFormats(name=filename, sheetName=sheetName, range=range)
if response.Status == "OK":
#download updated Workbook from storage server
response = storageApi.GetDo... |
# Support for building census bundles in Ambry
__version__ = 0.8
__author__ = 'eric@civicknowledge.com'
from .generator import *
from .schema import *
from .sources import *
from .transforms import *
import ambry.bundle
class AcsBundle(ambry.bundle.Bundle, MakeTablesMixin, MakeSourcesMixin,
JamValue... | :
@CaptureException
def ingest(self, sources=None, tables=None, stage=None, force=False, update_tables=True):
"""Override the ingestion process to download all of the input files at once. This resolves
the contention for the files that would occurr if many generators are trying to download
... | _download(ACS09TableRowGenerator)
return super(ACS2010Bundle, self).ingest(sources, tables, stage, force, update_tables)
|
#!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/r... | rs': [
'10.0.2.1/24',
]
}
bgpIntfs = {
'bgpq2-eth0': bgpEth0
}
bgpq2 = self.addHost("bgpq2", cls=Router,
quaggaConfFile='{}/quagga2.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
... | intfDict=bgpIntfs)
self.addLink(bgpq2, s1)
topos = {'sdnip': SdnIpTopo}
if __name__ == '__main__':
setLogLevel('debug')
topo = SdnIpTopo()
net = Mininet(topo=topo, controller=RemoteController)
net.start()
CLI(net)
net.stop()
info("done\n")
|
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
# |
# spec/fixtures/responses/whois.nic.pw/status_available
#
# and regenerate the tests with the following script
#
# $ scripts | /generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois
class TestWhoisNicPwStatusAvailable(object):
def setUp(self):
fixture_path = "spec/fixtures/responses/whois.nic.pw/status_available.txt"
host = "whois.nic.pw"
part ... |
#!/usr/bin/env python
'''
simple templating system for mavlink generator
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
from mavparse import MAVParseError
class MAVTemplate(object):
'''simple templating system'''
def __init__(self,
sta | rt_var_token="${",
end_var_token="}",
start_rep_token="${{",
end_rep_token="}}",
trim_leading_lf=True,
checkmissing=True):
self.start_var_token = start_var_token
self.end_var_token = en | d_var_token
self.start_rep_token = start_rep_token
self.end_rep_token = end_rep_token
self.trim_leading_lf = trim_leading_lf
self.checkmissing = checkmissing
def find_end(self, text, start_token, end_token):
'''find the of a token.
Returns the offset in the s... |
#!/usr/bin/env python
# Copyright 2020 the V8 project 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 heapq
import os
import platform
import random
import signal
import subprocess
# Base dir of the build products for Release an... | ):
self.size = size
self.key = key or (lambda x: x)
self.data = []
self.discriminator = 0
def add(self, elem):
elem_k = self.key(elem)
heapq.heappush(self.data, ( | elem_k, self.extra_key(), elem))
if len(self.data) > self.size:
heapq.heappop(self.data)
def extra_key(self):
# Avoid key clash in tuples sent to the heap.
# We want to avoid comparisons on the last element of the tuple
# since those elements might not be comparable.
self.discriminator += 1... |
# -*- coding: utf-8 -*-
from plugins import Plugin
from PyQt4 import QtCore, QtGui
import tempfile, codecs
import os, subprocess
class rst2pdf(Plugin):
name='rst2pdf'
shortcut='Ctrl+F8'
description='Run through rst2pdf and preview'
tmpf=None
def run(self):
| print "Running rst2pdf"
text=unicode(self.client.editor.toPlainText())
# Save to a named file
if self.tmpf is None:
self.tmpf=tempfile.NamedTemporaryFile(delete=False)
self.tmpf.cl | ose()
f=codecs.open(self.tmpf.name,'w','utf-8')
f.write(text)
f.close()
# FIXME: unsafe
# FIXME: show output of the process somewhere
try:
self.client.notify('Running rst2pdf')
subprocess.check_call('rst2pdf %s'%self.tmpf.name, shell=True)... |
s.conversion import RB_to_OPLS
from mbuild.utils.io import import_
from mbuild.utils.sorting import natural_sort
from .hoomd_snapshot import to_hoomdsnapshot
gsd = import_("gsd")
gsd.hoomd = import_("gsd.hoomd")
hoomd = import_("hoomd")
hoomd.md = import_("hoomd.md")
hoomd.md.pair = import_("hoomd.md.pair")
hoomd.md.... | = import_("hoomd.md.bond")
hoomd.md.angle = import_("hoomd.md.angle")
hoomd.md.dihedral = import_("hoomd.md.dihedral")
hoomd.group = import_("hoomd.group")
def create_hoomd_simulation(
structure,
ref_distance=1.0,
ref_mass=1.0,
ref_energy=1.0,
r_cut=1.2,
auto_scale=False,
snapshot_kwargs={... | ters
----------
structure : parmed.Structure
ParmEd Structure object
ref_distance : float, optional, default=1.0
Reference distance for conversion to reduced units
ref_mass : float, optional, default=1.0
Reference mass for conversion to reduced units
ref_energy : float, optio... |
"""
WSGI config for kanban 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_APPLICATION`` s... |
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_ | application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
#!/usr/bin/env python
# The really simple Python version of Qwt-5.0.0/examples/simple
# for debugging, requires: python configure.py --trace ...
if False:
import sip
| sip.settracemask(0x3f)
import | sys
import qt
import Qwt5 as Qwt
from Qwt5.anynumpy import *
class SimplePlot(Qwt.QwtPlot):
def __init__(self, *args):
Qwt.QwtPlot.__init__(self, *args)
# make a QwtPlot widget
self.setTitle('ReallySimpleDemo.py')
self.insertLegend(Qwt.QwtLegend(), Qwt.QwtPlot.RightLegend)
# set axis... |
# coding=utf-8
# Copyright 2015 Pants project contributors (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)
import os
from pants.util.dirutil import safe_mkdir_for
class ReproMixin(object):
""" Additional helper methods for use in Repro tests"""
| def add_file(self, root, path, content):
"""Add a file with specified contents
:param str root: Root directory for path.
:param str path: Path relative to root.
:param str content: Content to write to file.
"""
fullpath = os.path.join(root, path)
safe_mkdir_for(fullpath)
with open(full... |
import genxmlif
from genxmlif.xmlifODict import odict |
xmlIf = genxmlif.chooseXmlIf(genxmlif.XMLIF_ELEMENTTREE)
xmlTree = xmlIf.createXmlTree(None, "testTree", {"rootAttr1":"RootAttr1"})
xmlRootNode = xmlTree.getRootNode()
myDict = odict( (("childTag1","123"), ("childTag2","123")) )
xmlRootNode.appendChild("childTag", myDict)
xmlRootNode.appendChild("childTag", {"childTa... | Child("childTag", {"childTag1":"1", "childTag2":"1"})
print xmlTree.printTree(prettyPrint=1)
print xmlTree
print xmlTree.getRootNode() |
from jsbuild.attrdict import AttrDict
from time import strftime
class Manifest(AttrDict):
def __init__(self,*args,**kwargs):
super(AttrDict, self).__init__(*args,**kwargs)
self._buffer_ = None
self._parent_ = None
if not self.__contains__('_dict_'):
self['_dict_'] = {}
self['_dict_']... | tem__(name)
if isinstance(item,Manifest) and | not item._parent_:
item._parent_ = self
elif isinstance(item,str):
root = self
while root._parent_: root = root._parent_
item = item%root._dict_
return item
|
import sys
import unittest
sys.path.append('../../')
import lib.event
class TestEvents(unittest.TestCase):
def setUp(self):
TestEvents.successful = False
TestEvents.successful2 = False
def test_subscribe(self):
@lib.event.subscribe('test')
def subscribe_test():
Te... | def subscribe_test(successful=False):
TestEvents.successful = successful
lib.event.call('test2', {'successful': True})
self.assertTrue(TestEvents.successful)
def test_subscribe_two_with_params(self):
| @lib.event.subscribe('test3')
def subscribe_test(successful=False):
TestEvents.successful = successful
@lib.event.subscribe('test3')
def subscribe_test2(successful=False):
TestEvents.successful2 = successful
lib.event.call('test3', {'successful': True})
... |
# -*- coding: utf-8 -*-
# import sqlite3 as sqlite
import sys
import uuid
from pysqlcipher3 import dbapi2 as sqlite
def main():
print("***************** Welcome to OSS DataMaster-Rigster System *******************")
print("* *")
pri... | data_master_name, password, unique_id))
conn.commit()
c.close()
print("*********** | *******************************************************************")
print("* *")
print("********************* Data Master Rigster Is Successful! *********************")
if __name__ == '__main__':
main()
|
return cp.all(copied_predt == inplace_predt)
for i in range(10):
run_threaded_predict(X, rows, predict_df)
base_margin = cudf.Series(rng.randn(rows))
self.run_inplace_base_margin(booster, dtrain, X, base_margin)
@given(strategies.integers(1, 10),
tm.data... | lose(inplace, copied, atol=1e-6)
@pytest.mark.skipif(**tm.no_cupy())
def test_dtypes(self):
import cupy as cp
rows = 1000
cols = 10
rng = cp.random.RandomState(1994)
orig = rng.randint(low=0, high=127, size=rows * cols).reshape(
rows, cols
)
y... | rain({"tree_method": "gpu_hist"}, dtrain)
predt_orig = booster.inplace_predict(orig)
# all primitive types in numpy
for dtype in [
cp.signedinteger,
cp.byte,
cp.short,
cp.intc,
cp.int_,
cp.longlong,
cp.unsignedi... |
#
# cellulist documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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.
#
# All configuration value... | = None
# For "man | ual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manua... |
from pytest_factoryboy import register
from me | inberlin.test.factories impo | rt kiezkasse
register(kiezkasse.ProposalFactory)
|
# This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy... | gField(_('Title'), [DataRequired()])
code = StringField(_('Code'))
track_group = QuerySelectField(_('Track group'), default='', allow_blank=True, get_label='title',
description=_('Select a track group to which this track should belong'))
default_sessi | on = QuerySelectField(_('Default session'), default='', allow_blank=True, get_label='title',
description=_('Indico will preselect this session whenever an abstract is '
'accepted for the track'))
description = IndicoMarkdown... |
#
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | er
pc.pa | ssword = provider['password'] or self._play_context.password
pc.private_key_file = provider['ssh_keyfile'] or self._play_context.private_key_file
pc.timeout = int(provider['timeout'] or C.PERSISTENT_COMMAND_TIMEOUT)
display.vvv('using connection plugin %s' % pc.connection, pc.remote_... |
import _plotly_utils.basevalidators
class TypesrcValidator(_plotly_utils.basevalidators. | SrcValidator):
def __init__(
self | ,
plotly_name="typesrc",
parent_name="scatterternary.marker.gradient",
**kwargs
):
super(TypesrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
#!/usr/bin/env python
import os.path
import sys
# Version file managment scheme and graceful degredation for
# setuptools borrowed and adapted from GitPython.
try:
from setuptools import setup, find_packages
# Silence pyflakes
assert setup
assert find_packages
except ImportError:
from ez_setup imp... | email="wal-e@googlegroups.com",
maintainer="Daniel Farina",
maintainer_email="daniel@heroku.com",
description="Continuous Archiving for Postgres",
long_description=read('README.rst'),
classifiers=['Topic :: Database',
'Topic :: | System :: Archiving',
'Topic :: System :: Recovery Tools'],
platforms=['any'],
license="BSD",
keywords=("postgres postgresql database backup archive archiving s3 aws "
"openstack swift wabs azure wal shipping"),
url="https://github.com/wal-e/wal-e",
# Include the VER... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.