prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
are nice values.
@type replacechar: string
@param remove_escaped_chars_p: If True, also remove escaped characters
like '&', '<', '>' and '"'.
@type remove_escaped_chars_p: boolean
@return: Input text with HTML markup removed.
@rtype: string
"""
if not remove_escaped_c... | ls, original_string='', escape_quotes=False):
if isinstance(original_string, EscapedString):
escaped_string = str(original_string)
else:
if original_string and not str(original_string).strip():
escaped_string = ' '
else:
escaped_st... | string
obj.escape_quotes = escape_quotes
return obj
def __repr__(self):
return 'EscapedHTMLString(%s, %s)' % (repr(self.original_string), repr(self.escape_quotes))
def __add__(self, rhs):
return EscapedHTMLString(EscapedString(str(self) + str(rhs)))
class EscapedXMLString(Esca... |
_x-w//2,delta_y-h//2))
## images.append(result)
## if reverse:
## images += images[::-1][1:-1]
## return images
def get_shifted_tiles(img, nframes, dx=0, dy=0, reverse=False, sin=True):
r = img.get_rect()
w,h = r.size
images = []
for i in range(nframes):
if sin:
... | turn tilers
def load_tilers_dynamic(i, grasses, waters, | folder): #pour static, nframes=1
nzoom = len(grasses)
assert nzoom == len(waters) #same number of zoom levels
nframes = len(grasses[0])
for z in range(nzoom):
assert nframes == len(waters[z]) #same number of frames
tilers = [[None for n in range(nframes)] for z in range(nzoom)]
for z in ... |
# coding: utf-8
#
# Copyright © 2012-2014 Ejwa Software. All rights reserved.
#
# This file is part of gitinspector.
#
# gitinspector is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | at your option) any later version.
#
# gitinspector is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the... | <http://www.gnu.org/licenses/>.
from __future__ import print_function
from __future__ import unicode_literals
import re
import textwrap
from gitinspector.localization import N_
from gitinspector.outputable import Outputable
from gitinspector import terminal
__filters__ = {"file": [[], set()], "author": [[], set()],... |
# -*- coding: utf-8 -*-
import os
from mock import Mock, patch
from maidchan.translate import get_trans_language_prediction, get_translation
SCRIPT_PATH = os.path.abspath(os.path.dirname(__file__))
def _get_response(name):
path = os.path.join(SCRIPT_PATH, 'data', name)
with open(path) as f:
return ... | args[0] and 'hello, world!' in args[0]:
return_value = _get_response('get_trans_prediction.txt')
elif '-b' in args[0] and 'en:ja' in args[0] and 'hello, world!' in args[0]:
return_value = _get_response('get_trans_translation.txt')
elif '-b' in args[0] and 'en:id' in args[0] and 'hello, world!' i... | )}
process_mock.configure_mock(**attrs)
return process_mock
class TestTranslate:
@patch('subprocess.Popen', side_effect=mocked_trans)
def test_get_translate_language_prediction(self, mock_trans):
assert get_trans_language_prediction("hello, world!") == "en"
@patch('subprocess.Popen', side... |
child.removeColumns(position, columns)
return True
def setData(self, column, value):
if column < 0 or column >= len(self.itemData):
return False
self.itemData[column] = value
return True
class TreeModel(QtCore.QAbstractItemModel):
def __i... | (index).parent()
|
if parentItem == self.rootItem:
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
if index.column() == 1 or index.column() == 2:
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.Item... |
# -*- coding: utf-8 -*-
import random
import pytest
from holviapi.utils import (
ISO_REFERENCE_VALID,
fin_reference_isvalid,
int2fin_reference,
iso_reference_isvalid,
str2iso_reference
)
def test_fin_reference_isvalid_valid_results():
"""Test handpicked, known-good inputs"""
assert fin_re... | assert not fin_reference_isvalid(1039110)
assert not fin_reference_isvalid(1084110)
def test_int2fin_refere | nce_valid_results():
"""Test handpicked, known-good inputs and corresponding outputs"""
assert int2fin_reference(1) == '13'
assert int2fin_reference(10) == '107'
assert int2fin_reference(10552) == '105523'
assert int2fin_reference(10231) == '102319'
assert int2fin_reference(10832) == '108326'
... |
#!/usr/bin/env python3.4
# -*- c | oding: utf | -8 -*-
|
import pytest
from awsshell.fuzzy import fuzzy_search
@pytest.mark.parametrize("sea | rch,corpus,expected", [
('foo', ['foobar', 'fooba | z'], ['foobar', 'foobaz']),
('f', ['foo', 'foobar', 'bar'], ['foo', 'foobar']),
('fbb', ['foo-bar-baz', 'fo-ba-baz', 'bar'], ['foo-bar-baz', 'fo-ba-baz']),
('fff', ['fi-fi-fi', 'fo'], ['fi-fi-fi']),
# The more chars it matches, the higher the score.
('pre', ['prefix', 'pre', 'not'], ['pre', 'prefix'... |
from akara.dist import se | tup
setup(name="basic",
version="1.0",
akara_extensions=["blah.py"]
)
| |
ss_msg
def check_console_width(val):
""" Show ruler to check console width. """
valid = True
message = "-" * val + "\n"
message += "console_width set to %s, try a lower value if above line ove"\
"rlaps" % val
return dict(valid=valid, message=message)
def check_api_key(key):
""" Valid... | ConfigItem("search_music", True),
ConfigItem("window_pos", "", check_fn=check_win_pos,
require_known_player=True),
ConfigItem("window_size", "",
check_fn=check_win_size, require_known_player=True),
ConfigItem("download_command", ''),
Config... | check_lastfm_password),
ConfigItem("lastfm_api_key", ''),
ConfigItem("lastfm_api_secret", ''),
ConfigItem("audio_format", "auto",
allowed_values="auto webm m4a".split()),
ConfigItem("video_format", "auto",
allowed_values="auto webm mp4 3gp"... |
'Country': country,
'PlotOutline': item['description'],
'Plot': item['long_description'],
'Year': item['year'],
'Rating': imdb['rating'],
'Votes': imdb['vo... | ry:
label = item['name'] + ' | ' + item['international_name'] + ' (' + item['year'] + ')'
icon = BASE_URL + item['cover']
video_id = item['movie_id']
items.append({
'label': | common.replaceHTMLCodes(label),
'icon': icon,
'id': video_id
})
except:
pass
except:
default_oc_noty()
return items
# method
def get_movie(id):
items = []
try:
result = common.fetchP... |
#!/usr/bin/python
NWID=1
NR_NODES=20
#Controllers=[{"ip":'127.0.0.1', "port":6633}, {"ip":'10.0.1.28', "port":6633}]
Controllers=[{"ip":'10.0.1.28', "port":6633}]
"""
Start up a Simple topology
"""
from mininet.net import Mininet
from mininet.node import Controller, RemoteController
from mininet.log import setLogLeve... | f stop( self ):
"Overridden to do nothing."
| return
def checkListening( self ):
"Warn if remote controller is not accessible"
listening = self.cmd( "echo A | telnet -e A %s %d" %
( self.ip, self.port ) )
if 'Unable' in listening:
warn( "Unable to contact the remote controller"
... |
s None:
style = self.accessor.style_at_pos(pos)
style_names = self.style_names_from_style_num(style)
raise CodeIntelError("got unexpected style in `%s': %s %s"
% (basename(self.path), style, style_names))
try:
langintel = self.mgr.... | s):
import koXMLTreeService
self.xml_parse()
tree = self._xml_tree_cache
if not tree:
return None
line, col = self.accessor.line_and_col_at_pos(pos)
node = tree.locateNode(line, col)
# XXX this needs to be worked out better
last_start = self.ac... | koXMLTreeService.elementFromText(
tree, self.accessor.text[last_start:last_end], node)
if node is None or node.start is None:
return node
# elementtree line numbers are 1 based, convert to zero based
node_pos = self.accessor.pos_from_line_and_col(
node.st... |
# -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import json
import logging
import os
from openerp import api, exceptions, models, tools
from openerp.modules.module import get_module_path
from ..addon_hash import addo... | pass
class IncompleteUpgradeError(exceptions.Warning):
pass
def ensure_module_state(env, modules, state):
# read module states, bypassing any Odoo cache
if not modules:
return
env.cr.execute(
"SELECT name FROM ir_module_module "
"WHERE id IN %s AND state != %s",
(... | l()]
if names:
raise FailedUpgradeError(
"The following modules should be in state '%s' "
"at this stage: %s. Bailing out for safety." %
(state, ','.join(names), ),
)
class Module(models.Model):
_inherit = 'ir.module.module'
@api.multi
def _get_chec... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | $schema': u'http://json-schema.org/draft-04/hyper-schema',
u'type': u'object',
u'properties': {
u'NetworkID': {
u'description': u'Network ID',
u'$ref': u'#/definitions/commons/definitions/id'
},
u'EndpointID': {
u'description': u'Endpoint ID',
... | |
rappe.conf.admin_password,
"root_login": frappe.conf.root_login,
"root_password": frappe.conf.root_password,
"db_type": frappe.conf.db_type,
}
site_data = {"test_site": TEST_SITE, **global_config}
for key, value in global_config.items():
if value:
self.execute(f"bench set-config {key} {value} -g")... | th": db_path})
self.assertEqual(self.returncode, 0)
self.assertEqual(frappe.db.count("ToDo"), todo_count)
def test_recorder(self):
frappe.recorder.stop()
self.execute("bench --site {site} start-recording")
frappe.local.cache = {}
self.a | ssertEqual(frappe.recorder.status(), True)
self.execute("bench --site {site} stop-recording")
frappe.local.cache = {}
self.assertEqual(frappe.recorder.status(), False)
def test_remove_from_installed_apps(self):
app = "test_remove_app"
add_to_installed_apps(app)
# check: confirm that add_to_installed_app... |
, and stop resources within a Kubernetes Cluster
version_added: "2.0"
options:
name:
required: false
default: null
description:
- The name associated with resource
filename:
required: false
default: null
description:
- The path and filename of the resource(s) definition file(s).
... | return False
return True
# TODO: This is currently unused, perhaps convert to 'scale' with a replicas param?
def stop(self):
| if not self.force and not self.exists():
return []
cmd = ['stop']
if self.filename:
cmd.append('--filename=' + ','.join(self.filename))
else:
if not self.resource:
self.module.fail_json(msg='resource required to stop without filename')
... |
'''
Created on 26/09/2014
@author: javgar119
'''
cluster_list =([Cluster(set([]), 0, 0, 1, 0),
Cluster(set([]), 1, 0, 1, 0)])
cluster_list2 = ([Cluster(set([]), 0, 0, 1, 0),
Cluster(set([]), 1, 0, 1, 0),
Cluster(set([]), 2, 0, 1, 0... | ]), 7, 0, 1, 0),
Cluster(set([]), 8, 0, 1, 0),
Cluster(set([]), 9, 0, 1, 0),
| Cluster(set([]), 10, 0, 1, 0),
Cluster(set([]), 11, 0, 1, 0),
Cluster(set([]), 12, 0, 1, 0),
Cluster(set([]), 13, 0, 1, 0),
Cluster(set([]), 14, 0, 1, 0),
Cluster(set([]), 15, 0, 1, 0),
... |
from rpitc.io import IO
class TestOut:
def test_init_on(self, gpio):
from rpitc.io.out import Out
out = Out(7, status=IO.ON)
assert out.status == IO.ON
out.off()
def test_set_pin(self, out):
assert out.set_pin(IO.ON) == IO.ON
def test_on(self, out):
out.on... | out.status == IO.ON
def test_off(self, out):
out.off()
assert out.status == IO.OFF
def test_toggle(self, out):
out.off()
out.toggle()
| assert out.status == IO.ON
out.toggle()
assert out.status == IO.OFF
|
import pytest
i | mport watchmaker
@pytest.fixture
def setup_object():
pass
def test_main():
"""Placeholder for tests"""
# Placeholder
assert watchmaker.__version__ == watchmaker.__ | version__
|
import os
import threading
import time
from django.conf import settings
from django.db import connections
from django.dispatch import receiver
from django.test.signals import setting_changed
from django.utils import timezone
from django.utils.functional import empty
# Most setting_changed receivers are supposed to be... | go.core.cache import caches
caches._caches = threading.local()
@receiver(setting_changed)
def update_connections_time_zone(**kwargs):
if kwargs['setting'] == 'TIME_ZONE':
# Reset process time zone
if hasattr(time, 'tzset'):
if kwargs['value']:
os.environ['TZ'] =... | else:
os.environ.pop('TZ', None)
time.tzset()
# Reset local time zone cache
timezone.get_default_timezone.cache_clear()
# Reset the database connections' time zone
if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
USE_TZ, TIME_ZONE... |
# coding:utf-8
"""
Django settings for turbo project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see | ERROR: type should be string, got "\nhttps://docs.djangoproject.com/en/1.11/ref/settings/\n\"\"\"\n\nimport datetime\nimport os\nimport turbosettings.parameters as parameters\nfrom turbosettings.generate_secret_key import secret_key_from_file\n\n# Build paths inside the project like this: o" | s.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
USE_X_FORWARDED_HOST = False
FORCE_SCRIPT_NAME = ""
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/h... |
import tensorflow as tf
from tensorflow.python.keras.layers import Conv2D, Conv2DTranspose, Conv3D, Dense, Reshape
tfgan = tf.contrib.gan
def basic_generator(noise):
"""Simple generator to produce MNIST images.
Args:
noise: A single Tensor representing noise.
Returns:
A generated image... | _after_reshape])(net)
net = Conv2DTranspose(64, kernel_size=4, strides=2, padding="same", activation='elu')(net)
net = Conv | 2DTranspose(32, kernel_size=4, strides=2, padding="same", activation='elu')(net)
# Make sure that generator output is in the same range as `inputs`
# ie [-1, 1].
net = Conv2D(1, kernel_size=4, activation = 'tanh', padding='same')(net)
return net
def conditional_generator(inputs):
"""Generator to pr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Robin Wen
# Date: 2014-11-18
# Desc: Connect to MySQL using MySQLdb package, and insert test data.
import MySQLdb as mdb
con = mdb.connect(host='10.10.3.121', user='robin', passwd='rob | in89@DBA', db='testdb', unix_socket='/tmp/mysql5173.sock', port=5173)
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Writers")
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES('... | .execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
con.close()
|
#import factorial
#import square
x = int(raw_input("What is 'x'?\n"))
y = int(raw_input("What is y?\n"))
# question0 = str(raw_input("Define a y value? (y/n)\n"))
# if (question0 == "y","Y","yes","Yes"):
# y = int(raw_input("What will 'y' be?\n"))
# elif (y == "n","N","no","No"):
# question2 = str(raw_input("I... | (x * y)
div = (x / y)
rem = (x % y)
xeven = (x % 2 == 0)
xodd = (x % 2 != 0)
yeven = (y % 2 == 0)
yodd = (y % 2 != 0)
# xfact = (factorial(x))
# yfact = (factorial(y))
print "If you add x and y, you'll get %s." % add
print "If you subtract x and y, you'll get %s." % sub
print "If you mul | tiply x and y, you'll get %s." % mult
print "If you divide x and y, you'll get %s, with a remainder of %s." % (div, rem)
if (x % 2 == 0):
print "x is even."
if (x % 2 != 0):
print "x is odd."
if (y % 2 == 0):
print "y is even."
if (y % 2 != 0):
print "y is odd."
print "If you square x, you get %s, and ... |
import pygame
import sys
from psistatsrd.app import App
def create_queue_row(data, config):
mem_graph = create_mem_graph(config)
cpu_graph = create_cpu_graph(config)
scroll_text = []
title = []
if type(data['ipaddr']).__name__ == "list":
scroll_text = scroll_text + data['ipaddr']
el... | =config['statrow.title_font_aa'],
title_font=config['statrow.title_font'],
title_color=config['statrow.title_color'],
)
return row
def create_scroller( | scroll_text, config):
s = Scroller(
scroll_speed = float(config['scroller.scroll_speed']),
scroll_delay = int(config['scroller.scroll_delay']),
scroll_pause = int(config['scroller.scroll_pause']),
text_font = config['scroller.font.name'],
text_aa = config['scroller.font.aa'],... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pipeline.py
# AstroObject
#
# Created by Alexander Rudy on 2012-04-25.
# Copyright 2012 Alexander Rudy. All rights reserved.
#
u"""
Basic CCD Reduction Pipeline written with AstroObject
"""
# Python Imports
import shutil
import os
import collections
# Numpy I... | tack()
self.load_type("Data",self.data)
@include # Set this stage as something to be run with the *all macro.
@depends("create-bias","load-data")
@help("Subtract Bias Frame")
def subtract_bias(self):
"""Subtracting Bias Frame"""
iraf.unlearn( | iraf.ccdproc)
iraf.ccdproc(self.data.iraf.modatfile(),
ccdtype="", fixpix="no", overscan="no", trim ="no", zerocor="yes", darkcor="no", flatcor ="no",
zero=self.bias.iin("Bias"))
self.data.idone()
@include # Set this stage as something to be run with the *all macro.... |
"""
Django settings for todo project.
Generated by 'django-admin startproject' using Django 1.9.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Bu... | : os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirn | ame(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-b9xx8+eul3#8q&c@tv^5e!u66j=a6@377$y^b2q!0a%vj+!ny'
... |
pace)
except (exception.Forbidden, exception.NotFound):
# NOTE (abhishekk): Returning 404 Not Found as the
# namespace is outside of this user's project
msg = _("Namespace %s not found") % namespace
raise webob.exc.HTTPNotFound(explanation=msg)
try:
... | if visibility not in ['public', 'private']:
msg = _('Invalid visibility value: %s') % visibility
raise webob.exc.HTTPBadReq | uest(explanation=msg)
return filters
def _validate_limit(self, limit):
try:
limit = int(limit)
except ValueError:
msg = _("limit param must be an integer")
raise webob.exc.HTTPBadRequest(explanation=msg)
if limit < 0:
msg = _("limit ... |
n), subset of atoms in molecule Pn which are in Rm before reaction.")
report_mats("CP", CP)
def form_B(C):
"""Construct the B-matrices.
Returns a dict with (m, n) keys, containing the respective
subsets of C[(m, n)] that acutally participate in bond-breaking/forming.
"""
... | average
center_fragments(rfrag_lists, runion)
center_fragments(pfrag_lists, punion)
backup_coords(0)
# Translate reactant molecules
alphas = get_steps_to_active_atom_mean(
| rfrag_lists, rfrag_lists, AR, runion.coords3d
)
for rfrag, alpha in zip(rfrag_lists, alphas):
runion.coords3d[rfrag] += alpha
# Translate product molecules
betas = get_steps_to_active_atom_mean(
pfrag_lists, rfrag_lists, BR, punion.coords3d, skip=False
)
sigmas = get_step... |
# -*- coding: utf-8 -*-
from __future__ impor | t unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('broadcasts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='broadcast',
name='series',
field=models.ForeignKey(... | me='status',
field=models.CharField(max_length=200, blank=True),
),
]
|
"""
WSGI config for tiendalibros project.
It exposes the WSGI callable as a module-level variable named ``application``.
|
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_ap | plication
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tiendalibros.settings")
application = get_wsgi_application()
|
# Inviwo Python script
import inviwo
import math
import time
start = time.clock()
scale = 1;
d = 15
steps = 120
for i in range(0, steps):
r = (2 * 3.14 * i) / steps
x = d*math.sin(r)
z = -d*math.cos(r)
inviwo.setPropertyValue("EntryExitPoints.camera",((x*scale,3*scale,z*scale),(0,0,0),(0,... | )))
for i in range(0, steps):
r = (2 * 3.14 * i) / (steps)
x = 1.0*math.sin(r)
z = 1.0*math.cos(r)
inviwo.setCameraUp("EntryExitPoints.camera",(x*scale,z*scale,0))
end = time.clock()
fps = 2*steps / (end - start)
fps = round(fps,3)
print("Frames per second: " + s | tr(fps))
print("Time per frame: " + str(round(1000/fps,1)) + " ms") |
# Copyright 2019 Google LLC
#
# 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 writing, ... |
saver.restore(sess, tf.train.latest_checkpoint(x_dir))
x_final, y_final = sess.run([x, y])
# Make sure that x is loaded correctly from checkpoint, and that y
# isn't.
self.assertEqual(x_initial, x_final)
self.assertNotAllClose(y_initial, y_final)
class FilterNormalizationTest(tf.test.Te... | get_variable('abcdef/biases', shape=[2])
w = tf.get_variable('unpaired/weights', shape=[7, 5, 3, 2])
x = tf.get_variable('untouched', shape=[])
normalize_ops = experiment_utils.normalize_all_filters(
tf.trainable_variables())
with self.test_session() as sess:
sess.run(tf.global_variables... |
#!/usr/bin/python
'''
This script is used to generate a set of random-ish events to
simulate log data from a Juniper Netscreen FW. It was built
around using netcat to feed data into Flume for ingestion
into a Hadoop cluster.
Once you have Flume configured you would use the following
command to populate data:
./g... | ile (1 == 1):
proto_index = random.randint(0,1)
protocol = protocols[proto_index]
src_port_index = random.randint(0,13)
dest_port_index = random.randint(0,13)
src_port = common_ports[src_port_index]
dest_port = common_ports[dest_port_index]
action_index = random.randint | (0,3)
action = action_list[action_index]
src_ip_index = random.randint(1,254)
src_ip = src_network[src_ip_index]
dest_ip_index = random.randint(1,65535)
dest_ip = dest_network[dest_ip_index]
event = "192.168.1.3 Netscreen-FW1: NetScreen device_id=Netscreen-FW1 [Root]system-notification-00257(tra... |
import struct, socket, time, logging
from gosh.config import STUN_SERVER, STUN_PORT, logger
from gosh import JsonSocket
#=============================================================================
# STUN Client
# ============================================================================
class StunClient(object):... | ior testing nat """
message = self.CreateMessage()
data = self.binding_request(STUN_SERVER, STUN_PORT, message, True)
if not data:
return False
#======================== | =====================
# TEST I
# ============================================
logger.debug("mapping_behavior: TEST_I")
LOCAL_ADDR = "%s:%d" % self.local_addr
TEST_I = data['XOR-MAPPED-ADDRESS']
logger.debug("mapping_behavior: Public IP %s"%TEST_I)
OTHER_SERVER, OTHER_PORT = data['OTHER-ADDRESS'].split... |
from django.conf.urls.defaults import *
from models import Entry, Tag
from django.vie | ws.generic.dates import ArchiveIndexView, DateDetailView
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^/?$', ArchiveIndexView.as_view(model=Entry, date_field="published_on"), name="news-main"),
# url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[0-9A-Za-z-]+... | )/(?P<day>\d+)/(?P<pk>\d+)/$',
DateDetailView.as_view(model=Entry, date_field="published_on"),
name="news_detail"),
url(r'^about/$', TemplateView.as_view(template_name='news/about.html'), name='news-about'),
)
|
from collections imp | ort OrderedDict
n = int(input())
occurrences = OrderedDict()
for _ in range(0, n):
word = input().strip()
occurrences[word] = occurrences.get(word, 0) + 1
print(len(occurrences))
print( | sep=' ', *[count for _, count in occurrences.items()])
|
from nbdiff.adapter import git_adapter as g
from pretend import stub
def test_get_modified_notebooks_empty():
g.subprocess = stub(check_output=lambda cmd: 'true\n'
if '--is-inside-work-tree' in cmd
else '')
adapter = g.GitAdapter()
result = adapter.get_modif... | en(*args, **kwargs):
return stub(stdout=stub(read=lambda: ""))
g.open = lambda fname: stub(read=lambda: "")
g.subprocess = stub(
check_output=check_output_stub,
PIPE='foo',
Popen=popen,
)
g.os.path.exists = lambda path: 'bar.ipynb' in path
result = adapter.get_modifi... | g.GitAdapter()
def check_output_stub(cmd):
if '--modified' in cmd:
output = '''foo.ipynb
bar.ipynb
foo.txt
baz.ipynb
'''
return output
elif '--unmerged' in cmd:
return ''.join([
'100755\thash\t{i}\tfoo.ipynb\n'
for i in [1, 2, 3]
... |
of the loop only if `self.put()` had triggered
# `self.__tick` because `self._next_peek` wasn't set
self.logger.debug("Next task isn't due yet. Finished!")
self.queue.put((t, job))
self._set_next_peek(t)
break
if job.... | 's :attr:`context`
or change it to a repeating job.
interval (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta`, optional): The interval in
which the job will run. If it is an :obj:`int` or a :obj:`float`, it will be
interpreted as seconds. If you don't set this value... | set :attr:`repeat` to
``False`` and specify :attr:`next_t` when you put the job into the job queue.
repeat (:obj:`bool`, optional): If this job should be periodically execute its callback
function (``True``) or only once (``False``). Defaults to ``True``.
context (:obj:`objec... |
# Add a display showing the error token itsels:
s = s.replace('\n', ' ').replace('\t', ' ')
offset = pos
if len(s) > pos+10:
s = s[:pos+10]+'...'
if pos > 10:
s = '...'+s[pos-10:]
offset = 13
msg += '\n%s"%s"\n%s^' % (' '*16, s, ' '*(17+off... | except (TypeError, ValueError):
raise ValueError("%s: node value and children "
"must be immutable" % type(self).__name__)
def __setitem__(self, index, value):
raise ValueError('%s may not be modified' % type(self).__name__)
def __setslice__(self, i, j, value):
... | self).__name__)
def __delitem__(self, index):
raise ValueError('%s may not be modified' % type(self).__name__)
def __delslice__(self, i, j):
raise ValueError('%s may not be modified' % type(self).__name__)
def __iadd__(self, other):
raise ValueError('%s may not be modified' % type(se... |
# Copyright 2019 Google LLC.
"""Pipeline to decode and reencode a video using OpenCV."""
from absl import app
from absl import flags
from video_processing import processor_r | unner
from video_processing.processors import opencv_video_decoder
from video_processing.processors import opencv_video_encoder
flags.DEFINE_string('input_ | video_file', '', 'Input file.')
flags.DEFINE_string('output_video_file', '', 'Output file.')
FLAGS = flags.FLAGS
def pipeline(input_video_file, output_video_file):
return [
opencv_video_decoder.OpenCVVideoDecoderProcessor(
{'input_video_file': input_video_file}),
opencv_video_encoder.OpenCVVi... |
import boto
import sure # noqa
from mo | to import mock_ec2 |
@mock_ec2
def test_placement_groups():
pass
|
ts: (list of :class:`AST`) elements
"""
_fields = ("elts", "ctx")
class ListComp(expr, beginendloc):
"""
A list comprehension, e.g. ``[x for x in y]``.
:ivar elt: (:class:`AST`) comprehension body
:ivar generators: (list of :class:`comprehension`) ``for`` clauses
"""
_fields = ("elt", "... | ass UnaryOp(expr):
"""
An unary operation, e.g. ``+x``.
:ivar op: (:class:`unaryop`) o | perator
:ivar operand: (:class:`AST`) operand
"""
_fields = ("op", "operand")
class Yield(expr):
"""
A yield expression, e.g. ``yield x``.
:ivar value: (:class:`AST`) yielded value
:ivar yield_loc: location of ``yield``
"""
_fields = ("value",)
_locs = expr._locs + ("yield_loc",... |
#! /usr/bin/env python
# @brief Script to run apropriate tests.
import os
import distutils.core
from shutil import rmtree, copyfile
"""Avaiable tests dictionary in the format no_of_test : name_of_test"""
tests = {0:"default Generator.dat with lot of comments and explanations",
1:"RHIC pt_pi, eta_pi; tecm = 200... | """
#save old config file
copyfile(configFile, "OLD"+configFile)
#copy configuration files
fromDirectory = testDir + '/' + testName + str(number)
copyfile(fromDirectory, configFile)
return testDir
| def rmDir( directory = "./" ):
"""Remove directory and all its content
@param directory base directory for project
"""
rmtree( directory )
def runMake( option, runDir = './'):
"""Run make with option in given directory
@param option option for make
@param runDir directory in which make... |
#!/usr/bin/python
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
# The unittest framwork doesn't play nice with pylint:
# pylint: disable-msg=C0103
from __future__ import absolute_impor | t
import unittest
from svtplay_dl.service.oppetarkiv import OppetArkiv
from svtplay_dl.service.tests import HandlesURLsTestMixin
class handlesTest(unittest.TestCase, HandlesURLsTestMixin):
service = OppetArkiv
urls = {"ok": ["http://www.oppetarkiv.se/video/1129844/jacobs-stege-avsnitt-1-av-1"], "bad": ["htt... | 90393/del-9"]}
|
#!/usr/bin/env python
# Unix SMB/CIFS implementation.
# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
#
# 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 Lice... | self.assertEquals("foo bla",
samba.substitute_var("foo ${bar}", {"bar": "bla"}))
def test_broken(self):
self.assertEquals("foo ${bdkjfhsdkfh sdkfh ",
samba.substitute_var("foo ${bdkjfhsdkfh sdkfh ", {"bar": "bla"}))
def test_unknown_var(self):
self.assertEqual... | gsff",
samba.substitute_var("foo ${bla} gsff", {"bar": "bla"}))
def test_check_all_substituted(self):
samba.check_all_substituted("nothing to see here")
self.assertRaises(Exception, samba.check_all_substituted,
"Not subsituted: ${FOOBAR}")
class LdbExtensionTests(... |
#coding: utf-8
# Copyright 2005-2010 Wesabe, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | encodings, and if no encoding is given, UTF-8 (which is a
# superset of US-ASCII) | should be assumed; but if a named
# encoding other than USASCII or 'UNICODE' is given, that
# should be preserved. I'm also adding a get_encoding()
# method so that we can start to survey what encodings
# we're actually seeing, and use that to maybe be smarter
# about this in t... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import cPickle
import WebIDL
from Configuration import *
from Codegen import CGBindingRoot, replaceFileIfChang... | file)
if replaceFileIfChanged(filename, root.declare()) | :
print "Generating binding header: %s" % (filename)
def generate_binding_cpp(config, outputprefix, webidlfile):
"""
|config| Is the configuration object.
|outputprefix| is a prefix to use for the header guards and filename.
"""
filename = outputprefix + ".cpp"
root = CGBindingRoot(con... |
currencies/exchange_rates")
except Exception:
return
quote_currencies = {}
try:
for r in jsonresp:
if r[:7] == "btc_to_":
quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
with self.lock:
s... | except KeyError:
pass
self. | parent.set_currencies(quote_currencies)
def get_currencies(self):
return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
def _lookup_rate(self, response, quote_id):
return decimal.Decimal(str(response[str(quote_id)]["15m"]))
def _lookup_rate_cb(self, response... |
import cherrypy
from cherrypy.test import helper
class ETagTest(helper.CPWebCase):
def setup_server():
class Root:
def resource(self):
return "Oh wah ta goo Siam."
resource.exposed = True
def fail(self, code):
code = int(cod... | tus(304)
self.getPage("/fail/412", headers=[('If-None-Match', "*")])
self.assertStatus(412)
self.getPage("/fail/304", headers=[('If-None-Match', "*")])
self.assertStatus(304)
def test_unicode_body(self):
self.getPage("/unicoded")
self.assertStatus(200)
et... | f.assertHeader('ETag', etag1)
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | t Profile:")
profile = conn.cluster.get_profile('os_server')
print(profile.to_dict())
def find_profile(conn):
print("Find Profile:")
profile = conn.cluster.find_profile('os_server')
print(profile.to_dict())
def update_profile(conn):
print("Update Profile:")
profile = conn.cluster.upda... | d_server')
print(profile.to_dict())
def delete_profile(conn):
print("Delete Profile:")
conn.cluster.delete_profile('os_server')
print("Profile deleted.")
|
# coding: utf | -8
from django.db import models
class Band(models.Model):
name = models.CharField(max_length=100)
bio = models.TextField()
rank = models.IntegerField()
class Meta:
ordering = ('name',) | |
#!/usr/bin/env python3
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from SetupTools.SetupConfig import SetupConfig
from Interface.Interface import Interface
import importlib
import logging
class Previewer:
def __init__(self):
logging.basicConfig(filename='ArchSetup.preview.log',... | tattr(i, x)
self.windows.append(cl(self.callback, self.setupconfig))
self.interface.addwin(self.win | dows[self.window_index])
elif event == 'prev':
self.window_index -= 1
self.interface.addwin(self.windows[self.window_index])
elif event == 'next':
self.window_index += 1
if self.window_index == len(self.windows):
self.interface.exit()
... |
#!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# 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 ... | for i in range(manager.GetNumberOfVehicles()):
routing.AddVariableMinimizedByFinalizer(
token_dimension.CumulVar(routing.Start(i)))
| routing.AddVariableMinimizedByFinalizer(
token_dimension.CumulVar(routing.End(i)))
# [END depot_start_end_times]
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (
routing_enums_pb2.FirstSol... |
# -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/vip | er-framework/viper
# See the file 'LICENSE' for copying permission.
from viper.common.out import print_info
from viper.common.out import print_error
from viper.common.out import print_output
from viper.core.plugins import __modules__
from viper.core.session impo | rt __sessions__
from viper.core.database import Database
from viper.core.config import __config__
from viper.core.storage import get_sample_path
cfg = __config__
def parse_commands(data):
root = ''
args = []
words = data.split()
root = words[0]
if len(words) > 1:
args = words[1:]
re... |
mbda_facts:
query: all
function_name: myFunction
register: my_function_details
# List all versions of a function
- name: List function versions
lambda_facts:
query: versions
function_name: myFunction
register: my_function_versions
# List all lambda function versions
- name: List all function
lam... | tems nor next_marker for query=all.')
lambda_facts = dict()
function_name = module.params.get('function_name')
if function_name:
| lambda_facts[function_name] = {}
lambda_facts[function_name].update(config_details(client, module)[function_name])
lambda_facts[function_name].update(alias_details(client, module)[function_name])
lambda_facts[function_name].update(policy_details(client, module)[function_name])
lambda_fac... |
from circularbuffer import CircularBuffer
from pytest import raises
def test_index():
buf = Circul | arBuffer(32)
buf.write(b'asdf\r\njkl;\r\n1234\r\n')
assert buf.index(b'\r\n') == 4
assert buf.index(b'\r\n', 5) == 10
wi | th raises(ValueError):
buf.index(b'x')
buf.clear()
buf.write(b'asdf\r\njkl;\r\n1234\r\na')
assert buf.index(b'\r\n') == 4
assert buf.index(b'\r\n', 5) == 10
with raises(ValueError):
buf.index(b'x')
with raises(ValueError):
buf.index(b'')
|
import rpw
from pyrevit.sc | ript import get_logger
logger = get_logger()
selection = rpw.ui.Selection()
# TODO check in only one loop
number_of_unused_connectors = sum([element.ConnectorManager.UnusedConnectors.Size for element in selection])
logger.debug(number_of_unused_connectors)
if number_of_unused_connectors > 2:
rpw.ui.forms.Alert('P... | element.ConnectorManager.UnusedConnectors
|
from elan import *
#Set System description
#Finished
Viewer.Start()
Viewer.CloseAndClean()
Configurator.Start()
Configurator.basicinformation.Click()
Configurator.systemname.Wait()
sleep(1)
Configurator.Edit.SetText(2,"Changed")
Configurator.apply.Wait()
Configurator.apply.Click()
Configurator.RestartHard()
Configur... | omeBackOnline()
Configurator.S | tart()
Configurator.basicinformation.Click()
Configurator.systemdescriptionchangedset.Wait()
Configurator.Edit.SetText(2," ")
Configurator.apply.Wait()
Configurator.apply.Click()
Configurator.CloseAndClean()
print(' Finished') |
#!/usr/bin/env python3
import inspect
from classes.rgams_SRS import rgams_SRS
from classes.selectorvalve_VICI import selectorvalve_VICI
from classes.selectorvalve_compositeVICI import selectorvalve_compositeVICI
from classes.pressuresensor_WIKA import pressuresensor_WIKA
from classes.pressuresensor_... | HIS NEEDS THE underscore PACKAGE: \\usepackage[strings]{underscore}\n\n' )
for X in CLASSES:
outfile.write ( '\subsubsection{Class \\texttt{' + X.__name__ + '}}\n' )
P = inspect.getsourcefile(X)
outfile.write ( '\path{' + P[P.find('python'):len(P)] + '}\par\n' )
doc = inspect.getdoc(X)
if doc is None:
outfile.w... | X) + '\par' )
outfile.write ( '\n\n' )
for name, data in inspect.getmembers(X):
if name[0:2] == '__' :
continue
if name == '__doc__':
continue
if name == '__init__':
continue
if name == '__module__':
continue
outfile.write ( '\paragraph{Method \\texttt{' + name + '}}\n\\vspace{1ex}\n' )
exec... |
import scipy.cluster.hierarchy as hcl
from scipy.spatial.distance import squareform
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram
import scipy
import json
#data = pd | .read_json(path_ | or_buf= 'C:\Users\davtalab\Desktop\outJSON.json')
parsed_json = json.loads(open('C:\Users\davtalab\Desktop\data.json').read())
print parsed_json[1]['id']
|
': {
'name': long_name,
},
}
req = fakes.HTTPRequest.blank(self.url)
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._action_create_image, req,
FAKE_UUID, body)
def _do_test_create_volume_backed_ima... | _meta_from_vol_without_extra_meta(self):
self._test_create_volume_backed_image_with_metadata_from_volume()
def test_create_vol_backed_img_with_meta_from_vol_with_extra_meta(self):
self._test_create_volume_backed_image_with_metadata_from_volume(
extra_metadata={'a': 'b'})
|
def test_create_image_snapshots_disabled(self):
"""Don't permit a snapshot if the allow_instance_snapshots flag is
False
"""
self.flags(allow_instance_snapshots=False)
body = {
'createImage': {
'name': 'Snapshot 1',
},
}
... |
from rest_framework import serializers
from models import SurveyDraft
from taggit.models import Tag
class WritableJSONField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
""" ALSO REQUIRED because the default JSONField serialization includes the
`u` prefix on string... | odelSerializer):
count = serializers.SerializerMethodField()
label = serializers.CharField(source='name')
class Meta:
model = Tag
fields = ('id', 'label', 'count')
def get_count(self, obj):
return SurveyDraft.objects.filter(tags__name__in=[obj.name])\
.filter(user=se... | |
from .util.deb import deb
from .util.nrange import nrange
from .cell import Cell
#F,e,Cursor
from .grid import spoint
CURSOR_POS=None
def gcp(): #get cursor position
global CURSOR_POS
deb('gcp',CURSOR_POS)
return CURSOR_POS
def scp(x,y):
deb('scp',gcp(),x,y)
cxc=0 #todo, normalize in cursor...
global CURSOR_P... | pset
cpget=gcp
cpset=scp
def cursor(HG,x,y,f,X,Y):
deb('make an a cursor in the empty space around point in cell x,y',x,y)
#x,y=x-1,y-1
assert len(f)==4
#HG=_clearcursor(HG)
i=x
j=y
scp | (i,j)
cxl=Cell(f[0],0,0)
cyu=Cell(f[1],0,0)
cxr=Cell(f[2],0,0)
cyd=Cell(f[3],0,0,)
HG=spoint(i-1,j,HG,cxl)
HG=spoint(i,j-1,HG,cyu)
HG=spoint(i+1,j,HG,cxr)
HG=spoint(i,j+1,HG,cyd)
return HG
def grid_cursor(HG,x,y,f,X,Y):
return cursor(HG,x,y,f,X,Y)
def _clearcursor(HG):
cp=gcp()
r1=r2=r3=r4=Cell('.',0,0)
... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... | )/$', 'maps_tag', name='maps_browse_tag'),
url(r'^new$', 'new_map', name="new_map"),
url(r'^new/data$', 'new_map_json', name='new_map_json'),
url(r'^(?P<mapid>\d+)$', 'map_detail', name='map_detail'),
url(r'^(?P<mapid>\d+)/view$ | ', 'map_view', name='map_view'),
url(r'^(?P<mapid>\d+)/data$', 'map_json', name='map_json'),
url(r'^(?P<mapid>\d+)/download$', 'map_download', name='map_download'),
url(r'^(?P<mapid>\d+)/wmc$', 'map_wmc', name='map_wmc'),
url(r'^(?P<mapid>\d+)/remove$', 'map_remove', name='map_remove'),
url(r'^(?P<m... |
# Copyright 2019-2020 Camptocamp SA
# Copyright 2015 Mathias Neef copadoMEDIA UG
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Switzerland Country States",
"category": "Localisation",
"summary": "",
"version": "14.0.1.0.0",
"author": "copado MEDIA UG," "Odoo Community As... | ation (OCA)",
"websi | te": "https://github.com/OCA/l10n-switzerland",
"license": "AGPL-3",
"depends": ["base"],
"data": ["data/res_country_states.xml"],
}
|
le
def bookmark_button_visible(self):
""" Check if bookmark button is visible """
EmptyPromise(lambda: self.q(css='.bookmark-button').visible, "Bookmark button visible").fulfill()
return True
@property
def bookmark_button_state(self):
""" Return `bookmarked` if button is in... | ='.bookmark-button').first.click()
EmptyPromise(lambda: self.bookmark_button_state != previous_state, "Bookmark button toggled").fulfill()
# TODO: TNL-6546: Remove this helper function
def click_bookmarks_button(self):
""" Click on Bookmarks button """
self.q(css='.bookmarks-list-button... | arks_page.visit()
class CoursewareSequentialTabPage(CoursePage):
"""
Courseware Sequential page
"""
def __init__(self, browser, course_id, chapter, subsection, position):
super(CoursewareSequentialTabPage, self).__init__(browser, course_id)
self.url_path = "courseware/{}/{}/{}".format... |
# Copyright 2019 Google LLC
#
# 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, ... | t up tracing autoinstrumentation for sqlalchemy
SQLAlchemyInstrumentor().instrument(
engine=self.engine,
service='users',
)
def add_user(self, user):
"""Add a user to the database.
Params: u | ser - a key/value dict of attributes describing a new user
{'username': username, 'password': password, ...}
Raises: SQLAlchemyError if there was an issue with the database
"""
statement = self.users_table.insert().values(user)
self.logger.debug('QUERY: %s', str(state... |
# Copyright 2021 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | ance_reservations', 'affinity',
existing_type=mysql.TINYINT(display_width=1),
nullable=True)
op.drop_table('devi | ce_reservations')
op.drop_table('device_allocations')
op.drop_table('device_extra_capabilities')
op.drop_table('devices')
# ### end Alembic commands ###
|
from django.conf.urls import patterns, include, url
from django.co | ntrib import admin
from api import views
admin.autodiscover()
from res | t_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'headings', views.HeadingViewSet)
router.register(r'users', views.UserViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
) |
if self.version >= 2:
del error["result"]
else:
error["result"] = None
error["error"] = {"code": code, "message": message}
if data is not None:
error["error"]["data"] = data
return error
# ----------------------------------------------------... | message = resu | lt["error"].get("trace", "<no error message>")
if -32700 <= code <= -32000:
# Pre-defined errors
# See http://www.jsonrpc.org/specification#error_object
raise ProtocolError((code, message))
else:
# Application error
... |
# ####################################################################
# gofed - set of tools to automize packaging of golang devel codes
# Copyright (C) 2014 Jan Chaloupka, jchaloup@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licen... | rn False
f.close()
return True
def getProvides(self):
"""Fetch a spec file from pkgdb and get provides from all its [sub]packages"""
if self.sp_obj == None:
return {}
return self.sp_obj.getProvides()
de | f getPackageCommits(self):
if self.sp_obj == None:
return ""
return self.sp_obj.getMacro("commit")
def getPkgURL(self):
if self.sp_obj == None:
return ""
return self.sp_obj.getTag("url")
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
#
# @author Meng G.
# 2016-03-28 restructed
from sqip.config import *
from sqip.libs import *
dashboard = Blueprint('dashboard', __name__, template_folder='templates')
@base.route('/admin/lo | gin' , methods=['GET'])
@union_bug
def admin_login():
template = env.get_template('login.html')
return template.render()
@base.route('/admin' , methods=['GET'])
@base.route('/admin/< | oath:path>' , methods=['GET'])
@union_bug
def admin():
template = env.get_template('index.html')
return template.render() |
#coding=utf-8
class Quantity:
__counter = 0
def __init__(self):
cls = self.__class__
prefix = cls.__name__
index = cls.__counter
self.storage_name = '_{}#{}'.format(prefix, index)
cls.__counter += 1
def __set__(self, isinstance, value):
if value > 0:
... | dict__[self.storage_name] = value
else:
raise ValueError('value must be > 0')
class LineItem:
weight = Quantity()
price = Quantity()
def __init__(self, description, weight, price):
self.description = description
| self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
|
"key": "/key.pem",
},
"host": "localhost",
"user": "scott",
"port": 3306,
},
)
@testing.combinations(
("compress", True),
("connect_timeout", 30),
("read_timeout", 30),
("write_timeout", 30),
... | SHOW VARIABLES"
):
engine.connect()
def | test_no_default_isolation_level(self):
from sqlalchemy.testing import mock
engine = engines.testing_engine()
real_isolation_level = testing.db.dialect.get_isolation_level
def fake_isolation_level(connection):
connection = mock.Mock(
cursor=mock.Mock(
... |
# @source http://rosettacode.org/wiki/Bitwise_IO#Python
# @license http://www.gnu.org/licenses/fdl-1.2.html
import logging
logger = logging.getLogger('naabal.util.bitio')
class BitIO(object):
BITS_IN_BYTE = 8
DEFAULT_MASK = 1 << (BITS_IN_BYTE - 1) # 0x80
def __init__(self, handle):
self._d... | self._bit_buffer |= self._bit_mask
self._bit_mask = self._bit_mask >> 1
if self._bit_mask == 0:
self._flush_bit_buffer()
self._reset_state()
mask = mask >> 1
def flush(self):
| if self._bit_mask != self.DEFAULT_MASK:
self._flush_bit_buffer()
self._reset_state()
return self._bit_idx
def _flush_bit_buffer(self):
self._data_buffer.write(chr(self._bit_buffer))
self._bit_idx += 1
def _reset_state(self):
self._bit_buffer = 0x00
... |
# Copyright (c) 2003-2008 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ | -- mailto:contact@logilab.fr
#
# 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 hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FO... |
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.urls import path
from confla import views
app_name = "confla"
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.IndexView... | rl_id>\w+)/events/$', views.EventView.event_list, name='event_list'),
| url(r'^(?P<url_id>\w+)/places/$', views.PlacesView.osm, name='places'),
url(r'^(?P<url_id>\w+)/about/(?P<page>\w+)$', views.PagesView.content, name='pages'),
url(r'^(?P<url_id>\w+)/speakers/grid/$', views.UserView.speaker_grid, name='speaker_grid'),
url(r'^(?P<url_id>\w+)/speakers/list/$', vie... |
from pprint import pprint
from django.shortcuts import render
def index(request):
return render(request, 'itat/ind | ex.html')
| |
# -*- coding: utf-8 -*-
import ConfigParser, sys, os, urllib2, json, time, shutil, filecmp
import Levenshtein
config = ConfigParser.ConfigParser()
config.read("config.ini")
def clean(chaine):
#print chaine
return chaine.lower().strip()
def decode(chaine):
chaine = chaine.replace(u"\u2018", "'").replace(u"... | ']):
return t
##print "### :: " + i['artist'] + '-' + i['name'] + ""
ties = []
for t in self.findtrack(a, i['name'], lev=True):
ties.append(t)
if len(ties) == 0:
return 0
if len(ties) == 1:
##print ties[0][1]
return ties... | lf.limit+"_%m%d%H%M.m3u")
fo = open(file, 'w+')
number = 0
for i in self.toptracks():
number += 1
print number
#for i in [{'name':u"The sound of silence",'artist':u"Simon and Garfunkel"}]:
a = self.findartist(i['artist'])
t = 0
... |
##
# Copyright 2012-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://ww | w.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
# |
# EasyBuild 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 v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILI... |
import json
from rhino import Mapper, get
# Our internal representation
report = {
'title': 'foo',
'author': 'Fred',
'date': '2015-01-09',
'tags': ['a', 'b', 'c'],
}
# Base class for our representations
class report_repr(object):
@classmethod
def serialize(cls, report):
obj = dict([(k... | [k]) for k in cls.fields])
return json.dumps(obj, sort_keys=True)
# Different versions of the representation
class report_v1(report_repr):
provides = 'application/vnd.acme.report+json;v=1'
fields = ['title', 'author']
class report_v2(report_repr):
provides = 'application/vnd.acme.report+json;v=2'
... | date']
class report_v3(report_repr):
provides = 'application/vnd.acme.report+json;v=3'
fields = ['title', 'author', 'date', 'tags']
# One handler can handle multiple representations.
# Here, report_v3 is the default when the client doesn't specify a preference.
@get(produces=report_v1)
@get(produces=report_v... |
# Copyright 2013 Kylin, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | f.neutron_quotas.first()
res = self.client.get(INDEX_URL)
self.assertTemplateUsed(res, 'admin/defaults/index.html')
expected_data = [
'<Quota: (injected_file_con | tent_bytes, 1)>',
'<Quota: (metadata_items, 1)>',
'<Quota: (injected_files, 1)>',
'<Quota: (ram, 10000)>',
'<Quota: (instances, 10)>',
'<Quota: (cores, 10)>',
'<Quota: (key_pairs, 100)>',
'<Quota: (server_groups, 10)>',
'<Qu... |
# Copyright (C) 2010-2013 Claudio Guarnieri.
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
"""Added failed statuses to tasks (from Cuckoo 1.1 to 1.2)
Revision ID: 495d5a6edef3
Revises: 18eee46c6f8... | d["id"] = item[0]
d["target"] = item[1]
| d["category"] = item[2]
d["timeout"] = item[3]
d["priority"] = item[4]
d["custom"] = item[5]
d["machine"] = item[6]
d["package"] = item[7]
d["options"] = item[8]
d["platform"] = item[9]
d["memory"] = item[10]
... |
self.fake_action_2.get('max_retries'))
self.assertEqual(result.get('max_retries_interval'),
self.fake_action_2.get('max_retries_interval'))
freezer_action = result.get('freezer_action')
self.assertEqual(freezer_action.get('action'),
... | while (count < 20):
doc = copy.deepcopy(self.fake_action_3)
action_id = common.get_fake_action_id()
doc['action_id'] = action_id
if count in [0, 4, 8, 12, 16]:
doc['max_retries'] = 10
result = self.dbapi.add_action(user_id=self.fake_acti... | oc=doc,
project_id=self.fake_project_id)
self.assertIsNotNone(result)
self.assertEqual(result, action_id)
actionids.append(action_id)
count += 1
search_opt = {'match': [{'_all': '[{"max_retries": 10}]'}]}
|
import attr
from widgetastic.widget import View, Text
from widgetastic_patternfly import Tab, Input, BootstrapSwitch, Button
from wrapanapi.rhevm import RHEVMSystem
from cfme.common.candu_views import VMUtilizationView
from cfme.common.provider import CANDUEndpoint, DefaultEndpoint, DefaultEndpointForm
from cfme.comm... | '(//*[@id="remote-console"]/canva | s|//*[@id="spice-screen"]/canvas)'
_ctrl_alt_del_xpath = '//*[@id="ctrlaltdel"]'
_fullscreen_xpath = '//*[@id="fullscreen"]'
bad_credentials_error_msg = "Credential validation was not successful"
ems_events = [
('vm_create', {'event_type': 'USER_ADD_VM_FINISHED_SUCCESS', 'vm_or_template_id': No... |
#!/usr/bin/env python3
from distutils.core import setup
from catkin_pkg.python_setup impo | rt generate_distutils_setup
d = generate_distutils_setup(
packages=['lg_keyboard'],
package_dir={'': 'src'},
scripts=[],
requires=[]
)
setup(**d)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# clamm documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 2 20:47:20 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... | tml_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'clammdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterp | aper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document ... |
#############################################################################
##
## Copyright (C) 2015 The Qt Company Ltd.
## Contact: http://www.qt.io/licensing
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance wit... | Config != config:
test.fatal("Build configuration %s is selected instead of %s" % (buildConfig, config))
continue
test.log("Testing build configuration: " + config)
if not JIRA.isBugStillOpen(13700):
invokeMenuItem("Build", "Run qmake")
waitForCompile()
... | # Add a new run configuration
invokeMenuItem("File", "Exit")
def init():
global SpeedCrunchPath
SpeedCrunchPath = os.path.join(srcPath, "creator-test-data", "speedcrunch", "src", "speedcrunch.pro")
cleanup()
def cleanup():
# Make sure the .user files are gone
cleanUpUserFiles(SpeedCrunchPath)... |
import shipane_sdk
# 初始化函数,设定要操作的 | 股票、基准等等
def initialize(context):
# 定义一个全局变量, 保存要操作的股票
# 000001(股票:平安银行)
g.security = '000001.XSHE'
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
def process_initialize(context):
# 创建 StrategyManager 对象
# 参数为配置文件中的 manager id
g.__manager = shipane_sdk.JoinQuantStrategyManagerFactory(contex... | der_ = order(g.security, 100)
# 实盘易依据聚宽的 order 对象下单
g.__manager.execute(order_)
order_ = order(g.security, -100)
g.__manager.execute(order_)
# 撤单
g.__manager.cancel(order_)
|
pplicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
from oslo_v... | e_id)
class ResourcesPullRpcCallbackTestCase(ResourcesRpcBaseTestCase):
def setUp(self):
super(ResourcesPullRpcCallbackTestCase, self).setUp()
self.callbacks = resources_rpc.ResourcesPullRpcCallback()
self.resource_obj = _create_test_resource(self.context)
def test_pull(self):
... | ck.patch.object(
resources_rpc.prod_registry, 'pull',
return_value=self.resource_obj) as registry_mock:
primitive = self.callbacks.pull(
self.context, resource_type=FakeResource.obj_name(),
version=FakeResource.VERSION,
resource... |
#!/usr/bin/env python
traindat = '../data/fm_train_real.dat'
testdat = '../data/fm_test_real.dat'
parameter_list = [[traindat,testdat,2 | ,10], [traindat,testdat,5,10]]
def kernel_anova_modular (train_fname=traindat,test_fname=testdat,cardinality=2, size_cache=10):
from modshogun import ANOVAKernel,RealFeatures,CSVFile
feats_train=RealFeatures(CSVFile(train_fname))
feats_test=Real | Features(CSVFile(test_fname))
kernel=ANOVAKernel(feats_train, feats_train, cardinality, size_cache)
km_train=kernel.get_kernel_matrix()
kernel.init(feats_train, feats_test)
km_test=kernel.get_kernel_matrix()
return km_train, km_test, kernel
if __name__=='__main__':
print('ANOVA')
kernel_anova_modular(*paramet... |
from math import sqrt
def main():
n = int(input("Enter n : "))
boolArr = [True for i in range(n + 1)]
boolArr[0] = boolArr[1] = False
for i in range(2, int(sqrt(n) + 1)):
if boolArr[i] is True:
for j in range(i * i, n + 1, i):
# print(boolArr)
boo | lArr[j] = False
for i in range(2, n + 1):
if boolArr[i] is True:
print(i)
if __name__ = | = '__main__':
main()
|
# 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... | t_scales[0] = scale
self.outputs = {
'Out': np.round(self.inputs['X'] / scale * (
(1 << (self.attrs['bit_length'] - 1)) - 1)),
'OutScale': scale,
'OutScales': out_scales,
}
def test_check_output(self):
self.check_output()
class TestFakeQ... | rage_abs_max"
self.attrs = {
'bit_length': int(5),
'moving_rate': float(0.9),
'is_test': False
}
accum = np.zeros(1).astype("float32")
accum[0] = 1
state = np.zeros(1).astype("float32")
state[0] = 1
scale = np.zeros(1).astype("f... |
# vkapi.py
#
# Copyright 2016 Igor Unixoid Kolonchenko <enepunixoid@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; either version 2 of the License, or
# (at your option) ... | ied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this pr | ogram; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import requests
import sys
class vkapi(object):
redirect_url = ''
scope = 0 '''Разрешение прав доступа'''
access_token = ''
client_id =
"""
https://oauth.vk.com/authorize?
... |
from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb
class User(User):
"""
Universal user model. Can be used with App Engine's default users API,
own auth or third party authentication methods (OpenID, OAuth etc).
based on https://gist.github.com/kylefinley
""... | . Only set for own authentication.
# Not required beca | use third party authentication
# doesn't use password.
password = ndb.StringProperty()
#: User Country
country = ndb.StringProperty()
#: User TimeZone
tz = ndb.StringProperty()
#: Account activation verifies email
activated = ndb.BooleanProperty(default=False)
@classmethod
d... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLE | ARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program 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.
#
# This... | 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################... |
1033915679"\
"83989576556519317788300024161353956243777784080174881937309502"\
"69990089089932808839743036773659552489130015663329407790713961"\
"46453408879151030065132193448667324827590794680787981942501958"\
"6223203951312520141099605312606965554042486705499867... | "14293083128576125448194444947324481909379536900820638463167822"\
"06480953181040657025432760438570350592281891987806586541218429"\
"21727372095510324225107971807783304260908679427342895573555925"\
"72380551144043800123904168771644518022649168164192740110645162"\
... | 54795968466980429801736257040673"\
"28212996215368488140410219446342464622074557564396045298531307"\
"40908460849965376780379320189914086581466217531933766597011433"\
"60862500982956691763884605676297293146491149370462446935198403"\
"534449135141193667933301936617... |
#!/usr/bin/env python
'''
OWASP ZSC
https://www.owasp.org/inde | x.php/OWASP_ZSC_Tool_Project
https://github.com/zscproject/OWASP-ZSC
http://api.z3r0d4y.com/
https://groups.google.com/d/forum/owasp-zsc [ owasp-zsc[at]googlegroups[dot]com ]
'''
from core i | mport stack
def create_file(create_command):
return '''
xor %ecx,%ecx
mov %fs:0x30(%ecx),%eax
mov 0xc(%eax),%eax
mov 0x14(%eax),%esi
lods %ds:(%esi),%eax
xchg %eax,%esi
lods %ds:(%esi),%eax
mov 0x10(%eax),%ebx
mov 0x3c(%ebx),%edx
add %ebx,%edx
mov 0x78(%edx),%edx
add %ebx,%edx
mov... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.