prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 t... | Y = verbosity
def write_message(msg, stream=sys.stdout, verbose=1):
"""Write message and flush output stream (may be sys.stdout or sys.stderr).
Useful | for debugging stuff."""
if VERBOSITY is None:
return bibtask_write_message(msg, stream, verbose)
elif msg and VERBOSITY >= verbose:
if VERBOSITY > 8:
print(datetime.now().strftime('[%H:%M:%S] '), end=' ', file=stream)
print(msg, file=stream)
|
# SPDX-License-Identifier: AGPL-3.0-or-later
# lint: pylint
"""Google (Scholar)
For detailed description of the *REST-full* API see: `Query Parameter
Definitions`_.
.. _Query Parameter Definitions:
https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
"""
# pylint: dis... | mis | sing-function-docstring
from urllib.parse import urlencode
from datetime import datetime
from lxml import html
from searx import logger
from searx.utils import (
eval_xpath,
eval_xpath_list,
extract_text,
)
from searx.engines.google import (
get_lang_info,
time_range_dict,
detect_google_sorry... |
import unittest
from aquarius.Aquarius import Aquarius
class ConsoleTestBase(unittest.TestCase):
def initialise_app_mock(self):
self.app = Aquarius(None, None, None)
|
def assert_c | alled(self, method):
self.assertTrue(method.called) |
+x foo.py. (2) scp it over to the /home/pi/ros_catkin_ws/build/opt/ros/kinetic/share/rosbots_driver. (3) from remote machine 'rosrun rosbots_driver foo.py'")
def push_test_ros_script(path_fn=None):
if path_fn == None:
_fp("\nERROR\nPlease specify local ROS script name")
_fp("$ fab push_test_ros_scr... | fi_reg_domain)
ssid_name = _get_input("What is the SSID?", force_need_query=True)
_fp(ssid_name)
if sudo("grep 'ssid=\"" + ssid_name + "\"' " + supplicant_fn, \
warn_only=True).succeeded:
_fp("This SSID is already set up")
else:
wpa_pwd = _get_input("What is the WPA pwd?", f... | force_need_query=True)
_fp(name)
_fp("Adding the network you specified into " + supplicant_fn)
network_config = "country=" + wifi_reg_domain + "\n" + \
"\n\n" + \
"network={\n" + \
" ssid=\"" + ssid_name + "\"\n" + \... |
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will b... | eturn (n, ns[1])
def isqref(object):
"""
Get whether the object is a I{qualified reference}.
@param object: An object to be tested.
@type object: I{ | any}
@rtype: boolean
@see: L{qualify}
"""
return (\
isinstance(object, tuple) and \
len(object) == 2 and \
isinstance(object[0], basestring) and \
isinstance(object[1], basestring))
class Filter:
def __init__(self, inclusive=False, *items):
self.inclusive = ... |
def forwards(self, orm):
# Adding model 'Contact'
db.create_table('storybase_user_contact', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('storybase.fields.ShortTextField')(blank=True)),
('info', self.gf('djan... | blank': 'True'}),
'owner': ('django.db. | models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'datasets'", 'null': 'True', 'to': "orm['auth.User']"}),
'published': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'source': ('django.db.models.fields.TextField', [], {'blank': 'True'})... |
#!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat | num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
| if os.name == "nt":
sep = "\\"
else:
sep = '/'
def main():
if len(sys.argv)<2:
usage()
return
if sys.argv[1]=='-s' and len(sys.argv) >= 4:
try:
send()
except KeyboardInterrupt:
printError("\nAbort")
elif sys.argv[1]=='-r':
try:
recieve()
except KeyboardInterrupt:
printError("\nAbort")
els... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core.platform import profiler
from telemetry.core import util
from telemetry.internal.backends.chrome import andr... | roid_browser_finder.CanFindAvailableBrowsers()
return browser_type.startswith('android')
def CollectProfile(self):
self._recorder.communicate(input='\n')
print 'Screen recording saved as %s' % self._output_path
print 'To view, open in Chrome or a video player'
retur | n [self._output_path]
|
# Copyright (C) 2020 Red Hat, Inc., Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/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 Gen... | e.
#
# See the LICENSE file in the source distribution for further information.
from sos.policies.init_systems import InitSystem
from sos.utilities import shell_out
class SystemdInit(InitSystem):
"""InitSystem abstraction for SystemD systems"""
def __init__(self):
super(SystemdInit, self).__init__(
... | ervices()
def parse_query(self, output):
for line in output.splitlines():
if line.strip().startswith('Active:'):
return line.split()[1]
return 'unknown'
def load_all_services(self):
svcs = shell_out(self.list_cmd).splitlines()[1:]
for line in svcs:
... |
# coding: utf-8
from app.settings.dist import *
try:
from app.settings.local import *
except ImportError:
pass
from app.settings.messages import *
from ap | p.settings.dist import INSTALLED_APPS
DEBUG = True
DEV_SERVER = True
USER_FILES_LIMIT = 1.2 * 1024 * 1024
SEND_MESSAGES = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', |
'NAME': '_test.sqlite',
},
}
INSTALLED_APPS = list(INSTALLED_APPS)
removable = ['south', ]
for app in removable:
if app in INSTALLED_APPS:
INSTALLED_APPS.remove(app)
TEST_DATABASE_NAME = DATABASES['default']['NAME'] if \
DATABASES['default']['NAME'].startswith('test_') else \
'test_' ... |
"""
Shopify Trois
---------------
Shopify API for Python 3
"""
from setuptools import setup
setup(
name='shopify-trois',
version= | '1.1-dev',
url='http://masom.github.io/shopify-trois',
license='MIT',
author='Martin Samson',
author_email='pyrolian@gmail.com',
maintainer='Martin Samson',
maintainer_email='pyrolian@g | mail.com',
description='Shopify API for Python 3',
long_description=__doc__,
packages=[
'shopify_trois', 'shopify_trois.models', 'shopify_trois.engines',
'shopify_trois.engines.http'
],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
... |
class node:
def __init__(self):
self.outputs=[]
def set(self):
for out in self.outputs:
out.set()
def clear(self):
for out in self.outputs:
out.clear()
class switch:
def __init__(self):
self.outputs=[]
self.state=False
self.inp | ut=False
def set(self):
self.input=True
if(self.state):
for out in self.outputs:
out.set()
def clear(self):
self.input=False
for out in self.outputs:
out.clear()
def open(self):
self.state=False
for out in self.outputs:
out.clear()
|
def close(self):
self.input=True
if(self.input):
for out in self.outputs:
out.set()
class light:
def __init__(self):
self.outputs=[]
def set(self):
print('light set')
for out in self.outputs:
out.set()
def clear(self):
print('light cleared')
for out in self.outputs:
out.clear()
i... |
000000)
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
else:
microseconds = int(microseconds)
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 24*3600)
d += days
... | return s
def total_seconds(self): |
"""Total seconds in the duration."""
return ((self.days * 86400 + self.seconds) * 10**6 +
self.microseconds) / 10**6
# Read-only field accessors
@property
def days(self):
"""days"""
return self._days
@property
def seconds(self):
"""seconds""... |
from math import sqrt
def is_prime(x):
for i in xrange(2, int(sq | rt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLIO... | = 1
print ans
|
mponents.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT component, using paho-mqtt.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/
"""
import json
import logging
import os
import socket
import time
from homeassistant.exceptions import HomeAssistantErro... | mqttc.user_data_set(self.userdata)
if username is not None:
self._mqttc.username_pw_set(username, password)
if certificate is not None:
self._mqttc.tls_set(certificate)
| self._mqttc.on_subscribe = _mqtt_on_subscribe
self._mqttc.on_unsubscribe = _mqtt_on_unsubscribe
self._mqttc.on_connect = _mqtt_on_connect
self._mqttc.on_disconnect = _mqtt_on_disconnect
self._mqttc.on_message = _mqtt_on_message
self._mqttc.connect(broker, port, keepalive... |
"" | "
Empt | y
"""
|
from __future__ import absolute_import
from celery import shared_task
import praw
from .commonTasks import *
from .models import Redditor, RedditorStatus, Status
@shared_task
def test(pa | ram):
return 'The test task executed with argument "%s" ' % param
@shared_task
def update_user(redditor):
update_user_status(redditor, 10)
get_submissions(redditor)
update_u | ser_status(redditor, 20)
get_comments(redditor)
update_user_status(redditor, 30)
@shared_task
def write_user(user):
create_user(user)
|
"""
WSGI config for spendrbackend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
http | s://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spendrbackend.settings")
application = get_wsgi_applica | tion()
|
import os
import sys
path = os. | path.dirname(os.pa | th.dirname(os.path.realpath(__file__)))
sys.path.insert(0, path)
|
# Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http | ://www.gnu.org/licenses/gpl-3.0.html
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
from .details_table import DetailsModel
class DetailsDialog(QDialog):
def __init__(self, parent, | app, **kwargs):
super().__init__(parent, Qt.Tool, **kwargs)
self.app = app
self.model = app.model.details_panel
self._setupUi()
# To avoid saving uninitialized geometry on appWillSavePrefs, we track whether our dialog
# has been shown. If it has, we know that our geometry... |
#!/usr/bin/env python
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
call_command(
'dumpdata',
"waffle.flag",
inde | nt=4,
| use_natural_foreign_keys=True,
use_natural_primary_keys=True,
output='base/fixtures/waffle_flags.json'
)
|
'''
Copyright 2017, Fujitsu Network Communications, Inc.
License | d 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 the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
|
from pprint import pprint
from amazon_cf import Environment
from amazon_client import Cloudformation
from helper import (
Listener,
SecurityGroupRules,
UserPolicy,
get_my_ip,
get_local_variables,
convert_to_aws_list,
ContainerDefinition
)
if __name__ == "__main__":
# Manually created it... | _ip=my_ip)
in_rules.add_rule("tcp", from_port=443, to_port=443, cidr_ip="0.0.0.0/0",)
in_rules.add_rule("tcp", from_port=80, to_port=80, cidr_ip="0.0.0.0/0",)
out_rules = SecurityGroupRules("SecurityGroupEgress")
out_rules.add_rule("-1", cidr_ip="0.0.0.0/0")
my_env.add_security_group(
"My se... | out_rules.rules)
docker_user = UserPolicy("docker")
docker_user.add_statement([
"ecr:*",
"ecs:CreateCluster",
"ecs:DeregisterContainerInstance",
"ecs:DiscoverPollEndpoint",
"ecs:Poll",
"ecs:RegisterContainerInstance",
"ecs:StartTelemetrySession",
"... |
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from finance.models import Payment
from .models import BookingVehi | cle
@receiver([post_save, post_delete], sender=Payment)
def update_booking_payment_info(sender, instance, **kwargs):
if instance.item_content_type.app_label == 'opencabs' and \
instance.item_content_type.model == 'booking':
if instance.item_object:
i | nstance.item_object.save()
@receiver([post_save, post_delete], sender=BookingVehicle)
def update_booking_drivers(sender, instance, **kwargs):
instance.booking.update_drivers()
|
# -*- coding: utf-8 - | *-
# Copyright (c) 2018, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.d | ocument import Document
class QualityMeeting(Document):
pass |
ne, 'provider_auth': None,
'display_name': 'vol-test02', 'instance_uuid': None,
'attach_status': 'detached',
'volume_type': [],
'_name_id': None, 'volume_metadata': []}
test_volume5 = {'migration_status': None, 'availability_zone': 'no... | ', snapName)
def SNAP_DELETE_CMD(self, name):
return ('snap', '-destroy', '-id', name, '-o')
def SNAP_CREATE_CMD(self, name):
return ('snap', '-create', '-res', 1, '-name', name,
'-allowReadWrite', 'yes',
'-allowAutoDelete', 'no')
def LUN_DELETE_CMD(self, n... | :
return ('lun', '-destroy', '-name', name, '-forceDetach', '-o')
def LUN_CREATE_CMD(self, name, isthin=False):
return ('lun', '-create', '-type', 'Thin' if isthin else 'NonThin',
'-capacity', 1, '-sq', 'gb', '-poolName',
'unit_test_pool', '-name', name)
def LUN... |
wly negotiated encryption parameters for outbound traffic"
m = Message()
m.add_byte(chr(MSG_NEWKEYS))
self._send_message(m)
block_size = self._cipher_info[self.local_cipher]['block-size']
if self.server_mode:
IV_out = self._compute_key('B', block_size)
key... | not None):
origin_addr = m.get_string()
origin_port = m.get_int()
self._log(DEBUG, 'Incoming x11 connection from %s:%d' % (origin_addr, origin_port))
self.lock.acquire()
try:
my_chanid = self._next_channel()
finally:
| self.lock.release()
elif (kind == 'forwarded-tcpip') and (self._tcp_handler is not None):
server_addr = m.get_string()
server_port = m.get_int()
origin_addr = m.get_string()
origin_port = m.get_int()
self._log(DEBUG, 'Incoming tcp forwarded ... |
'''
Audio
=====
The :class:`Audio` is used for recording audio.
Default path for recording is set in platform implementation.
.. note::
On Android the `RECORD_AUDIO`, `WAKE_LOCK` permissions are needed.
Simple Examples
---------------
To get the file path::
>>> audio.file_path
'/sdcard/testrecorde... | ay(self):
'''
Play current recording.
'''
self._play()
self.state = 'playing'
@property
def file_path(self):
return self._file_path
@file_path.setter
def file_path(self, location):
'''
Location of the recording.
'''
assert... | nce(location, (basestring, unicode)), \
'Location must be string or unicode'
self._file_path = location
# private
def _start(self):
raise NotImplementedError()
def _stop(self):
raise NotImplementedError()
def _play(self):
raise NotImplementedError()
|
x = "12345"
print(x[2])
""")
# Simple negative index
self.assertCodeExecution("""
x = "12345"
print(x[-2])
""")
# Positive index out of range
self.assertCodeExecution("""
x = "12345"
print(x[10])
... | s BinaryStrOperationTests(BinaryOperationTestCase, TranspileTestCase):
data_type = 'st | r'
not_implemented = [
'test_add_class',
'test_add_frozenset',
'test_and_class',
'test_and_frozenset',
'test_eq_class',
'test_eq_frozenset',
'test_floor_divide_class',
'test_floor_divide_complex',
'test_floor_divide_frozenset',
'te... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... |
At this level pyglet | does not try to interpret *what* a particular device is,
merely what controls it provides. A `Control` can be either a button, whose
value is either ``True`` or ``False``, or a relative or absolute-valued axis,
whose value is a float. Sometimes the name of a control can be provided (for
example, ``x``, representing t... |
#! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes the test cases from the answers/question_name file
and executes each test case. The output of each execution
will be compared and the program outp | uts a binary string.
Eg : 1110111 means out of 7 test cases 4th failed and rest
all passed.
Resource/Time limit errors will be produced from docker container'''
#opening and parsing test cases
with open ("answer") as file: # change after develo | pment finishes
cases=file.readlines();
cases = [x.strip() for x in cases]
cases = [ast.literal_eval(x) for x in cases]
s="" #return string
number_of_cases = len(cases)/2
for i in range(number_of_cases):
if type(cases[i]) is tuple:
if cases[number_of_cases+i] == solution.answer(*cases):
s+=... |
pp, client):
"""A POST to /upload of public and internal files fails with 403 if the
user only has permission to upload public files."""
batch = mkbatch()
batch['files']['two'] = {
'algorithm': 'sha512',
'size': len(TWO),
'digest': TWO_DIGEST,
'visibility': 'internal',
... | t_upload_batch_success_fresh(client, app):
"""A POST to /upload with a good batch succeeds, returns signed URLs expiring
in one hour, and inserts the new batch into the DB with links to files, but
no instances, and inserts a pending upload row."""
batch = mkbatch()
with set_time():
with not_... | esp = upload_batch(client, batch)
result = assert_batch_response(resp, files={
'one': {'algorithm': 'sha512',
'size': len(ONE),
'digest': ONE_DIGEST}})
assert_signed_url(result['files']['one']['put_url'], ONE_DIGEST,
method='P... |
ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"recommonmark",
]
# autodoc/autosummary flags
autocla... | 843
"ref.python"
]
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' 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 tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, ... |
import re
import numpy as np
from scipy import special
from .common import with_attributes, safe_import
with safe_import():
from scipy.special import cython_special
FUNC_ARGS = {
'airy_d': (1,),
'airy_D': (1,),
'beta_dd': (0.25, 0.75),
'erf_d': (1,),
'erf_D': (1+1j,),
'exprel_d': (1e-6,)... | e, bases, dct):
params = [(10, 100, 1000), ('python', 'numpy', 'cython')]
param_names = ['N', 'api']
def get_time_func(name, args):
@with_attributes(params=[(name,), (args,)] + params,
param_ | names=['name', 'argument'] + param_names)
def func(self, name, args, N, api):
if api == 'python':
self.py_func(N, *args)
elif api == 'numpy':
self.np_func(*self.obj)
else:
self.cy_func(N, *args)
... |
# -*- coding: utf-8 -*-
# This exploit template was generated via | :
# $ pwn template ./vuln
from pwn import *
# Set up pwntools for the correct architecture
exe = context.binary = ELF('./vuln')
def start(argv=[], *a, **kw):
'''Start the exploit against the target.'''
if args.GDB:
return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
e | lse:
return process([exe.path] + argv, *a, **kw)
gdbscript = '''
break *0x{exe.symbols.main:x}
continue
'''.format(**locals())
io = start()
payload = cyclic(76)
#payload = 'A'*64
payload += p32(0x80485e6)
io.sendline(payload)
io.interactive()
|
"""Request/Response Schemas are defined here"""
# pylint: disable=invalid-name
from marshmallow import Schema, fields, validate
from todo.constants import TO_DO, IN_PROGRESS, DONE
class TaskSchema(Schema):
"""Schema for serializing an instance of Task"""
id = fields.Int(required=True)
title = fields.Str... | N_PROGRESS, DONE],
error="Status must be one of {choices} (given: {input})"))
number = fields.Int(required=True)
created_at = fields.DateTime(required=True)
updated_at = fields.DateTime(required=True)
class BoardSchema(Schema):
"""Schema for serializing an instance of Board"""
id = fie... | me = fields.Str(required=True)
created_at = fields.DateTime(required=True)
updated_at = fields.DateTime(required=True)
class BoardDetailsSchema(BoardSchema):
"""Schema for serializing an instance of Board and its tasks"""
tasks = fields.Nested(TaskSchema, many=True)
|
import asyncio
import discord
from discord.ext import commands
from cogs.utils import checks
from cogs.utils.storage import RedisDict
class TemporaryVoice:
"""A cog to create TeamSpeak-like voice channels."""
def __init__(self, liara):
self.liara = liara
self.config = RedisDict('pandentia.te... | def filter(self, channels):
_channels = []
for channel in channels:
if channel.name.startswith('Temp: ') or channel.id in self.tracked_channels:
_channels.append(channel)
return _channels
async def create_channel(self, member: discord.Member):
guild = mem... | guild.default_role: discord.PermissionOverwrite(connect=False),
member: discord.PermissionOverwrite(connect=True, manage_channels=True, manage_roles=True)
}
channel = await guild.create_voice_channel(('Temp: {}\'s Channel'.format(member.name))[0:32],
... |
imp | ort brickpi3
Z | Z
|
#!/usr/bin/env python
"""
Cop | yright 2014 Jirafe, 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 to in writin... | he License for the specific language governing permissions and
limitations under the License.
"""
class Category:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'str',
... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestGeneratorsGeometric():
def test_random_geometric_graph(self):
G=nx.random_geometric_graph(50,0.25)
assert_equal(len(G),50)
def test_geographical_threshold_graph(sel | f):
G=nx.geographical_threshold_graph(50,100)
assert_equal(len(G),50)
def test_waxman_graph(self):
G=nx.waxman_graph(50,0.5,0.1)
assert_equal(len(G),50)
G=nx.waxman_graph(50,0.5,0.1,L=1)
assert_equal(len(G),50)
def test_naviable_small_world(self):
... | gg = nx.grid_2d_graph(5,5).to_directed()
assert_true(nx.is_isomorphic(G,gg))
G = nx.navigable_small_world_graph(5,p=1,q=0,dim=3)
gg = nx.grid_graph([5,5,5]).to_directed()
assert_true(nx.is_isomorphic(G,gg))
G = nx.navigable_small_world_graph(5,p=1,q=0,dim=1)
gg = nx... |
fault_obj.instance_uuid = instance.uuid
fault_obj.update(exception_to_dict(fault, message=fault_message))
code = fault_obj.code
fault_obj.details = _get_fault_details(exc_info, code)
fault_obj.create()
def get_device_name_for_instance(instance, bdms, device):
"""Validates (or generates) a device... | age_ref']
def heal_reqspec_is_bfv(ctxt, request_spec, instance):
"""Calculates the is_bfv flag for a RequestSpec created before Rocky.
Starting in Rocky, new instances have their RequestSpec created with
the "is_bfv" flag to indicate if they are volume-backed which is used
by the scheduler when deter... | t: nova.context.RequestContext auth context
:param request_spec: nova.objects.RequestSpec used for scheduling
:param instance: nova.objects.Instance being scheduled
"""
if 'is_bfv' in request_spec:
return
# Determine if this is a volume-backed instance and set the field
# in the request ... |
NOER | ROR = 0
NOCONTEXT = -1
NODISPLAY = -2
NOWINDOW = -3
NOGRAPHICS = -4
NOTTOP = -5
NOVISUAL = -6
BUFSIZE = -7
BADWINDOW = -8
ALREADYBOUND = -100
BINDFAILED = -101
SETFAILED = -1 | 02
|
#!/usr/bin/python
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Python sample demonstrating use of the Google Genomics Pipelines API.
This sample demonstrates a pipe... | credentials=credentials)
# Run the pipeline.
operation = service.pipelines().run(body={
# The ephemeralPipeline provides the template for the pipeline.
# The pipelineArgs provide the inputs specific to this run.
'ephemeralPipeline' : {
'projectId': PROJECT_ID,
' | name': 'Bioconductor: count overlaps in a BAM',
'description': 'This sample demonstrates a subset of the vignette https://bioconductor.org/packages/release/bioc/vignettes/BiocParallel/inst/doc/Introduction_To_BiocParallel.pdf.',
# Define the resources needed for this pipeline.
'resources' : {
# Speci... |
"strides": [[-2], [-1], [1], [2]],
"begin_mask": [0, 1],
"end_mask": [0, 1],
"shrink_axis_mask": [0],
"constant_indices": [False],
},
]
_make_strided_slice_tests(options, test_parameters)
# For verifying https://github.com/tensorflow/tensorflow/issues/23599
# TOD... | cells"]
inputs_after_split = []
for i in xrange(time_step_size):
one_timestamp_input = tf.placeholder(
dtype=parameters["dtype"],
name="split | _{}".format(i),
shape=[num_batchs, input_vec_size])
inputs_after_split.append(one_timestamp_input)
# Currently lstm identifier has a few limitations: only supports
# forget_bias == 0, inner state activation == tanh.
# TODO(zhixianyan): Add another test with forget_bias == 1.
# TODO(zhixi... |
n-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical produ... | mediu | m customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of ... |
he License for the specific language governing permissions and
# limitations under the License.
from unittest import mock
import oslo_messaging
import six
import testtools
from sahara import conductor as cond
from sahara import context
from sahara import exceptions as exc
from sahara.plugins import base as pl_base
f... | er):
pass
def get_description(self):
return "Some description"
def get_title(self):
return "Fake plugin"
def validate(sel | f, cluster):
self.calls_order.append('validate')
def get_open_ports(self, node_group):
self.calls_order.append('get_open_ports')
def validate_scaling(self, cluster, to_be_enlarged, additional):
self.calls_order.append('validate_scaling')
def get_versions(self):
return ['0.... |
from cinder.excepti | on import *
from cinder.i18n import _
class ProviderMultiVolumeError(CinderException):
msg_fmt = _("volume %(volume_id)s More than one provider_volume are found")
class ProviderMultiSnapshotError(CinderException):
msg_fmt = _("snapshot % | (snapshot_id)s More than one provider_snapshot are found")
class ProviderCreateVolumeError(CinderException):
msg_fmt = _("volume %(volume_id)s create request failed,network or provider internal error")
class ProviderCreateSnapshotError(CinderException):
msg_fmt = _("snapshot %(snapshot_id)s create request fai... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow_serving/config/platform_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.pr... | PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY.fields_by_name['value'].message_type = _PLATFORMCONFIG
_PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY. | containing_type = _PLATFORMCONFIGMAP
_PLATFORMCONFIGMAP.fields_by_name['platform_configs'].message_type = _PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY
DESCRIPTOR.message_types_by_name['PlatformConfig'] = _PLATFORMCONFIG
DESCRIPTOR.message_types_by_name['PlatformConfigMap'] = _PLATFORMCONFIGMAP
_sym_db.RegisterFileDescriptor... |
from django. | conf.urls import url
from DjangoTaskManager.task import views
urlpatterns = [
url(r'^$', views.all_tasks, name='all_tasks'),
url(r'^add/$', views.add, name='task_add'),
url(r'^mark-done/(?P<task_id>[\w+:-]+)/$',
views.mark_done, name='task_mark_done'),
url(r'^edit/(?P<task_id>[\w+:-]+)/$',
... | views.edit, name='task_edit'),
url(r'^delete/(?P<task_id>[\w+:-]+)/$',
views.delete, name='task_delete'),
url(r'^single/(?P<task_id>[\w+:-]+)/$',
views.single, name='single_task'),
]
|
class Node(object):
#a binary search tree has a left node (smaller values) and a right node (greater values)
def __init__(self, data):
self.data = data;
self.left_child = None;
self.right_child = None;
class BinarySearchTree(object):
def __init__(self):
self.root = None;
#inserting ite... |
node.right_child = Node(data);
#if the tree is balanced then it has O(logN) running time
def remove_node(self, data, node):
#base case for recursive function calls
if not node:
return node;
#first we have to find the node to remove
#left node -> containts smaller value
#right nod... | lif data > node.data:
node.right_child = self.remove_node(data, node.right_child);
#this is when we find the node we want to remove
else:
#the node is a leaf node: no children at all
if not node.left_child and not node.right_child:
print("Removing a leaf node...");
del node;
return... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>>... | data in json_data['messages']]
self.message_count = len(self.messages)
self.total_price = sum(msg.message_pr | ice for msg in self.messages)
self.remaining_balance = min(msg.remaining_balance for msg in self.messages)
class NexmoMessage(object):
"""A wrapper to manipulate a single `message` entry in a Nexmo response.
When a text messages is sent in several parts, Nexmo will return a status
for each and ev... |
#PROJECT
from outcome import Outcome
from odds import Odds
class Bin:
def __init__(
self,
*outcomes
):
self.outcomes = set([outcome for outcome in outcomes])
def add_outcome(
self,
outcome
):
self.outcomes.add(outcome)
def __str__(self):
re... | n([str(i) for i in bins])),
Odds.SPLIT_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def street_bets(self):
for row in range(12):
| n = 3 * row + 1
bins = [n, n + 1, n + 2]
outcome = Outcome(
'street {}-{}'.format(bins[0], bins[-1]),
Odds.STREET_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def corner_bets(self):
for col in ... |
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from djgeojson.views import GeoJSONLayerView
from wagtail.contrib.wagtailsitemaps.views import sitemap
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs import urls as wagtaildo... | iles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView, RedirectView
# Serve static and media files from development server
| urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Add views for testing 404 and 500 templates
urlpatterns += [
url(r'^test404/$', TemplateView.as_view(template_name='404.html')),
url(r'^test500/$', TemplateView.as_view(te... |
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#
# module_dumper.py - WIDS/WIPS framework file dumper module
# Copyright (C) 2009 Peter Krebs, Herbert Haas
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by the
# Fr... | s):
"""DumperClass
| Receives messages and dumps them into file.
"""
def __init__(self, controller_reference, parameter_dictionary, module_logger):
"""Constructor
"""
fw_modules.module_template.ModuleClass.__init__(self, controller=controller_reference, param_dict=parameter_dicti... |
exprs.update(hive_stats_collection_operator.get_default_exprs(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
m... | e=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
select_count_query = (
"SELECT COUNT(*) AS __count "
"FROM airflow.static_babynames_partitioned "
"WHERE ds = '2015-01-01';"
)
mock_presto_hook.get_first.assert_called_with(hql=select_count_query)
... | "FROM hive_stats "
"WHERE table_name='airf |
"""
raven.utils
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import hashlib
import hmac
import logging
try:
import pkg_resources
except ImportError:
pkg_resources = None
import sys
import raven
def construct_check... | version = None
else:
version = None
if isinstance(version, (list, tuple)):
version = '.'.join(str(o) for o in version)
_VERSION_CACHE[module_name] = version
else:
version = _VERSION_CACHE[module_name]
if ve... | s[module_name] = version
return versions
def get_signature(key, message, timestamp):
return hmac.new(key, '%s %s' % (timestamp, message), hashlib.sha1).hexdigest()
def get_auth_header(signature, timestamp, client):
return 'Sentry sentry_signature=%s, sentry_timestamp=%s, raven=%s' % (
signature,
... |
"""
Copyright 2017 Robin Verschueren
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, softw... | tions.complex2real.atom_canonicalizers.zero_canon import zero_canon
CANON_METHODS = {
AddExpression: separable_canon,
bmat: separable_canon,
cumsum: separable_canon,
diag: separable_canon,
Hstack: separable_canon,
index: separable_canon,
special_index: separable_canon,
Promote: separab... | n,
transpose: separable_canon,
NegExpression: separable_canon,
upper_tri: separable_canon,
Vstack: separable_canon,
conv: binary_canon,
DivExpression: binary_canon,
kron: binary_canon,
MulExpression: binary_canon,
multiply: binary_canon,
conj: conj_canon,
imag: imag_canon,
... |
#----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including ... | le, e))
else:
raise Exception("ABAC Credential not parsable: %s. Cred start: %s..." % (e, credString[:50]))
else:
raise Exception("Unknown credential type '%s'" % cred_type)
if __name__ == "__main__":
c2 = open('/tmp/sfa.xml').read()
cred1 = Crede... | red2
c1s = cred1.dump_string()
print "C1 = %s" % c1s
# print "C2 = %s" % cred2.dump_string()
|
# -*- python -*-
# Copyright (C) 2009-2017 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later versio... | THOUT ANY WARRANT | Y; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
impo... |
neoffset'], coll.get_lineoffset())
@cleanup
def test__EventCollection__get_linestyle():
'''
check to make sure the default linestyle matches the input linestyle
'''
_, coll, _ = generate_EventCollection_plot()
assert_equal(coll.get_linestyle(), [(None, None)])
@cleanup
def test__EventCollection_... | props['lineoffset'],
props[ | 'orientation'])
splt.set_title('EventCollection: append_positions')
splt.set_xlim(-1, 90)
@image_comparison(baseline_images=['EventCollection_plot__extend_positions'])
def test__EventCollection__extend_positions():
'''
check to make sure extend_positions works properly
'''
splt, coll, props = ... |
# Generated by Django 2.2.6 on 2019-10-23 09:06
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import olympia.amo.models
class Migration(migrations.Migration):
dependencies = [
('scanners', '0008_auto_20191021_1718'),
]
|
operations | = [
migrations.CreateModel(
name='ScannerMatch',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False)),
... |
RVICE_SEND_COMMAND = "send_command"
SERVICE_SET_FAN_SPEED = "set_fan_speed"
SERVICE_START_PAUSE = "start_pause"
SERVICE_START = "start"
SERVICE_PAUSE = "pause"
SERVICE_STOP = "stop"
STATE_CLEANING = "cleaning"
STATE_DOCKED = "docked"
STATE_RETURNING = "returning"
STATE_ERROR = "error"
STATES = [STATE_CLEANING, STATE... | if self.supported_features & SUPPORT_FAN_SPEED:
data[ATTR_FAN_SPEED] = self.fan_speed
return data
def stop(self, **kwargs):
"""Stop the vacuum cleaner."""
raise NotImplementedError()
async def async_stop(self, **kwargs):
"""Stop the vacuum cleaner.
This ... | the event loop.
"""
await self.hass.async_add_executor_job(partial(self.stop, **kwargs))
def return_to_base(self, **kwargs):
"""Set the vacuum cleaner to return to the dock."""
raise NotImplementedError()
async def async_return_to_base(self, **kwargs):
"""Set the vacuum... |
on,
wf_params, context,
delete=False,
lbaas_entity=None, entity_id=None):
"""Update the WF state. Push the result to a queue for processing."""
if not self.workflow_templates_exists:
self._verify_workflow_templates()... | e_workflow_params=None):
"""Create a WF if it doesn't exists yet."""
if not self.workflow_templates_exists:
self._verify_workflow_templates()
if not self._workflow_exists(wf_name):
if not create_workflow_params:
create_workflow_params = {}
... | response = _rest_wrapper(self.rest_client.call('POST',
resource,
params,
TEMPLATE_HEADER))
LOG.debug(_('create_workflow respons... |
'''longtroll: Notify you when your long-running processes finish.'''
import argparse
import getpass
import os
import pickle
import re
import subprocess
import time
collapse_whitespace_re = re.compile('[ \t][ \t]*')
def spawn_notify(notifier, proc_ended):
cmd = notifier.replace('<cmd>', proc_ended[0])
cmd = cmd.r... | ed[1]))
subprocess.Popen(cmd, shell=True)
def get_user_processes(user):
def line_to_dict(line):
line = re.sub(collapse_whitespace_re, ' ', line).strip()
time, pid, ppid, command = line.split(' ', 3)
try:
| return {
'age': etime_to_secs(time),
'pid': int(pid),
'ppid': int(ppid),
'command': command,
}
except Exception:
print('Caught exception for line: %s' % line)
raise
ps_out = subprocess.Popen(' '.join([
'ps', '-U %s' % user, '-o etime,pid,ppid,... |
"""
Decode all-call reply messages, with downlink format 11
"""
from pyModeS import common
def _checkdf(func):
"""Ensure downlink format is 11."""
def wrapper(msg):
df = common.df(msg)
if df != 11:
raise RuntimeError(
"Incorrect downlink format, expect 11, got {}"... | ode transponder code (ICAO address).
Args:
msg (str): 14 hexdigits string
Returns:
string: ICAO address
"""
return common.icao(msg)
@_checkdf
def interrogator(msg):
"""Decode interrogator identifier code.
Args:
msg (str): 14 hexdigits string
Returns:
int:... | s are CL field and last four bits are IC field.
remainder = common.crc(msg)
if remainder > 79:
IC = "corrupt IC"
elif remainder < 16:
IC="II"+str(remainder)
else:
IC="SI"+str(remainder-16)
return IC
@_checkdf
def capability(msg):
"""Decode transponder capability.
... |
= OPTIONAL or action.nargs is None:
return num_consumed_args == 0
assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
return num_consumed_args < action.nargs
def action_is_greedy(action, isoptional=False):
''' Returns True if action will necessarily ... | tions # Added by argcomplete
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen a | rguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_act... |
import wx
from ui.custom_checkbox import CustomCheckBox
class CustomMenuBar(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.SetBackgroundColour(self.parent.G | etBackgroundColour())
self.SetForegroundColour(self.parent.GetForegroundColour())
self.SetFont(self.parent.GetFont())
self.img_size = 12
self._dragPos = None
self.Bind(wx.EVT_MOTION, self.OnMouse)
gbSizer = wx.GridBagSizer()
self.txtTitle = wx.StaticText(self, wx... | DefaultPosition, wx.DefaultSize, 0)
gbSizer.Add(self.txtTitle, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5)
self.txtServer = wx.StaticText(self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0)
gbSizer.Add(self.txtServer, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_H... |
from urlparse import urlparse
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from cabot.cabotapp.models import Service
from cabot.metricsapp.models import MetricsSourceBase, ElasticsearchStatusCheck, GrafanaInstance, GrafanaPanel
class TestM... | icsearchStatusCheck.objects.get(pk=self.metrics_check.pk)
self.assertEqual(self.metrics_check.name, 'test')
# now accept the changes by manually setting skip_review to True (which should be done in the response)
# (would ideally do this by using a browser's normal submit routine on the response... | .
# we at least scan the HTML for the skip_review input to make sure it got set to True)
self.assertContains(response,
'<input id="skip_review" name="skip_review" type="checkbox" checked="checked" />',
status_code=200)
data['skip_review'] =... |
IX + s
# only add the prefix if the last stream ended with a newline.
self._can_prefix = s.endswith('\n')
# Make sure to call the super classes write method.
io.StringIO.write(self, s)
# When we are written to, we also write to the secondary stream.
self... | self.report({'ERROR'}, 'Unable to open script.')
return {'CANCELLED'}
# Setup the times dict to keep track of when all the files where last edited.
dirs, files = self.get_paths()
self._times = dict((path, os.stat(path).st_mtime) for path in files) # Where we store the ... | |
#!/usr/bin/env python3
# copyright (C) 2021- The University of Notre Dame
# Thi | s software is distributed under the GNU General Public License.
# See the file COPYING for details.
# Example on how to execute python code with a Work Queue task.
# The class PythonTask allows users to execute python functions as Work Queue
# commands. Functions and their arguments are pickled to a file and executed
... | read when neccesary
# allowing the user to get the result as a python variable during runtime and
# manipulated later.
# A PythonTask object is created as `p_task = PyTask.PyTask(func, args)` where
# `func` is the name of the function and args are the arguments needed to
# execute the function. PythonTask can be subm... |
e" % self.table_prefix)
self.failUnless(cur.rowcount in (-1,1),
'cursor.rowcount should == number of rows returned, or '
'set to -1 after executing a select statement'
)
self.executeDDL2(cur)
self.assertEqual(cur.rowcount,-1,
... | ieved')
finally:
con.close()
def test_fetchone(self):
con = self._connect()
try:
cur = con.cursor()
# cursor.fetchone should raise an Error if called before
# executing a select-type query
self.assertRa | ises(self.driver.Error,cur.fetchone)
# cursor.fetchone should raise an Error if called after
# executing a query that cannnot return rows
self.executeDDL1(cur)
self.assertRaises(self.driver.Error,cur.fetchone)
cur.execute('select name from %sbooze' % self.ta... |
# License AGP | L-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import test_ui | |
fro | m survey.management.commands.import_location import Command
__all__ = [''] | |
# -*- coding: utf-8 -*-
from mesa_pd.accessor import create_access
from mesa_pd.utility import generate_file
def create_property(name, type, defValue=""):
"""
Parameters
----------
name : str
name of the property
type : str
type of the property
defValue : str
default valu... | s="g"))
self.context['interface'].append(create_access("angularVelocity", "walberla::mesa_pd::Vec3", access="g")) |
self.context['interface'].append(create_access("invMass", "walberla::real_t", access="g"))
self.context['interface'].append(create_access("invInertia", "walberla::mesa_pd::Mat3", access="g"))
self.context['interface'].append(create_access("dv", "walberla::mesa_pd::Vec3", access="gr"))
s... |
#! /usr/bin/env python
""" Create files for shuf unit test """
import nmrglue.fileio.pipe as pipe
import nmrglue.process.pipe_proc as p
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="ri2c")
pipe.write("shuf1.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="c... | d, a, mode="rolr")
pipe.write("shuf5.glue", d, a, overwrite=True)
| d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="swap")
pipe.write("shuf6.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="inv")
pipe.write("shuf7.glue", d, a, overwrite=True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from core.base_processor import xBaseProcessor
from utilities.export_helper import xExportHelper
from util | ities.file_utility import xFileUtility
from definitions.constant_data import xConstantData
class xProcessorPhp(xBaseProcessor) :
def __init__(self, p_strSuffix, p_strConfig) :
return super(xProcessorPhp, self) | .__init__('PHP', p_strSuffix, p_strConfig)
def ProcessExport(self, p_strWorkbookName, p_cWorkbook, p_cWorkSheet, p_mapExportConfigs, p_mapDatabaseConfigs, p_mapIndexSheetConfigs, p_mapDataSheetConfigs, p_mapPreloadDataMaps, p_nCategoryLevel) :
print('>>>>> 正在处理 工作表 [{0}] => [{1}]'.format(p_mapIndexSheetConfigs['DAT... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain th... | rocess.Popen(args, stderr=subprocess.PIPE)
for line in proc.stderr:
print line,
interpret_warning(line)
result = proc.wait()
except OSError as e:
result = e.errno
if result == errno.ENOENT:
print args[0] + ':',e.strerror
print 'Is your... |
return result
if __name__ == '__main__':
status = run_gcc()
sys.exit(status)
|
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution. |
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www | .apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
# These licenses are valid for use in Servo
licenses = [
"""\
/* This Source Code Form is subject to t... |
from . import db
from .assoc import section_professor
class Professor(db.Model):
__tablename__ = 'professors'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), unique=True)
first_name = db.Column(db.Text, nullable=False)
last_name = db.Column... | dict(self):
return {
'id': self.id,
'first_name': self.first_name,
'last_name | ': self.last_name
}
|
esent
name: router1
network: ext_network1
external_fixed_ips:
- subnet: public-subnet
ip: 172.24.4.2
- subnet: ipv6-public-subnet
ip: 2001:db8::3
# Delete router1
- os_router:
cloud: mycloud
state: absent
name: router1
'''
RETURN = '''
router:
description: Dicti... | module.params)
router = cloud.get_router(name)
net = None
if network:
net = cloud.get_network(network)
if not net:
module.fail_json(msg='network %s not found' % network)
# Validate and cache the subnet IDs so we can avoid duplicate checks
... | stem_state_change(cloud, module, router, net, internal_ids)
)
if state == 'present':
changed = False
if not router:
kwargs = _build_kwargs(cloud, module, router, net)
router = cloud.create_router(**kwargs)
for internal_subnet_... |
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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
#
# htt... | split())
except SystemExit:
| exc_type, exc_value, exc_traceback = sys.exc_info()
self.assertIn(exc_value.code, exitcodes)
return (mock_stdout.getvalue(), mock_stderr.getvalue())
|
# -*- coding: utf-8 -*-
"""
Написать функцию is_prime, принимающую 1 аргумент: число от 0 до 1000.
Если число простое, то функция возвращает True, а в противном случае - False.
"""
prime_1000 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, ... | 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, ... | 7, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
def is_prime(num):
if type(num) is "int":
raise TypeError("argument is not integer")
if num <= 0 or num > 1000:
raise ValueError("argument value out of bounds")
if num % 2 == 0:
re... |
"""
Clone server Model Six
"""
import random
import time
import zmq
from clone import Clone
SUBTREE = "/client/"
def main():
# Create and connect clone
clone = Clone()
clone.subtree = SUBTREE
clone.connect("tcp://localhost", 5556)
clone.connect("tcp://localhost", 5566)
try:
while ... | y-value message
key = "%d" % random.randint(1,10000)
value = "%d" % random.randint(1,1000000)
clone.set(key, value, random.randint(0,30))
time.sleep(1)
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main() | |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from dja | ngo.db import models, migrations
class Migration(migrat | ions.Migration):
dependencies = [
('zeltlager_registration', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='jugendgruppe',
name='address',
),
migrations.DeleteModel(
name='Jugendgruppe',
),
migration... |
# Base class defines VM must be off after a save
self.monitor.cmd("system_reset")
self.verify_status('paused') # Throws exception if not
def restore_from_file(self, path):
"""
Override BaseVM restore_from_file method
"""
self.verify_status('paused') # Throw... | return None
def check_block_locked(self, value):
"""
Check whether specified block device is locked or not.
Return True, if device is locked, else False.
:param vm: VM object
:param value: Parameter that can specify block device.
Can be any pos... | e is unlocked.
"""
assert value, "Device identification not specified"
blocks_info = self.monitor.info("block")
assert value in str(blocks_info), \
"Device %s not listed in monitor's output" % value
if isinstance(blocks_info, str):
lock_str = "locked=1"... |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | $ {command} MY-RULE --target-tags
"""
parser.add_argument(
'name',
help='The name of the firewall rule to {0}'.format(
'update.' if for_update else 'create.'))
def ParseAllowed(allowed, message_classes):
"""Parses protocol:port mappings from --allow command line."""
allowed_va... | 'Firewall rules must be of the form {0}; received [{1}].'
.format(ALLOWED_METAVAR, spec))
if match.group('ports'):
ports = [match.group('ports')]
else:
ports = []
allowed_value_list.append(message_classes.Firewall.AllowedValueListEntry(
IPProtocol=match.group('protocol'),
... |
#!/usr/bin/env python3
import random
import numpy as np
import sympy
mod_space = 29
'''
Generate Encryption Key
'''
# In --> size of matrix (n x n)
# Out --> List of lists [[1,2,3],[4,5,6],[7,8,9]]
def generate_encryption_key(size):
determinant = 0
# Need to make sure encryption key is invertible, IE det(k... | x for | m)
# Out --> Decryption Key
def generate_decryption_key(encryption_key):
# Take the prod of these 2 vars
key_inv = np.linalg.inv(encryption_key) # Inverse of encryption key
# Determinant of encryption key
det_key = int(np.linalg.det(encryption_key))
#print((key_inv * (det_key) * modular_inverse... |
from django.forms import | ModelForm
from bug_reporting.models import Feedback
from CoralNet.forms import FormHelper
class FeedbackForm(ModelForm):
class Meta:
model = Feedback
fields = ('type', 'comment') # Other fields are auto-set
#error_css_class = ...
#required_css_class = ... |
def clean(self):
"""
1. Strip spaces from character fields.
2. Call the parent's clean() to finish up with the default behavior.
"""
data = FormHelper.stripSpacesFromFields(
self.cleaned_data, self.fields)
self.cleaned_data = data
return super... |
#!/usr/bin/env python
import os
import sys
if __ | name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mobilepolls.settings")
from django.core.management import execute_from_command_line
execu | te_from_command_line(sys.argv)
|
t
# * test on 64 bits XP + VS 2005 (and VS 6 if possible)
# * SDK
# * Assembly
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py bee7caf9defd6e108fc2998a2520ddb36a967691 2019-12-17 02:07:09 bdeegan"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import SCons.Util
i... | dio\10.0\Setup\VC\ProductDir'),
],
'10.0Exp' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'),
],
'9.0': [
(SCons.Util.HKEY_CURRENT_USER, r'Microsoft\DevDiv\VCForPython\9.0\installdir',),
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\Visu... | ns.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'),
],
'8.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'),
],
'8.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'),
],
... |
nput and initial state values for testing."""
np.random.seed(seed)
num_layers = self._rnn.num_layers
dir_count = self._rnn.num_dirs
num_units = self._rnn.num_units
input_size = self._rnn.input_size
np_dtype = np.float32 if self._dtype == dtypes.float32 else np.float64
inputs = np.random.ran... | m_ops.random_uniform([
num_layers * dir_count, bat | ch_size, num_units], dtype=dtypes.float32)
lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units,
direction=direction,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
... |
"updated": "2011-06-09T00:00:00+00:00"
},
{
"alias": "FAKE-2",
"description": "Fake extension number 2",
"links": [],
"name": "Fake2",
"namespace": ("http://docs.openstack.org/"
... |
{'transfers': [
_stub_transfer_full(transfer1, base_uri, tenant_id),
_stub_transfer_full(transfer2, base_uri, tenant_id)]})
def delete_os_volume_transfer_5678(self, **kw):
return (202, {}, None)
def post_os_volume_transfer(self, **kw):
b... | {'transfer': _stub_transfer(transfer1, base_uri, tenant_id)})
def post_os_volume_transfer_5678_accept(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
transfer1 = '5678'
return (200, {},
{'transfer': _stub_transfer(transf... |
from registrator.models.registration_entry import RegistrationEntry
from uni_info.models import Sect | ion
class RegistrationProxy(Registr | ationEntry):
"""
Proxy class which handles actually doing the registration in a system
of a :model:`registrator.RegistrationEntry`
"""
# I guess functions for registration in Concordia's system would go here?
def add_schedule_item(self, schedule_item):
section_list = schedule_item.sect... |
import argparse
import docker
import logging
import os
import docket
logger = logging.getLogger('docket')
logging.basicConfig()
parser = argparse.ArgumentParser(description='')
parser.add_argument('-t --tag', dest='tag', help='tag for final image')
parser.add_argument('--verbose', dest='verbose', action='store_true',... | ttps:')
tls_config = None
if cert_path:
tls_config = docker.tls.TLSConfig(verify=tls_verify,
client_cert=(os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem')),
ca_cert=os.path.join(cert_path, 'ca.pem')
)
client = docker.Client(base_url=base_url, version='1.15', timeout=10, ... | ls_config)
tag = args.tag or None
buildpath = args.buildpath[0]
def main():
docket.build(client=client, tag=tag, buildpath=buildpath, no_cache=args.no_cache)
exit()
if __name__ == '__main__':
main()
|
"""
Utilities for validating inputs to user-facing API functions.
"""
from textwrap import dedent
from types import CodeType
from functools import wraps
from inspect import getargspec
from uuid import uuid4
from toolz.curried.operator import getitem
from six import viewkeys, exec_, PY3
_code_argorder = (
('co_ar... | raise TypeError(
"Can't validate functions using tuple unpacking: %s" %
(argspec,)
)
# Ensure | that all processors map to valid names.
bad_names = viewkeys(processors) - argset
if bad_names:
raise TypeError(
"Got processors for unknown arguments: %s." % bad_names
)
return _build_preprocessed_function(
f, processors, args_defaults, varar... |
ticLine', ['control','tool'],
['pos', 'size'], image=images.TreeStaticLine.GetImage())
c.addStyles('wxLI_HORIZONTAL', 'wxLI_VERTICAL')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'line', 'wxStaticLine', 20)
component.Manager.setTool(c, 'Controls', pos=(0,3))
### wxStaticBitmap
... | 'wxTR_ROW_LINES',
'wxTR_HAS_VARIABLE_ROW_HEIGHT',
'wxTR_SINGLE',
'wxTR_MULTIPLE',
'wxTR_EXTENDED',
'wxTR | _DEFAULT_STYLE')
c.addEvents('EVT_TREE_BEGIN_DRAG',
'EVT_TREE_BEGIN_RDRAG',
'EVT_TREE_BEGIN_LABEL_EDIT',
'EVT_TREE_END_LABEL_EDIT',
'EVT_TREE_DELETE_ITEM',
'EVT_TREE_GET_INFO',
'EVT_TREE_SET_INFO',
'EVT_TREE_ITEM_EXPANDED',
... |
# Copyright (C) 2009-2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman | 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.
#
# GNU Mailman is | distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman. ... |
#
# Copyright 2007-2009 Fedora Unity Project (http://fedoraunity.org)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2, or (at your option) any
# later version.
#
# This program is di... | SE. See the
# GNU Library Gen | eral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
__license__ = "GNU GPLv2+"
__version__ = "Git Development Hacking"
|
"""
Tests for functionality in openedx/core/lib/courses.py.
"""
import ddt
from django.test.utils import override_settings
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from ..course... | """ Verify that non-ascii image names are cleaned """
course_image = u'before_\N{SNOWMAN}_after.jpg'
course = CourseFactory.create(course_image=course_image)
self.verify_url(
unicode(course.id.make_asset_key('asset', course_image.replace(u'\N{SNOWMAN}', '_'))),
course_... | paces_in_image_name(self):
""" Verify that image names with spaces in them are cleaned """
course_image = u'before after.jpg'
course = CourseFactory.create(course_image=u'before after.jpg')
self.verify_url(
unicode(course.id.make_asset_key('asset', course_image.replace(" ", "... |
sa_oaep_md (< 1.0.2)"
)
def test_unsupported_mgf1_hash_algorithm_decrypt(self):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
... | curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
builder = x509.CertificateRevocationListBuilder()
| builder = builder.issuer_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).last_update(
datetime.datetime(2002, 1, 1, 12, 1)
).next_update(
datetime.datetime(2032, 1, 1, 12, 1)
)
with pytest.raises(NotImplementedErr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.