prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
"""add unique key to username
Revision ID: c19852e4dcda
Revises: 1478867a872a
Create Date: 2020-08-06 00:39:03.004053
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c19852e4dcda'
down_revision = '1478867a872a'
branch_labels = None
depends_on = None
def upgr... | r', schema=None) as batch_op:
batch_op.drop_index('ix_user_username')
batch_op.create_index(batch_op.f('ix_user_username'), ['username'], unique=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('u... | ique=False)
# ### end Alembic commands ###
|
#!/bin/env python
# Copyright 2013 Zynga In | c.
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOU... |
"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.Sessi... | e',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | common.policy')
CONF.import_opt('compute_driver', 'nova.virt.driver')
CONF.import_opt('api_paste_config', 'nova.wsgi')
class ConfFixture(config_fixture.Config):
"""Fixture to manage global conf settings."""
def setUp(self):
super(ConfFixture, self).setUp()
self.conf.set_default('api_pas | te_config',
paths.state_path_def('etc/nova/api-paste.ini'))
self.conf.set_default('host', 'fake-mini')
self.conf.set_default('compute_driver',
'nova.virt.fake.SmallFakeDriver')
self.conf.set_default('fake_network', True)
self.co... |
ight (c) 2010-2011 Joshua Harlan Lifton.
# See LICENSE.txt for details.
# TODO: add tests for all machines
# TODO: add tests for new status callbacks
"""Base classes for machine types. Do not use directly."""
import binascii
import threading
import serial
from plover import _, log
from plover.machine.keymap import... | l parameters.
SERIAL_PARAMS = {
'port': None,
'baudrate': 9600,
'bytesize': 8,
'parity': 'N',
'stopbits': 1,
'timeout': 2.0,
}
def __init__(self, serial_params):
"""Monitor the stenotype over a serial port.
The key-value pairs in the <serial_... | as the keyword arguments for a serial.Serial object.
"""
ThreadedStenotypeBase.__init__(self)
self.serial_port = None
self.serial_params = serial_params
def _close_port(self):
if self.serial_port is None:
return
self.serial_port.close()
s... |
# -*- coding: utf-8 -*-
from folium.plugins.marker_cluster import MarkerCluster
from folium.utilities import if_pandas_df_convert_to_numpy, validate_location
from jinja2 import Template
class FastMarkerCluster(MarkerCluster):
"""
Add marker clusters to a map using in-browser rendering.
Using FastMarkerC... | ilable when using it.
Parameters
----------
data: list of list with values
List of list of shape [[lat, lon], [lat, lon], etc.]
When you use a custom | callback you could add more values after the
lat and lon. E.g. [[lat, lon, 'red'], [lat, lon, 'blue']]
callback: string, optional
A string representation of a valid Javascript function
that will be passed each row in data. See the
FasterMarkerCluster for an example of a custom callba... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 01 10:45:09 2014
Training models remotely in cloud
@author: pacif_000
"""
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
import os
import platform
if platform.system() == 'Windows':
import win32api
else:
import signal
import thread
... | if producer:
producer.stop()
producer = None
if kafka:
kafka.close()
| kafka = None
print('remote_rainter {0} is shutting down'.format(os.getpid()))
def handler(sig, hook = thread.interrupt_main):
global kafka, consumer, producer
if consumer:
consumer.commit()
consumer.stop()
consumer = None
if producer:
producer.stop()
producer = N... |
# Copyright (c) 2013 - 2020 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
import re
from typing import List
from yawast.reporting.enums | import Vulnerabilities
from yawast.scanner.plugins.result import Result
from yawast.shared import network, output
_checked: List[str] = []
def reset():
global _checked
_checked = []
| def check_cve_2019_5418(url: str) -> List[Result]:
global _checked
# this only applies to controllers, so skip the check unless the link ends with '/'
if not url.endswith("/") or url in _checked:
return []
results: List[Result] = []
_checked.append(url)
try:
res = network.http... |
#因为首尾相连, 考虑第一位抢或不抢 两种情况分开
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums)
l = []
... | # print(nums)
# l = [0] * len(nums)
l.append(nums[0])
l1.append(0)
l.append(max(nums[0], nums[1]))
l1.append(nums[1])
for i in range(2, len(nums)):
if i == len(nums) - 1:
l.append(l[i-1])
else:
l.append(max(l[i-... | == 2:
l1.append(max(l1[i-1], nums[i]))
else:
l1.append(max(l1[i-2] + nums[i], l1[i-1]))
return max(max(l), max(l1))
|
import unittest
from mock import Mock
from cartodb_services.tomtom.isolines import TomTomIsolines, DEFAULT_PROFILE
from cartodb_services.tools import Coordinate
from credentials import tomtom_api_key
VALID_ORIGIN = Coordinate(-73.989, 40.733)
class TomTomIsolinesTestCase(unittest.TestCase):
def setUp(self):
... | _isolines.calculate_isochrone(
origin=VALID_ORIGIN,
profile=DEFAULT_PROFILE,
time_ranges=time_ranges)
assert solution
def test_calculate_isodistance(self):
distance_r | ange = 10000
solution = self.tomtom_isolines.calculate_isodistance(
origin=VALID_ORIGIN,
profile=DEFAULT_PROFILE,
distance_range=distance_range)
assert solution
|
# -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [ | token])
row = cursor.fetchone()
return 0 if row is None else row[2]
def deposit(self, token, amount):
cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balance... | execute(
"""UPDATE balances SET amount = amount + %s WHERE token = %s""",
[amount, token])
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, amount])
self.db.commit()
return True
def withdraw(self, token, a... |
#!/usr/bin/python
#
#
from distutils.core import setup
from spacewalk.common.rhnConfig import CFG, initCFG
initCFG('web')
setup(name = "rhnclient",
version = "5.5.9",
description = CFG.PRODUCT_NAME + " Client Utilities and Libraries",
long_description = CFG.PRODUCT_NAME + """\
Client Utilities
Incl... | , "rhn.client"],
license = "GPL",
|
)
|
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from . import BedLevelMachineAction
from . import UMOUpgradeSe | lection
def getMetaData():
return {}
def register(app):
return { "machine_action": [
BedLevelMachine | Action.BedLevelMachineAction(),
UMOUpgradeSelection.UMOUpgradeSelection()
]}
|
import _plotly_utils.basevalidators
class WidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="width", parent_name="scatter.line", **kwargs):
super(WidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | edit_type=kwargs.pop("edit_ | type", "style"),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "style"),
**kwargs
)
|
n=int(input('Enter any number: '))
if n%2!=0:
n=n+1
for i in range(n):
for j in range(n):
if (i==int(n/2)) or j==int(n/2) or ((i==0)and (j>=int(n/2))) or ((j==0)and (i<=int(n/2))) or ((j==n-1)and (i>=int(n/2))) or ((i==n-1)and (j<=int(n/2))):
| print('*',end='')
else:
print(' ',end= | '')
print()
|
from PyQt4.QtCore import QSize
from PyQt4.QtGui import QVBoxLayout
# This is really really ugly, but the QDockWidget for some reason does not notice when
# its child widget becomes smaller...
# Therefore we manually set its minimum s | ize when our own minimum size changes
class MyVBoxLayout(QVBoxLayout):
def __init__(self, parent=None):
QVBoxLayout.__init__(self, parent)
self._last_size = QSize(0, 0)
def setGeometry(self, r):
QVBoxLayout.setGeo | metry(self, r)
try:
wid = self.parentWidget().parentWidget()
new_size = self.minimumSize()
if new_size == self._last_size: return
self._last_size = new_size
twid = wid.titleBarWidget()
if twid is not None:
theight = twid.s... |
# Copyright (c) 2013 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | L3_HOSTB, constants.L3_AGENT_MODE_LEGACY)
dhcp_hosta = helpers._get_dhcp_agent_dict(DHCP_HOSTA)
dhcp_hostc = helpers._get_dhcp_agent_dict(DHCP_HOSTC)
helpers.register_l3_agent(host=L3_HOSTA)
helpers.register_l3_agent(host=L3_HOSTB)
helpers.register_dhcp_agent(host=DHCP_HOSTA)
... | |
#!/bin/env python
# \author Hans J. Johnson
#
# Prepare for the future by recommending
# use of itk::Math:: functions over
# vnl_math:: functions.
# Rather than converting vnl_math_ to vnl_math::
# this prefers to convert directly to itk::Math::
# namespace. In cases where vnl_math:: is simply
# an alias to std:: func... | _math_remainder_floored,itk::Math::remainder_floored
"""
ITK_replace_head_names = OrderedDict()
ITK_replace_functionnames = OrderedDict()
ITK_replace_manual = OrderedDict()
ITK_repl | ace_manual['"vnl/vnl_math.h"']='"itkMath.h"'
ITK_replace_manual['<vnl/vnl_math.h>']='<itkMath.h>'
for line in info_for_conversion.splitlines():
linevalues = line.split(",")
if len(linevalues) != 3:
#print("SKIPPING: " + str(linevalues))
continue
fname=linevalues[0]
new_name=fname.replac... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Defines custom errors and exceptions used in `astropy.samp`.
"""
impo | rt xmlrpc.client as xmlrpc
from astropy.utils.exceptions import AstropyUserWarning
__all__ = ['SAMPWarning', 'SAMPHubError', 'SAMPClientError', 'SAMPProxyError']
class SAMPWa | rning(AstropyUserWarning):
"""
SAMP-specific Astropy warning class
"""
class SAMPHubError(Exception):
"""
SAMP Hub exception.
"""
class SAMPClientError(Exception):
"""
SAMP Client exceptions.
"""
class SAMPProxyError(xmlrpc.Fault):
"""
SAMP Proxy Hub exception
"""
|
#Author: Miguel Molero <miguel.molero@gmail.com>
from PyQt5.QtCore import *
from PyQt5.Qt | Gui import *
from PyQt5.QtWidgets import *
class ObjectInspectorWidget(QWidget):
def __init__(self, parent = None):
super(ObjectInspectorWidget, self).__init__(parent)
layout = QVBoxLayout()
self.tab = QTabWidget() |
self.properties_tree = QTreeWidget()
self.properties_tree.setHeaderLabels(["",""])
self.properties_tree.setAlternatingRowColors(True)
self.properties_tree.setColumnCount(2)
self.properties_tree.header().resizeSection(0, 200)
self.tab.addTab(self.properties_tree, "Proper... |
t=b'Sample message for keylen<blocklen',
key=codecs.decode(
'00010203' '04050607' '08090A0B' '0C0D0E0F' '10111213'
'14151617' '18191A1B',
'hex',
),
mac=codecs.decode(
'E3D249A8' 'CFB67EF8' 'B7A169E9' 'A0A59971' '4A2CECBA... | 0C0D0E0F' '10111213'
'14151617' '18191A1B' '1C1D1E1F' '20212223' '24252627'
'28292A2B' '2C2D2E2F' '30313233' '34353637' '38393A3B'
'3C3D3E3F' '40414243' '44454647' '48494A4B' '4C4D4E4F'
'50515253' '54555657' '58595A5B' '5C5D5E5F' '60616263'
| '64656667' '68696A6B' '6C6D6E6F' '70717273' '74757677'
'78797A7B' '7C7D7E7F',
'hex',
),
mac=codecs.decode(
'63C5DAA5' 'E651847C' 'A897C958' '14AB830B' 'EDEDC7D2'
'5E83EEF9' '195CD458' '57A37F44' '8947858F' '5AF50CC2'
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, clf, res=0.02):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, res),
np.arang... | X[:, 1], c=y, alpha=0.8)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
class Perceptron(object):
def __init__(self, eta=0.01, epochs=50):
self.eta = eta
self.epochs = epochs
def train(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
... | ge(self.epochs):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
... |
# -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import Client
from .....checkout.tests import BaseCheckoutAppTests
from .....delivery.tests import TestDeliveryProvider
from .....order import handler as order_handler
from .....payment imp... | rtEqual(order.status, 'pay | ment-pending')
def test_confirmation_view_redirects_when_order_or_payment_is_missing(self):
cart = self._get_or_create_cart_for_client(self.anon_client)
cart.replace_item(self.dead_parrot, 1)
order = self._get_or_create_order_for_client(self.anon_client)
# without payment
... |
# -*- coding: utf-8 -*-
# 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 pytest
import backend_common
@pytest.fixture(scope='session')
def app():
... | ': 'dummy_id',
'AUTH_CLIENT_SECRET': 'dummy_secret',
'AUTH_DOMAIN': 'auth.localho | st',
'AUTH_REDIRECT_URI': 'http://localhost/login',
'OIDC_USER_INFO_ENABLED': True,
'OIDC_CLIENT_SECRETS': os.path.join(os.path.dirname(__file__), 'client_secrets.json'),
'TASKCLUSTER_CLIENT_ID': 'something',
'TASKCLUSTER_ACCESS_TOKEN': 'something',
})
app = shipit_api.cr... |
faces/embedding_in_qt_sgskip.html
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
if is_pyqt5():
from matplotlib.backends.backend_qt5agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
else:
from matplotlib.backends.backend_qt4agg import (
FigureCanvas, Na... |
cnt10ks_imu = nci.variables[cntvar][:]
#time_imu = netCDF4.num2date(nci.variables['time'][:],units=nci.variables['t | ime'].units)
fi = 1/(np.diff(cnt10ks_imu).mean())
for vartmp in nci.variables:
print(vartmp)
if(not "cnt" in vartmp):
varname = g + ' ' + vartmp
print('reading')
... |
command
# will run!? build the ssh command - n.b: spaces cause wobblies!
cmd = ['ssh']
cmd.extend(["%s@%s" % (rsync_user, rsync_server)])
mkdirstr = "mkdir -p"
cmd.extend([mkdirstr])
cmd.extend([rem_path])
if wxobs_debug == 2:
... | clude file.
[[Remote]]
This is used when you want to tra | nsfer the include file and the
database to a remote machine where the web files have been sent
seperately with the weewx.conf [FTP] or [RSYNC] section.
dest_directory: is the switch that turns this o. It transfers BOTH the
include and database files to the same directory as the tuple spe... |
# © 2017 Sergio Teruel <sergio.ter | uel@tecnativa.com>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from .hooks impor | t pre_init_hook
from . import models
from . import report
|
# Copyright (c) 2014, | Max Zwiessele, James Hensman
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from paramz.transformations import *
from paramz.transformations imp | ort __fixed__
|
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | should be done
:param sample_form: form in which experimental sample is: Powder or SingleCrystal (str)
:param abins_data: object of type AbinsData with data from phonon file
:param instrument: object of type Instrument for which simulation should be performed
:p | aram quantum_order_num: number of quantum order events taken into account during the simulation
:param bin_width: width of bins in wavenumber
"""
if sample_form in AbinsModules.AbinsConstants.ALL_SAMPLE_FORMS:
if sample_form == "Powder":
return AbinsModules.SPowderSe... |
'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},... |
video_urls = video_urls_dict[format_id]
for i, video_url_info in enumerate(video_urls):
if len(entries) < i + 1:
entries.append({'formats': []})
entries[i]['formats'].append(
{
'url': video_url_info[... | elf.get_bid(format_id))
}
)
for i in range(len(entries)):
self._sort_formats(entries[i]['formats'])
entries[i].update(
{
'id': '%s_part%d' % (video_id, i + 1),
'title': title,
}
... |
ices=[(b'BGN', b'Began'), (b'END', b'Ended'), (b'OCR', b'Occurred')], max_length=3, null=True),
),
migrations.AddField(
model_name='authority',
name='dataset',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
... | fix',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
| model_name='historicalacrelation',
name='record_status_explanation',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='historicalacrelation',
name='record_status_value',
field=models.Ch... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-10-14 12:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Documen... | models.BooleanField()),
| ('update_time', models.DateTimeField(auto_now=True)),
],
),
]
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | re management
endpoint audience.
:type azure_management_endpoint_audience: str
"""
_validation = {
'resource_id': {'required': True},
'aad_authority': {'required': True},
'aad_tenant_id': {'required': True},
'service_principal_client_id' | : {'required': True},
'service_principal_object_id': {'required': True},
'azure_management_endpoint_audience': {'required': True},
}
_attribute_map = {
'auth_type': {'key': 'authType', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'aad_authority': ... |
'''Todo:
* Add multiple thread support for async_process functions
* Potentially thread each handler function? idk
'''
import sys
import socket
import re
import threading
import logging
import time
if sys.hexversion < 0x03000000:
#Python 2
import Queue as queue
BlockingIOError = socket.error
else:
imp... | for handler in self._handlers['kick']:
handler(self, nick, host, channel, kicked_nick, reason)
elif command == 'NICK':
new_nick = args[2][1:]
for handler in self._handlers['nick']:
handler(s... | channel = args[2]
message = ' '.join(args[3:])
for handler in self._handlers['notice']:
handler(self, nick, host, channel, message)
else:
logger.warning("Unhandled command %s" % command)
... |
from django.http import HttpRequest
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
try:
from allauth.account import app_settings as allauth_settings
from allauth.utils import (email_address_exists,
get_username_max_length)
from allaut... | aise serializers.ValidationError(_('Incorrect value'))
if not login.is_existing:
login.lookup()
login.save(request, connect=True)
attrs['user'] = login.account.user
return attrs
class RegisterSerializer(serializers.Serializer):
username = serializers.CharField(
... | s.USERNAME_MIN_LENGTH,
required=allauth_settings.USERNAME_REQUIRED
)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password1 = serializers.CharField(write_only=True)
password2 = serializers.CharField(write_only=True)
def validate_username(self, username):
... |
#!/Users/shreyashirday/Personal/ | openmdao-0.13.0/bin/python
# EASY-INSTALL-SCRIPT: 'docutils==0.10','rst2odt_prepstyles.py'
__requires__ = 'docutils==0.10'
__import__('pkg_resources').run_script('docutils==0.10', 'rst2odt_pre | pstyles.py')
|
#!/usr/bin/env python2.7
#
# Copyright 2017 Google 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 c | opy 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 speci... | for all exception's which search services may raise."""
from search.common import utils
class Error(Exception):
"""Generic error."""
def ToString(self, error_prefix):
"""Builds error message string escaping it for HTML.
Args:
error_prefix: an error prefix.
Returns:
HTML escaped error m... |
#! /usr/bin/env python
# coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
import os
#config
#ch | ange the GPIO Port number
gpioport=24
sdate = time.strftime("%H:%M:%S")
stime = time.strftime("%Y-%m-%d")
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpioport, GPIO.IN)
def sysshutdown(channel):
msg="System shutdown GPIO.Low state"
logpath="/var/log/shutdown.log"
print("System shutdown")
f = open(logpath, "a")
f.write(str... | tdown("1")
break
time.sleep(2)
|
d_dirs.append('original')
options.compressed_dirs.append('goodbad')
options.compressed_dirs.append('maxqual')
options.compressed_dirs.append('minqual')
for reads_filename in options.reads_filenames:
# Copy the original sequences over.
out_cmd("", std_err_file.name, ["cp", reads_filenam... | call(call_arr, stdout=std_err_file, stderr=std_err_file)
os.chdir(prev_dir)
# QualComp writes the files into the original directory,
# so move the fastq files into the QualComp directory.
mv_cmd = "mv " + qualcomp_prefix + "_" + options.clusters + "_"... | _dir + '/qualcomp_r' + rate + '/' + os.path.basename(reads_filename)
call_arr = mv_cmd.split()
out_cmd("", std_err_file.name, call_arr)
call(call_arr, stderr=std_err_file)
filename_list = glob.glob(qualcomp_prefix + "_" + options.clusters + "_*")
... |
"""Prepare rendering of popular smart grid actions widget"""
from apps.widgets.smartgrid import smartgrid
def supply(request, page_nam | e):
"""Supply view_objects content, which are the popular actions from the smart grid game."""
_ = request
num_results = 5 if page_name != "status" else None
#contruct a dictionary containing the most popular tasks.
#The keys are the type of the task and the values are a list of tasks."""
popu... | mmitment": smartgrid.get_popular_actions("commitment", "approved", num_results),
"Event": smartgrid.get_popular_actions("event", "pending", num_results),
"Excursion": smartgrid.get_popular_actions("excursion", "pending", num_results),
}
count = len(popular_tasks)
return {
"popula... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-02-29 16:58
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sa_api_v2', '0004_dj... | migrations.AddF | ield(
model_name='attachment',
name='width',
field=models.IntegerField(blank=True, null=True),
),
]
|
"""Authentication and authorization."""
from haas.errors import AuthorizationError
from haas import model
from abc import ABCMeta, abstractmethod
import sys
_auth_backend = None
class AuthBackend(object):
"""An authentication/authorization backend.
Extensions which implement authentication/authorization b... | ):
"" | "Authenticate the api call, and prepare for later authorization checks.
This method will be invoked inside of a flask request context,
with ``haas.rest.local.db`` initialized to a valid database session.
It is responsible for authenticating the request, and storing any
data it will need... |
"""
Author: Seyed Hamidreza Mohammadi
This file is part of the shamidreza/uniselection software.
Please refer to the LICENSE provided alongside the software (which is GPL v2,
http://www.gnu.org/licenses/gpl-2.0.html).
This file includes the code for putting all the pieces together.
"""
from utils import *
from extra... | ()
units = units[:int(units.shape[0]*(100.0/100.0))]
best_units_indice=search(target_units, units,limit=20)
best_units = units[best_units_indice]
f=open('tmp2.pkl','w+')
import pickle
pickle.dump(best_units,f)
pickle.dump(fnames,f)
f.flush()
f.clos... | f.close()
for i in xrange(target_units.shape[0]):
print target_units[i].phone, best_units[i].phone, best_units[i].unit_id
#wavs=concatenate_units_overlap(best_units, fnames)
#gcis = gcis[(gcis>times[128]) * (gcis<times[140])]
#gcis -= times[128]
##$frm_time, frm_val = units2for(best_unit... |
import os
import os.path
from raiden.constants import | RAIDEN_DB_VERSION
def database_from_privatekey(base_dir, app_number):
""" Format a database path based on the private key and app number. """
| dbpath = os.path.join(base_dir, f"app{app_number}", f"v{RAIDEN_DB_VERSION}_log.db")
os.makedirs(os.path.dirname(dbpath))
return dbpath
|
=utf-8
from datetime import datetime, date, time
from decimal import Decimal
import json
import django
from django.forms import IntegerField
from django.test import TransactionTestCase, Client
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy
import pytz
from formapi.api imp... | 01)
def test_invalid_password(self):
data = {'username': self.user.username, 'password': '1337hax/x'}
response = self.send_request(self.authenticate_url, data)
self.assertEqual(response.status_code, 400)
response_data = json.loads(smart_u(response.content))
self.assertGreate... | ])
def test_invalid_parameters(self):
data = {'email': self.user.email, 'password': 'rosebud'}
response = self.send_request(self.authenticate_url, data)
self.assertEqual(response.status_code, 401)
def test_revoked_api_key(self):
data = {'username': self.user.username, 'password... |
'''
20140213
Import CSV Data - Dict
Save as JASON?
Basic Stats
Save to file
Find Key Words
Generate Reports...
Generate Plots
'''
import csv
import numpy as np
import matplotlib as mpl
from scipy.stats import nanmean
filename = '20140211_ING.csv'
###____________ Helper ___________###
def number_fields(data):
... | ORT ----')
print('------------------------')
print('')
print('Filename: \t %s' % filename)
print('')
print('--------------------')
for i in fields:
print('FIELD: \t\t %s' % i)
print('#Values: \t %s' % d[i]['#Values'])
print('M | ax: \t\t %s' % d[i]['Max'])
print('Min: \t\t %s' % d[i]['Min'])
print('Mean: \t\t %s' % round(d[i]['Mean'], 2))
print('--------------------')
print('')
###________ main _________###
def main(filename):
basic_report(filename)
print("")
numeric_report(filename)
main(filenam... |
# -*- coding: utf-8 -*-
# Created By: Virgil Dupras
# Created On: 2009-09-19
# Copyright 2010 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://... |
self.connect(self.browserView.selectionModel(), SIGNAL('selectionChanged(QItemSelection,QItemSelection)'), self.browserSelectionChanged)
def _setupUi(self):
self.setupUi(self)
self.setWindowFlags(Qt.Tool)
self.browserView.setMod | el(self.boxModel)
h = self.browserView.header()
h.setResizeMode(QHeaderView.Fixed)
h.resizeSection(1, 120)
h.setResizeMode(0, QHeaderView.Stretch)
#--- Events
def browserSelectionChanged(self, selected, deselected):
selectedIndexes = self.browserView.selectionModel()... |
"""The WaveBlocks Project
Compute the transformation to the eigen basis for wavefunction.
@author: R. Bourquin
@copyright: Copyright (C) 2012, 2016 R. Bourquin
@license: Modified BSD License
"""
from WaveBlocksND import BlockFactory
from WaveBlocksND import WaveFunction
from WaveBlocksND import BasisTransformationWF... | s.shape[0]
iomout.add_wavefunction(parameters, timeslots=nrtimesteps, blockid=blockidout)
# The grid on the domain
grid = BlockFactory().create_grid(para | meters)
# The potential used
Potential = BlockFactory().create_potential(parameters)
# Basis transformator
BT = BasisTransformationWF(Potential)
BT.set_grid(grid)
# And two empty wavefunctions
WF = WaveFunction(parameters)
WF.set_grid(grid)
# Iterate over all timesteps
for i,... |
try:
import ossaudiodev
except:
print "ossaudiodev not installed"
ossaudiodev = None
try:
import FFT
except:
print "FFT not installed"
ossaudiodev = None
try:
import Numeric
except:
print "Numeric not installed"
ossaudiodev = None
import struct, math, time, threading, copy
def add(s... | nt(self.sample_rate * seconds)
for freq in freqs:
if self.cache and (freq,seconds) in self.cacheDict:
| sample = self.cacheDict[(freq,seconds)]
else:
for n in range(len(sample)):
sample[n] = min(max(sample[n] + int(127 * math.sin(n * 2 * math.pi * freq/self.sample_rate) * volume), 0),255)
self.cacheDict[(freq,seconds)] = sample
if self.async:
... |
# (c) 2014, James Tanner <tanner.jc@gmail.com>
# (c) 2014, James Cammarata, <jcammarata@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version ... | a = vl.decrypt(fdata)
except errors.AnsibleError:
error_hit = True
os.unlink(v10_file.name)
assert vl.cipher_name == "AES256", "wrong cipher name set after rekey: %s" % vl.cipher_name
assert error_hit is False, "error decrypting migrated | 1.0 file"
assert dec_data.strip() == b"foo", "incorrect decryption of rekeyed/migrated file: %s" % dec_data
|
def main():
a=r | aw_input()
print a | .lstrip()
print "Hello world"
main()
|
from __future__ import absolute_import
fro | m jinja2 import Markup
from rstblog.programs import RSTProgram
import typogrify
class TypogrifyRSTProgram(RSTProgram):
def get_fragments(self):
if self._fragment_cache is not None:
return self._fragment_cache
with self.context.open_source_file() as f:
self.get_header(f)
... | Markup(typogrify.typogrify(rv['fragment']))
self._fragment_cache = rv
return rv
def setup(builder):
builder.programs['rst'] = TypogrifyRSTProgram |
from aiida import load_dbenv
load_dbenv()
from aiida.orm import Code, DataFactory
import numpy as np
StructureData = DataFactory('structure')
ParameterData = DataFactory('parameter')
codename = 'lammps_md@boston'
############################
# Define input parameters #
############################
a = 5.404
cell... | :
structure.append_atom(position=np.dot(scaled_position, cell).tolist(),
symbols=symbols[i])
structure.store()
# Silicon(C) Tersoff
tersoff_si = {'Si Si Si ': '3.0 1.0 1.7322 1.0039e5 16.218 -0.59826 0.78734 1.0999e-6 1.7322 471.18 2.85 0.15 2.4799 1830.8'}
potential ={'pair_st... |
parameters_md = {'timestep': 0.001,
'temperature' : 300,
'thermostat_variable': 0.5,
'equilibrium_steps': 100,
'total_steps': 2000,
'dump_rate': 1}
code = Code.get_from_string(codename)
calc = code.new_calc(max_wallclock_seconds=36... |
from codecs import open # To use a consistent encoding
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
# Get version info
ABOUT = {}
with open(path.join(HERE, 'datadog_checks', 'riak_repl', '__about__.py')) as f:
exec(f.read(), ABOUT)
# Get the long description from... | ort literal_eval
pattern = r'^{} = (\[.*?\])$'.format(name)
with open(os.path.join(HERE, 'pyproject.toml'), 'r', | encoding='utf-8') as f:
# Windows \r\n prevents match
contents = '\n'.join(line.rstrip() for line in f.readlines())
array = re.search(pattern, contents, flags=re.MULTILINE | re.DOTALL).group(1)
return literal_eval(array)
CHECKS_BASE_REQ = parse_pyproject_array('dependencies')[0]
setup(
... |
import os,sys,re
# EXTRACTING ALL FILENAMES AND THEIR CLIENTS
# ---------------------------------------------------
# read in the log
# ---------------------------------------------------
f=open(sys.argv[1],'rb')
data=f.readlines()
f.close()
n=0
t=len(data)
clients = []
filename = None
for l in data :
n = n... | # new file to ingest
if parts[6] == 'Read' :
# all products will have its first cli | ent as "allproducts"
if filename != None :
if len(clients) == 0 :
clients.append('allproducts')
else :
clients.sort()
clients.insert(0,'allproducts')
print("%s %s" % (filename,','.join(clients)) )
filepath = parts[-1]
filename = ... |
# -*- coding: utf-8 -*-
import webapp2
from boilerplate import models
from boilerplate import forms
from boilerplate.handlers import BaseHandler
from google.appengine.datastore.datastore_query import Cursor
from google.appengine.ext import ndb
from google.appengine.api import users as googleusers
from collections impor... | user in users:
if user.country:
users_by_country[user.country] += 1
params = {
| "data": users_by_country.items()
}
return self.render_template('admin/geochart.html', **params)
class EditProfileForm(forms.EditProfileForm):
activated = fields.BooleanField('Activated')
class List(BaseHandler):
def get(self):
p = self.request.get('p')
q = self.re... |
import asyncio
from unittest import mock
from aiorpcx import RPCError
from server.env import Env
from server.controller import Controller
loop = asyncio.get_event_loop()
def set_env():
env = mock.create_autospec(Env)
env.coin = mock.Mock()
env.loop_policy = None
env.max_sessions = 0
env.max_subs... | xception(msg):
raise RPCError(1, msg)
def ensure_text_exception(test, exception):
res = err = None
try:
| res = loop.run_until_complete(test)
except Exception as e:
err = e
assert isinstance(err, exception), (res, err)
def test_transaction_get():
async def test_verbose_ignore_by_backend():
env = set_env()
sut = Controller(env)
sut.daemon_request = mock.Mock()
sut.d... |
"""
================================================================================
Logscaled Histogram
================================================================================
| Calculates a logarithmically spaced histogram for a data map.
| Written By: Matthew Stadelman
| Date Written: 2016/03/07
| Last Mod... | stance.
"""
parser = subparsers.add_parser(cls.__name__,
aliases=['histlog'],
parents=[parent],
help=cls.__doc__)
#
parser.add_argument('scale_fact', type=float, nargs='?'... | default=10.0,
help='base to generate logscale from')
parser.set_defaults(func=cls)
def define_bins(self, **kwargs):
r"""
This defines the bins for a logscaled histogram
"""
self.data_vector.sort()
sf = self.args['scale_fact']
num_b... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Roboterclub Aachen e.V.
# All rights reserved.
#
# The file is part of the xpcc library and is released under the 3-clause BSD
# license. See the file `LICENSE` for the full license governing this code.
# ----------------------------------------------... | r import AVRDevi | ceReader
from dfg.avr.avr_writer import AVRDeviceWriter
if __name__ == "__main__":
"""
Some test code
"""
level = 'info'
logger = Logger(level)
devices = []
for arg in sys.argv[1:]:
if arg in ['error', 'warn', 'info', 'debug', 'disabled']:
level = arg
logger.setLogLevel(level)
continue
xml_path = ... |
from rest_framework import relations, serializers
import amo
import mkt.carriers
import mkt.regions
from addons.models import Category
from mkt.api.fields import SplitField, TranslationSerializerField
from mkt.api.serializers import URLSerializerMixin
from mkt.collections.serializers import (CollectionSerializer, Slug... | CollectionSerializer())
class Meta:
| fields = ('carrier', 'category', 'collection', 'id', 'item_type',
'region', 'url')
item_types = ('collection',)
model = FeedItem
url_basename = 'feeditem'
def validate(self, attrs):
"""
Ensure that at least one object type is specified.
"""
... |
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_j... | le_dir, 'json-org-sample5.smile')
j = os.path.join(self.json_dir, 'json-org-sample5.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))... | self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def... |
import nmrglue as ng
import matplotlib.pyplot as plt
# read in data
dic, data = ng.pipe.read("test.ft2")
# find PPM limits along each axis
uc_15n = ng.pipe.make_uc(dic, data, 0)
uc_13c = ng.pipe.make_uc(di | c, data, 1)
x0, x1 = uc_13c.ppm_limi | ts()
y0, y1 = uc_15n.ppm_limits()
# plot the spectrum
fig = plt.figure(figsize=(10, 10))
fig = plt.figure()
ax = fig.add_subplot(111)
cl = [8.5e4 * 1.30 ** x for x in range(20)]
ax.contour(data, cl, colors='blue', extent=(x0, x1, y0, y1), linewidths=0.5)
# add 1D slices
x = uc_13c.ppm_scale()
s1 = data[uc_15n("105.52... |
#!/usr/bin/env python3
#
# Copyright (c) 2012 Timo Savola
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
... | ss + offset)
def _data(self, offset, size):
return self.arena._data(self.address + offset, size)
@property
def end(self):
return self.address + self.size
class Allocated(Node):
def __ | init__(self, arena, address, size):
super(Arena.Allocated, self).__init__(arena, address)
self.size = size
def __str__(self):
return "Allocated space at %u: %r" % (self.address, self.data)
@property
def data(self):
return self._data(0, self.size)
class Free(Node):
def __str__(self):
return "... |
kycoord_circ_2['aperture_sum'])
photometry_skycoord_ell = aperture_photometry(
data, SkyEllipticalAperture(pos_skycoord, 3 * u.arcsec,
3.0001 * u.arcsec, theta=45 * u.arcsec),
wcs=wcs)
photometry_skycoord_ell_2 = aperture_photometry(
data, SkyElliptic... | a has unit, | but error does not
aperture_photometry(data2, aper, error=error1)
error2 = u.Quantity(error1 * u.Jy)
with pytest.raises(ValueError):
# data and error have different units
aperture_photometry(data2, aper, error=error2)
def test_aperture_photometry_with_error_units():
"""Test apert... |
s initially un-cached
with self.assertNumQueries(FuzzyInt(1, 20)):
response = self.client.get('/en/')
self.assertEqual(response.status_code, 200)
#
# Test that subsequent requests of the same page are still requires DB
... | response = self.client.get('/en/')
self.assertContains(response, 'First c | ontent')
response = self.client.get('/en/')
self.assertContains(response, 'First content')
add_plugin(placeholder, "TextPlugin", 'en', body="Second content")
page1.publish('en')
response = self.client.get('/en/')
self.assertContains(response, 'Seco... |
#!/usr/bin/python
import cgi
from redis import Connection
from socket import gethostname
from navi import *
fields = cgi.FieldStorage()
title = "Message | Box"
msg_prefix = 'custom.message.'
def insert_msg(cust, tm, msg):
conn = Connection(host=gethostname(),port=6379)
conn.send_command('set', msg_prefix+cust+'--'+tm, msg)
conn.disconnect()
def read_msg():
ret = ''
conn = Connection(host=gethostname(),port=6379)
conn.send_command('keys', msg... | send_command('mget', *keys)
vals = conn.read_response()
ret += "<h2>" + "Message log" + "</h2>"
for k, v in zip(keys, vals):
ret += "<span>" + k.replace(msg_prefix, '').replace('--', ' ') + "</span>"
ret += "<pre readonly=\"true\">" + v + "</pre>"
conn.disconnect()... |
# License LGPL-3.0 or later | (http://www.gnu.org/licenses/lgpl).
fr | om . import controllers
|
impor | t struct
import unittest
from zoonado.protocol import response, primitives
class ResponseTests(unittest.TestCase):
def test_deserialize(self):
class FakeResponse(response.Response):
opcode = 99
parts = (
("first", primitives.Int),
("second", prim... | # note that the xid and opcode are omitted, they're part of a preamble
# that a connection would use to determine which Response to use
# for deserializing
raw = struct.pack("!ii6s", 3, 6, b"foobar")
result = FakeResponse.deserialize(raw)
self.assertEqual(result.first, 3)
... |
import os
MOZ_OBJDIR = 'obj-firefox'
config = {
'default_actions': [
'clobber',
'clone-tools',
'checkout-sources',
#'setup-mock',
'build',
#'upload-files',
#'sendchange',
'check-test',
'va | lgrind-test',
#'generate-build-stats',
#'update',
],
'stage_platform': 'linux64-va | lgrind',
'publish_nightly_en_US_routes': False,
'build_type': 'valgrind',
'tooltool_manifest_src': "browser/config/tooltool-manifests/linux64/\
releng.manifest",
'platform_supports_post_upload_to_latest': False,
'enable_signing': False,
'enable_talos_sendchange': False,
'perfherder_extra_opt... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('training', '0006_auto_20160627_1620'),
]
operations = [
migrations.RemoveField(
model_name='trainesscourserecor | d',
name='approvedby',
),
migrations.RemoveField(
model_name='trainesscourserecord', |
name='createdby',
),
migrations.RemoveField(
model_name='trainesscourserecord',
name='createtimestamp',
),
]
|
"""
Proctored Exams Transformer
"""
from django.conf import settings
from edx_proctoring.api import get_attempt_status_summary
from edx_proctoring.models import ProctoredExamStudentAttemptStatus
from openedx.core.lib.block_structur | e.transformer import BlockStructureTransformer, FilteringTransformerMixin
class ProctoredExamTransformer(FilteringTransformerMixin, BlockStructureTransformer):
"""
Exclude proctored exams unless the user is not a verified student or has
declined taking the exam.
"""
VERSION = 1
BLOCK_HAS_PROCT... | tes any information for each XBlock that's necessary to execute
this transformer's transform method.
Arguments:
block_structure (BlockStructureCollectedData)
"""
block_structure.request_xblock_fields('is_proctored_enabled')
block_structure.request_xblock_fields('is_p... |
from panda3d.core import LPoint3
# EDIT GAMEMODE AT THE BOTTOM (CHESS VARIANTS)
# COLORS (for the squares)
BLACK = (0, 0, 0, 1)
WHITE = (1, 1, 1, 1)
HIGHLIGHT = (0, 1, 1, 1)
HIGHLIGHT_MOVE = (0, 1, 0, 1)
HIGHLIGHT_ATTACK = (1, 0, 0, 1)
# SCALE (for the 3D representation)
SCALE = 0.5
PIECE_SCALE = 0.3
BOARD_HEIGHT = ... | [ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
],
[
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[-3,-1,-1,-1,-3],
[-2,-4,-6,-4,-2],
],
]
CARD_PAWN_2STEP = True
CARD_B... | 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
],
[
[ 4, 3, 3, 4],
[ 1, 1, 1, 1],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
try:
import sqlite3
except ImportError:
pass
import logging
from | lib.core.convert impo | rt utf8encode
from lib.core.data import conf
from lib.core.data import logger
from lib.core.exception import SqlmapConnectionException
from lib.core.exception import SqlmapMissingDependence
from plugins.generic.connector import Connector as GenericConnector
class Connector(GenericConnector):
"""
Homepage: htt... |
T, Float, INT, INTEGER, Integer, NCHAR, NVARCHAR, NUMERIC,
Numeric, SMALLINT, SmallInteger, String, TEXT, TIME, Text, Time, Unicode,
UnicodeText, VARCHAR, Enum)
from .. import mix_types as t
from ..main import (
SKIP_VALUE, LOGGER, TypeMixer as BaseTypeMixer, GenFactory as BaseFactory,
Mixer as BaseMix... | lue: A default value or NO_VALUE
"""
column = field.scheme
if isinstance(column, RelationshipProperty):
column = column.local_remote_pairs[0][0]
if not column.default:
return SKIP_VALUE
if column.default.is_callable:
return column.default.a... | sts value from database.
:param field_name: Name of field for generation.
:return : None or (name, value) for later use
"""
if not self.__mixer or not self.__mixer.params.get('session'):
return field_name, SKIP_VALUE
relation = self.mapper.get_property(field_name)... |
# Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com>
# 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... | ssions and
# limitations under the License.
import sys
if sys.version_info[0] >= 3:
basestring = str
unicode = str
def encode_string( value ):
return value.encode('utf-8') if isinstance(value, unicode) else value |
def decode_string(value):
return value if isinstance(value, basestring) else value.decode('utf-8')
# hmac.compare_digest were introduced in python 2.7.7
if sys.version_info >= ( 2, 7, 7 ):
from hmac import compare_digest as SecureStringsEqual
else:
# This is the compare_digest function from python 3.4, adapt... |
import unittest
import sys
import numpy as np
from opm.util import EModel
try:
from tests.utils import test_path
except ImportError:
from utils import test_path
class TestEModel(unittest.TestCase):
def test_open_model(self):
refArrList = ["PORV", "CELLVOL", "DEPTH", "DX", "DY", "DZ", "PORO", "... | self.assertEqual((nI,nJ,nK), (13, 22, 11))
nAct = mod1.active_cells()
self.assertEqual(nAct, 2794)
def test_hc_filter(self):
nAct_hc_eqln1 = 1090
nAct_hc_eqln2 = 1694
mod1 = EModel(test_path("data/9_EDITNNC.INIT"))
porv = mod1.get("PORV")
mod1.set_ | depth_fwl([2645.21, 2685.21])
mod1.add_hc_filter()
porv = mod1.get("PORV")
self.assertEqual(len(porv), nAct_hc_eqln1 + nAct_hc_eqln2)
mod1.reset_filter()
mod1.add_filter("EQLNUM","eq", 1);
mod1.add_filter("DEPTH","lt", 2645.21);
porv1 = mod1.get("PORV")
... |
nicode import to_unicode, to_str
from ansible.plugins import module_loader
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class ConsoleCLI(CLI, cmd.Cmd):
modules = []
def __init__(self, args):
super(ConsoleCLI, self)... | cd webservers:dbservers
cd webservers:!phoenix
cd webservers:&staging
cd webservers:dbservers:&s | taging:!phoenix
"""
if not arg:
self.options.cwd = '*'
elif arg == '..':
try:
self.options.cwd = self.inventory.groups_for_host(self.options.cwd)[1].name
except Exception:
self.options.cwd = ''
elif arg in '/*':
... |
from abc import ABCMeta, abstractmethod
class ProgressMessage(object):
def __init__(self, path, bytes_per_second, bytes_read, bytes_expected):
self._path = path
self._bytes_per_second = bytes_per_second
self._bytes_read = bytes_read
self._bytes_expected = bytes_expected
@prope... | sh(self, value):
self._hash = value
def get_dateModified(self):
return self._dateModified
def set_dateModified(self, value):
self._dateModified = valu | e
def get_content_type(self):
return self._contentType
def set_content_type(self, value):
self._contentType = value
@property
def path(self):
return self._path
@property
def name(self):
return self._name
@property
def isFolder(self):
return se... |
from direct.directnotify import DirectNotifyGlobal
from BaseActivityFSM import BaseActivityFSM
| from activityFSMMixins import IdleMixin
from activityFSMMixins import RulesMixin
from activityFSMMixins import ActiveMixin
from activityFSMMixins import DisabledMixin
from activityFSMMixins import ConclusionMixin
from activityFSMMixins import WaitForEnoughMixin
from activityFSMMixins import WaitToStartMixin
from activi... | yFSMMixins import WaitClientsReadyMixin
from activityFSMMixins import WaitForServerMixin
class FireworksActivityFSM(BaseActivityFSM, IdleMixin, ActiveMixin, DisabledMixin):
notify = DirectNotifyGlobal.directNotify.newCategory('FireworksActivityFSM')
def __init__(self, activity):
FireworksActivityFSM.n... |
# -*- coding: utf-8 -*-
"""
tomorrow night blue
---------------------
Port of the Tomorrow Night Blue colour scheme https://github.com/chriskempson/tomorrow-theme
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, Text, \
Number, Operator, Generic, Whitespace, ... | Name.Function: BLUE, # class: 'nf'
Name.Property: "", # class: 'py'
Name.Label: "", # class: 'nl'
Name.Namespace: YELLOW, # class: 'nn' - to be revised
Name.Other: BLUE, # class: '... | Name.Variable.Class: "", # class: 'vc' - to be revised
Name.Variable.Global: "", # class: 'vg' - to be revised
Name.Variable.Instance: "", # class: 'vi' - to be revised
Number: ORANGE, # class: 'm'
Number.Float: ... |
import unitt | est
from PyFoam.Applications.ConvertToCSV import ConvertToCSV
theSuite=unittest.Tes | tSuite()
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | infrastructure as | tei
def _get_model(shape, axis, keepdims, input_zp, input_sc, output_zp, output_sc, dtype):
a = relay.var("a", shape=shape, dtype=dtype)
casted = relay.op.cast(a, "int32")
mean = relay.mean(casted, axis, keepdims)
model = relay.qnn.op.requantize(
mean,
input_scale=relay.const(input_sc,... |
,
onupdate="CASCADE",
ondelete="CASCADE",
),
)
cookies = Table(
"cookies",
db.metadata,
Column("cookie", Text(), primary_key=True, nullable=False),
Column(
"name",
CIText(),
ForeignKey(
"accounts_user.username",
onupdate="CASCADE",
... | b.metadata,
Column("server_url", String(2047), primary_key=True, nullable=False),
Column("timestamp", Integer(), primary_key=True, nullable=False),
Column("salt", String(40), primary_key=True, nullable=False),
)
openid_discovered = Table(
"ope | nid_discovered",
db.metadata,
Column("url", Text(), primary_key=True, nullable=False),
Column("created", DateTime(timezone=False)),
Column("services", LargeBinary()),
Column("op_endpoint", Text()),
Column("op_local", Text()),
)
openid_nonces = Table(
"openid_nonces",
db.metadata,
... |
#!/usr/bin/env python
import os
import os.path
path = "source"
import doctest
for f in os.listdir(path):
if f.endswith(".txt"):
| print f
doctest.testfile(os.path.join(path, f), module_relative=False)
| |
"""
Virtualization installation functions.
Copyright 2007-2008 Red Hat, Inc.
Michael DeHaan <mdehaan@redhat.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... | nter + 1
else:
if bridge is not None:
| profile_bridge = bridge
else:
profile_bridge = profile_data["virt_bridge"]
if profile_bridge == "":
raise koan.InfoException("virt-bridge setting is not defined in cobbler")
nic_obj = virtinst.VirtualNetworkInterface(macaddr=random_mac(), br... |
features[str(feature)] = currWeight
sorted_features = sorted(features.iteritems(), key=operator.itemgetter(1))
sorted_features = [(features_str[f],abs(w)) for (f, w) in sorted_features]
#sorted_features.reverse()
return sorted_features
def getBestForAbsoluteNormalized(weights, ranges, num_consume... | return sorted_features
def getBestMinusWorst(weights, ranges, num_consumers):
features = {}
features_str = {}
#print weights
| (maxes, mins) = ranges
metrics_variables_string = [str(i) for i in metrics_variables]
#print weights
for i in weights:
(objective, weight, feature) = i
if features.get(str(feature)):
currWeight = features[str(feature)]
else:
currWeight = (1, 0)
... |
import load | _data as ld
import sys
import os
f_list = os.listdir(sys.argv[1])
data = ld.loadIntoPandas(ld.processAllDocume | nts(sys.argv[1], f_list))
data.to_pickle(sys.argv[2])
|
from fractions import gcd
def greatest_common_divisor(*args):
args = list(args)
a, b = args.pop(), a | rgs.pop()
gcd_local = gcd(a, b)
while len(args):
gcd_local = gcd(gcd_local, args.pop())
return gcd_local
def test_function():
assert greatest_common_divisor(6, 10, 15) == 1, "12"
assert greatest_common_divisor(6, 4) = | = 2, "Simple"
assert greatest_common_divisor(2, 4, 8) == 2, "Three arguments"
assert greatest_common_divisor(2, 3, 5, 7, 11) == 1, "Prime numbers"
assert greatest_common_divisor(3, 9, 3, 9) == 3, "Repeating arguments"
if __name__ == '__main__':
test_function()
|
ass AccountBankStatementLine(models.Model):
_name = "account.bank.statement.line"
_description = "Bank Statement Line"
_order = "statement_id desc, sequence"
_inherit = ['ir.needaction_mixin']
name = fields.Char(string='Memo', required=True)
date = fields.Date(required=True, default=lambda self... | elp="This technical field can be used at the statement line creation/import time in order to avoid the reconciliation"
" process on it later on. The statement line will simply create a counterpart on this account")
statement_id = fields | .Many2one('account.bank.statement', string='Statement', index=True, required=True, ondelete='cascade')
journal_id = fields.Many2one('account.journal', related='statement_id.journal_id', string='Journal', store=True, readonly=True)
partner_name = fields.Char(help="This field is used to record the third party nam... |
class APIError(Exception):
"""Represents an error returned in a response to a fleet API call
This exception will be raised any time a response code >= 400 is returned
Attributes:
code (int): The response code
message(str): The message included with the error response
http_error(goo... | If you need access to the raw response, this is where you'll find
it.
"""
def __init__(self, code, message, http_error):
"""Construct an exception representing an error returned by fleet
Args:
code (int):... | lient.errors.HttpError): The underlying exception that caused this exception
to be raised.
"""
self.code = code
self.message = message
self.http_error = http_error
def __str__(self):
# Return a string like r'Some bad... |
# Copyright (C) 2018, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw
# This file is part of Nicotb.
# Nicotb 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 opti... | om ms.IssueCommands(wcmd + rcmd)
test.Get(read_v)
yield ck_ev
MAGIC = next(r)
ADR = 200
print(
"Test Pipelined Interleaved R/W\n"
f"MAGIC/ADR is {MAGIC}/{ADR}"
)
wcmd = [(True, ADR+i*4, MAGIC+i) for i in range(N)]
rcmd = [(False, ADR+i*4) for i in range(N)]
cmd = [v for p in zip(wcmd, rcmd) for v in p]
t... | ses([("wd",), ("rd",),])
hsel, haddr, hwrite, htrans, hsize, hburst, hready, hresp = CreateBuses([
(("u_dut", "HSEL"),),
(("u_dut", "HADDR"),),
(("u_dut", "HWRITE"),),
(("u_dut", "HTRANS"),),
(("u_dut", "HSIZE"),),
(("u_dut", "HBURST"),),
(("u_dut", "HREADY"),),
(("u_dut", "HRESP"),),
])
ck_ev, rs_ev = CreateEv... |
# Copyright 2012 Nebula, 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 agree... |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# u | nder the License.
from django import template
from horizon.utils import html
class Breadcrumb(html.HTMLElement):
def __init__(self, request, template, root,
subfolder_path, url, attr=None):
super(Breadcrumb, self).__init__()
self.template = template
self.request = reques... |
t character has the value end. Such a
ramp can be used as a map argument of im.Map.
"""
rv = ramp_cache.get((start, end), None)
if rv is None:
chars = [ ]
for i in range(0, 256):
i = i / 255.0
chars.append(chr(int( end * i + start * (1.0 - i) ) ) )
... | (), True)
renpy.display.module.map(surf, rv,
self.rmap, self.gmap, self.bmap, self.amap)
return rv
def predict_files(self):
return self.image.predict_files()
class Twocolor(Imag | eBase):
"""
This takes as arguments two colors, white and black. The image is
mapped such that pixels in white have the white color, pixels in
black have the black color, and shades of gray are linearly
interpolated inbetween. The alpha channel is mapped linearly
between 0 and the alpha found i... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Criado em 19 de Novembro de 2016
@author: Denis Varise Bernardes & Eder Martioli
Descricao: esta biblioteca possui as seguintes funcoes:
mkDir_saveCombinedImages: pela chamada da funcao LeArquivoReturnLista retorna a lista de todas as imagens ad... | m)
criaArquivo_listaImag | ensReduzidas()
return
def mkDir_ImgPair(tagPAR2, tagPAR1, ganho, images_dir):
print('Criando diretorio: Imagens reduzidas')
if not os.path.exists(images_dir + '\\' + 'Imagens_reduzidas'): os.makedirs(images_dir + '\\' + 'Imagens_reduzidas')
chdir = images_dir + '\\' + 'Imagens_reduzidas'
... |
import os
from .PBX_Base_Reference import *
from ...Helpers import path_helper
class PBXLibraryReference(PBX_Base_Reference):
def __init__(self, lookup_func, dictionary, project, identifier):
super(PBXLibraryReference, self).__init__(lookup_func, dictionary, project, identifier);
| ||
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Founda | tion) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You ... |
"""
WSGI config for server project.
It ex | poses the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
from django.core.wsgi import get_wsgi_application
application ... | gi_application()
|
00000 | 0 output | /lattice.py.err
32074 1 output/lattice.py.out
|
# Verify leader-balanced
assert new_leader_imbal == 0
# Verify partitions-changed assignment
assert new_leaders_per_broker['0'] == 1
assert new_leaders_per_broker['1'] == 1
assert new_leaders_per_broker['2'] == 1
def test_rebalance_leaders_unbalanced_case2(
... | ct = create_cluster_topology | (assignment, broker_range(4))
cb = create_balancer(ct)
cb.rebalance_leaders()
# Verify balanced
leader_imbal = get_net_imbalance(
get_broker_leader_counts(ct.brokers.values()),
)
assert leader_imbal == 0
def test_rebalance_leaders_unbalanced_case2c(
... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | bazel run -c opt --config=cuda \
//third_party/tensorflow/python/ops/numpy_ops/benchmarks:micro_benchmarks -- \
--number=100 --repeat=100 \
--benchmarks=.
"""
from __future__ import absolute_import
fro | m __future__ import division
from __future__ import print_function
import gc
import time
from absl import flags
from absl import logging
import numpy as np # pylint: disable=unused-import
import tensorflow.compat.v2 as tf
from tensorflow.python.ops import numpy_ops as tfnp # pylint: disable=g-direct-tensorflow-i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.