prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/env python
"""
unit test for filters module
author: Michael Grupp
This file is part of evo (github.com/MichaelGrupp/evo).
evo 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 Li... | p.eye(3), np.array([0, 0, 0.9])),
lie.se3(np.eye(3), np.array([0, 0, 0.99])),
lie.se3(np.eye(3), np.array([0, 0, 0.999])) | ,
lie.se3(np.eye(3), np.array([0, 0, 0.9999])),
lie.se3(np.eye(3), np.array([0, 0, 0.99999])),
lie.se3(np.eye(3), np.array([0, 0, 0.999999])),
lie.se3(np.eye(3), np.array([0, 0, 0.9999999]))
]
POSES_4 = [
lie.se3(np.eye(3), np.array([0, 0, 0])),
lie.se3(np.eye(3), np.array([0, 0, 1])),
lie.... |
# 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
# d... | om alembic import op
import sqlalchemy as sa
import zun
def upgrade():
op.create_table(
'container',
sa.Colum | n('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('project_id', sa.String(length=255), nullable=True),
sa.Column('user_id', sa.String(length=255), nullable=True),
sa.Colum... |
import datetime
from tracker.models import Member, Report
from django.template.defaultfilters import slugify
import csv
import urllib
import simplejson as json
from dateutil.parser import *
import time
def update_twitter(branch='house', official=True, batch=1):
if official:
screen_names = [x.official_twit... | member, created = Member.objects.get_or_create(last_name=row['last'], first_name=row['first'], slug=slugify(row['first']+' '+row['last']), party=row['party'], branch=chamber, state=row['state'], district=row['district'])
if row['username'] != '':
member.official_facebook_name = row['username']
... | member.save()
elif row['username_campaign'] != '':
member.campaign_facebook_name = row['username_campaign']
member.save()
if row['twitter'] != '':
member.official_twitter_name = row['twitter']
member.save()
def update_from_al():
f = open("congre... |
tions for each source in the child
catalog.
"""
self.haystack = self.cat[[self.lon_col,
self.lat_col]].values
def _match(self):
"""
Match each source in the child catalog to the BGPS.
"""
self.matched_ix = {}
ids = se... | (bgps['uchii_f'] != 1)] = 0
bgps['sf_f'][(bgps['h2o_f'] == 1) |
(bgps['ch3oh_f'] == 1) |
(bgps['ir_f'] == 1) |
(bgps['uchii_f'] == 1)] = 1
return bgps
######################################################################## | #######
# Catalog Data Objects
###############################################################################
class WaterGbt(Data):
def __init__(self):
# Catalog parameters
self.name = 'h2o_gbt'
self.cat = catalog.read_cat('gbt_h2o')
self.lon_col = 'h2o_gl... |
baseInstance(BaseResource):
"""
This class represents a MySQL instance in the cloud.
"""
def __init__(self, *args, **kwargs):
super(CloudDatabaseInstance, self).__init__(*args, **kwargs)
self._database_manager = CloudDatabaseDatabaseManager(self.manager.api,
resource_clas... | e info for creating the user object,
# we have t | o do it manually.
return self._user_manager.find(name=name)
def delete_database(self, name_or_obj):
"""
Deletes the specified database. If no database by that name
exists, no exception will be raised; instead, nothing at all
is done.
"""
name = utils.get_nam... |
if to_add:
self.add_tags(to_add, auth=auth, save=save, log=log, system=system)
if to_remove:
self.remove_tags(to_remove, auth=auth, save=save)
def add_tags(self, tags, auth=None, save=True, log=True, system=False):
"""
Optimization method for use with update_tags. ... | s.ADDONS_AVAILABLE.index(config)
@property
def addons(self):
return self.get_addons()
def get_addons(self):
return filter(None, [
self.get_addon(config.short_name)
for config in self.ADDONS_AVAILABLE
])
def get_oauth_addons(self):
# TODO: Using ... | ses here causes a
# circular import error.
return [
addon for addon in self.get_addons()
if hasattr(addon, 'oauth_provider')
]
def has_addon(self, addon_name, deleted=False):
return bool(self.get_addon(addon_name, deleted=deleted))
def get_addon_na... |
TIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Requires Python 2.6+ and Openssl 1.0+
#
import socket
import glob
import mock
import traceback
import azurelinuxagent.common.osutil.default as osutil
import azurelin... | osutil.DefaultOSUtil.restart_if(osutil.DefaultOSUtil(), ifname=ifname, retries=retries, wait=0)
# assert
self.assertEqual(run_patch.call_count, retries)
self.assertEqual(run_patch.call_args_list[0][0][0], 'ifdown {0} && ifup {0}'.format(ifname))
def test_get_dvd_device_success... | ):
with patch.object(os, 'listdir', return_value=['cpu', 'notmatching']):
try:
osutil.DefaultOSUtil().get_dvd_device()
self.fail('OSUtilError was not raised')
except OSUtilError as ose:
self.assertTrue('notmatching' in ustr(ose))
@patc... |
# Patchwork - automated patch tracking system
# Copyright ( | C) 2016 Linaro Corporation
#
# SPDX-License-Identifier: GPL-2.0-or-later
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView
class IndexView(APIView):
def get(self, request, *args, **kwargs):
"""List API resources."""
r... | t=request),
'people': reverse('api-person-list', request=request),
'patches': reverse('api-patch-list', request=request),
'covers': reverse('api-cover-list', request=request),
'series': reverse('api-series-list', request=request),
'events': reverse('api-event-... |
import unittest
from unittest.mock import Mock
class Mailer:
def send_email(self, email, message):
raise NotImplementedError("Not implemented yet")
class DB:
def insert_user(self, user):
raise NotImplementedError("Not implemented yet")
class User:
def __init__(self, email, name):
... | test.TestCase):
TEST_EMAIL = 'student@campus.uib.es'
TEST_NAME = 'Student'
def testRegisterUser(self):
mock_db = Mock(DB)
mock_mailer = Mock(Mailer)
user = registerUser(self.TEST_EMAIL, self.TEST_NAME, mock_db, mock_mailer)
mock_db.insert_user.assert_ | called_once_with(user)
mock_mailer.send_email.assert_called_once_with(self.TEST_EMAIL, "Welcome")
self.assertIsInstance(user, User)
self.assertEqual(user.email, self.TEST_EMAIL)
self.assertEqual(user.name, self.TEST_NAME)
def testRegisterUserThrowsNotImplemented(self):
wit... |
/addons/plugin.program.jogosEmuladores',''))
CHECKVERSION = os.path.join(USERDATA,'version.txt')
KIDS = os.path.join(USERDATA,'kids.txt')
PROFILE = os.path.join(USERDATA,'profiles.xml')
LOCK = os.path.join(USERDATA,'lock.txt')
NOTICE = os.path.join(ADDON,'notice.txt')
WIPE = xbmc.translatePath('special://ho... | 'home'))
time.sleep(2)
unzip(lib,addonfolder)
sys.exit(1)
if nointernet == 0 and BetaUpdate == 0:
if auto == 'true':
if os.path.exists(CHECKVERSION):
checkurl = BetaTwo
vers = open(CHECKVERSION, "r")
regex = re.compile(r'<build>(.+?)</build><version>(.+?)</ | version>')
for line in vers:
currversion = regex.findall(line)
for build,vernumber in currversion:
if vernumber > 0:
req = urllib2.Request(checkurl)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
try:
re... |
from django.apps import AppConfig |
class CheckoutAppConfig(AppConfig):
name = 'ecommerce.extensions.checkout'
verbose_name = 'Checkout'
def ready(self):
super(CheckoutAppConfig, self).ready() |
# noinspection PyUnresolvedReferences
import ecommerce.extensions.checkout.signals # pylint: disable=unused-variable
|
"""
Created on November 20, 2019
This file is subject to the terms and conditions defined in the
file 'LICENSE.txt', whic | h is part of this source code package.
@author: David Moss
"""
# Section ID's
SECTION_ID_ALERTS = "alerts"
SECTION_ID_N | OTES = "notes"
SECTION_ID_TASKS = "tasks"
SECTION_ID_SLEEP = "sleep"
SECTION_ID_ACTIVITIES = "activities"
SECTION_ID_MEALS = "meals"
SECTION_ID_MEDICATION = "medication"
SECTION_ID_BATHROOM = "bathroom"
SECTION_ID_SOCIAL = "social"
SECTION_ID_MEMORIES = "memories"
SECTION_ID_SYSTEM = "system"
def add_entry(botengine, ... |
# -*- coding: utf-8 -*-
"""
Custom model managers for finan | ce.
"""
from .entity_manager import FinanceEntityMana | ger
__all__ = (
'FinanceEntityManager',
) |
#THIS IS /helicopter_providence/middletown_3_29_11/site1_planes/boxm2_site1_1/boxm2_create_scene.py
from boxm2WriteSceneXML import *
import optp | arse
from xml.etree.ElementTree import ElementTree
import os, sys
#Parse inputs
parser = optparse.OptionParser(description='Create BOXM2 xml file');
parser.add_option('--scene_info', action="store", dest="scene_info");
|
parser.add_option('--boxm2_dir', action="store", dest="boxm2_dir");
options, args = parser.parse_args();
boxm2_dir = options.boxm2_dir;
scene_info = options.scene_info;
if not os.path.isdir(boxm2_dir + '/'):
os.mkdir(boxm2_dir + '/');
print 'Parsing: '
print scene_info
print boxm2_dir
#parse ... |
from __future__ import absolute_import, unicode_literals
from django.http import HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from debug_toolbar.panels.sql.forms import SQLSelectForm
@csrf_exempt
def sql_select(request):
"""Returns the output of... | lt_error = "Profiling is either not available or not supported by your database."
cursor.close()
context = {
'result': result,
'result_error': result_er | ror,
'sql': form.reformat_sql(),
'duration': form.cleaned_data['duration'],
'headers': headers,
'alias': form.cleaned_data['alias'],
}
return render(request, 'debug_toolbar/panels/sql_profile.html', context)
return HttpResponseBadRequest('Form errors')... |
from dcgpy import expression_gdual_double as expression
from dcgpy import kernel_set_gdual_double as kernel_set
from pyaudi import gdual_double as gdual
# 1- Instantiate a random expression using the 4 basic arithmetic operations
ks = kernel_set(["sum", "diff", "div", "mul"])
ex = expression(inputs = 1,
... | med "x") and visualize the expression
in_sym = ["x"]
print("Expression:", ex(in_sym)[0])
# 3 - Print the simplified expression
print("Simplified expression:", ex.simplify(in_sym))
# 4 - Visualize the dCGP graph
ex.visualize(in_sym)
# 5 - Define a gdual number of value 1.2 and truncation order 2
x = gdual(1.2, "x", 2... | ression in x=1.2:", ex([x])[0])
print("Second derivative:", ex([x])[0].get_derivative([2]))
# 5 - Mutate the expression with 2 random mutations of active genes and print
ex.mutate_active(2)
print("Mutated expression:", ex(in_sym)[0])
|
import _plotly_utils.basevalidators
class BorderwidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="borderwidth",
parent_name="histogram2dcontour.co | lorbar",
**kwargs
):
super(BorderwidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
| min=kwargs.pop("min", 0),
role=kwargs.pop("role", "style"),
**kwargs
)
|
##parent_menu_widget.remove(menu_widget.get_submenu())
##else:
#if (1):
#parent_menu_widget.removeAction(menu_widget.menuAction())
#self.remove_actions_by_menu_name_id(menu_name_id)
#self.remove_separators_by_menu_name_id(menu_name_id)
#self.remove_submenus_by_menu_n... | []
#self.menu_indexes = []
#def clearMenu(self, menu_name_id):
#menu_index = self | .get_menu_index(menu_name_id)
#if menu_index < 0: return
#menu_widget = self.menu_indexes[menu_index][1]
##if TrayEngine == "KDE":
##menu_widget.clear()
##elif TrayEngine == "AppIndicator":
##for child in menu_widget.get_submenu().get_children():
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 João Pedro Rodrigues
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | rds in the PDB file.
"""
records = ('MODEL ', 'ATOM ', 'HETATM',
'ENDMDL', 'END ',
'TER ', 'CONECT')
for line in fhandle:
if line.startswith(records):
yield line
def main():
# Check Input
| pdbfh = check_input(sys.argv[1:])
# Do the job
new_pdb = keep_coordinates(pdbfh)
try:
_buffer = []
_buffer_size = 5000 # write N lines at a time
for lineno, line in enumerate(new_pdb):
if not (lineno % _buffer_size):
sys.stdout.write(''.join(_buffer))
... |
from clickFuUtils import cfAction
class osmViewMap(cfAction):
def __init__(self,iface):
cfAction.__init__(self,self.name(),iface)
return None
def name(self):
return "View OSM map"
def desc(self):
return "Goto Location on OpenStreetMap"
def createURL(self,lat,long):
... | rn url
class osmEditMap(cfAction):
def __init__(self,iface):
cfAction.__init__(self,self.name(),iface)
return None
def name(self):
return "Edit OSM with iD"
def desc(self):
return "Goto Location on OpenStreetMap and start editing with iD"
def createURL(self,lat,long):... | nit__(self,iface):
cfAction.__init__(self,self.name(),iface)
return None
def name(self):
return "Edit OSM with JOSM"
def desc(self):
return "Goto Location on OpenStreetMap and start editing with JOSM"
def createURL(self,lat,long):
url = "http://127.0.0.1:81... |
from django.conf import settings
# Safe User import for Django < 1.5
try:
from django.contrib.auth import | get_user_model
except ImportError:
from django.contrib.auth.models | import User
else:
User = get_user_model()
# Safe version of settings.AUTH_USER_MODEL for Django < 1.5
auth_user_model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | ',
'version': '0.1',
'author': 'OpusVL',
'website': 'http://opusvl.com/',
'summary': 'Allow company to present different branding on documents sent to different customers',
'description': """Allow company to present different branding on documents sent to different customers,
""",
'images':... | security/brand_groups.xml',
'security/ir.model.access.csv',
'res_partner_view.xml',
'res_company_brand_view.xml',
'res_company_view.xml',
'report_external_layout_modification.xml',
],
'demo': [
],
'test': [
],
'license': 'AGPL-3',
'installable': True,
... |
_path
def can_access_file(filePath):
'''test the existence of file'''
return os.access(filePath, os.F_OK)
def can_access_directory(destinationDirectory):
'''test readability, writability and executablility of directory'''
return os.access(destinationDirectory, os.R_OK | os.W_OK | os.X_OK)
def makedir... | ym:
if isDirectory(filePath):
| copytree(filePath, destination)
else:
shutil.copy(filePath, destination)
elif isDirectory(filePath):
copytree(filePath, destination, sym)
else:
error(_('ActionsAPI [copy]: File %s does not exist.') % filePath)
def copytree(source, destination, sym ... |
"""Workaround for formatting issue
Source: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html
"""
import decimal
import json
class Decimal | Encoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decim | al):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
|
reements. 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 use this file except in compliance
# with the License. You may obtain a copy of the License at
#... | ck.acquire()
try:
ok = port not in self._ports
if ok:
self._ports.add(port)
self._last_alloc = time.time()
finally:
self._lock.release()
| sock.close()
return port if ok else self._get_tcp_port()
def _get_domain_port(self):
port = random.randint(1024, 65536)
self._lock.acquire()
try:
ok = port not in self._dom_ports
if ok:
self._dom_ports.add(port)
finally:
self._lock.release()
return port if ok els... |
import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata... | st'
@pytest.fixture
def session():
Session = sessionmaker()
e | ngine = create_engine(MYSQL_CONNECTION_STRING)
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
mysqldb_hooks.install_patches()
try:
yield
finally:
... |
#
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# 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/.
#
# Copyright (C) 2011-2013 Star2Billing S.L.
#
# The Initia... | CampaignDelCascadeAPIPlayground(APIPlayground):
schema = {
"title": _("campaign delete cascade"),
"base_url": "http://localhost/api/v1/",
"resources": [
{
"name": "/campaign_delete_cascade/",
"description": _("this r | esource allows you to delete campaign."),
"endpoints": [
{
"method": "DELETE",
"url": "/api/v1/campaign_delete_cascade/{campaign-id}/",
"description": _("delete campaign"),
}
]... |
#!/usr/bin/env python3
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self,first,last):
self.first = first
self.last = last
self.email = first + '.' + last + '@kellynoah.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
def | apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
def __repr__(self):
return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay)
def __str__(self):
return '{} - {}'.format(self.fullname(), self.email)
de | f __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
emp_1 = Employee('John', 'Smith')
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())
|
#第四集(包含部分文件3.py和部分第二集)
# courses=['History','Math','Physics','Compsci']#此行代码在Mutable之前都要打开
# print(courses)
# courses.append('Art')#在最后添加一个元素
# courses.insert(0,'English')#在0的位置添加一个元素
# courses_2=['Chin | ese','Education']
# courses.insert(1,courses_2)#看看这条代码与下面两条代码有什么不同
# courses.append(courses_2)
# courses.extend(courses_2)
# #用pop删除和用remove删除可以详见3.py
# # courses.remove('Math')#删除一个元素
# popped=courses.pop()#删除一个元素并将该元素赋值给popped (括号内无数字则默认最后一个)
# print(popped)#输出被删除的元素
# courses.reverse()#将元素倒叙
# courses.sort()#排序 按... | orted_courses)
# alphabet=['DA1','SA2','AD3','3AD']
# alphabet.sort()
# print(alphabet)
# nums=[3,5,1,4,2]
# nums.sort()
# print(nums)
# print(min(nums))#输出最小数
# print(max(nums))#输出最大数
# print(sum(nums))#输出总和
# #中文不知道是什么规则
# Chinese=['啊了','吧即','啦']
# Chinese.sort()
# print(Chinese)
# print(courses.index('Math'))#查... |
om test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
from test import run_only
from mock import Mock
from diamond.collector import Collector
from elb import ElbCollector
def run_only_if_boto_is_available(func):
try:
import boto
except... | [{u'Timestamp': ts, u'Sum': 7.0, u'Unit': u'Count'}],
[{u'Timestamp': ts, u'Sum': 8.0, u'Unit': u'Count'}],
[{u'Timestamp': ts, u'Sum': 9.0, u'Unit': u'Count'}],
[{u'Timestamp': ts, u'Sum': 10.0, u'Unit': u'Count'}],
[{u'Timestamp': ts, u'Sum': 11.0, u'Unit': u'Count... | imestamp': ts, u'Sum': 12.0, u'Unit': u'Count'}],
[{u'Timestamp': ts, u'Maximum': 13.0, u'Unit': u'Count'}],
[{u'Timestamp': ts, u'Sum': 14.0, u'Unit': u'Count'}],
]
cloudwatch.connect_to_region = Mock()
cloudwatch.connect_to_region.return_value = cw_conn
collec... |
#!/usr/bin/env python
# -*- codin | g: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU | LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Blei's LDA-C format.
"""
from __future__ import with_statement
import logging
from gensim import interfaces, utils
from gensim.corpora import IndexedCorpus
logger = logging.getLogger('gensim.corpora.bleicorpus')
class BleiCorpus(IndexedCorpus):
"""
... |
# 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 ... | ': 'httpRequest', 'type': 'str'},
}
def __init__(self, tenant_id=None, subscription_id=None, resource_group=None, resource_provider=None, resource_uri=None, operation_name=None, status=None, authorization=None, claims=None, correlation_id=None, http_request=None):
super(ResourceWriteFailureData, s | elf).__init__()
self.tenant_id = tenant_id
self.subscription_id = subscription_id
self.resource_group = resource_group
self.resource_provider = resource_provider
self.resource_uri = resource_uri
self.operation_name = operation_name
self.status = status
sel... |
"""(Re)builds feeds for categories"""
import os
import datetime
import jinja2
from google.appengine.api import app_identity
import dao
import util
def build_and_save_for_category(cat, store, prefix):
"""Build and save feeds for category"""
feed = build_feed(cat)
save_feeds(store, feed, prefix, cat.key.id... | .lastBuildDate = None
self.latest_item_dt = datetime.datetime.utcfromtimestamp(0)
def add_item(self, item):
self.items.append(item)
if self.latest_item_dt < item.dt:
self.latest_item_dt = item.dt
def render_short_rss(self):
self.lastBuildDate = self.latest_item_dt
... | et_template('rss_short.xml')
return template.render(feed=self)
def make_jinja_env():
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader('templates'),
# loader=PackageLoader('package_name', 'templates'),
autoescape=True,
extensions=['jinja2.ext.autoescape']
... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Functions that deal with local and device ports."""
import contextlib
import fcntl
import httplib
import logging
import os
import socket
import trace... | ion_error_msgs:
client_error = ' | '.join(exception_error_msgs)
# Only returns last client_error.
return (False, client_error or 'Timeout')
|
# coding:utf-8
from urllib import parse as url_parse
from logger.log import crawler
from apps.celery_init import celery
from page_get.basic import get_page
from config.conf import get_max_search_page
from page_parse import search as parse_search
from db.search_words import get_search_keywords
from db.keywords_wbdata im... | url_parse.quote(keyword)
while cur_page < limit:
cur_url = url.format(encode_keyword, cur_page)
search_page = get_page(cur_url)
if not search_page:
crawler.warning('No result for keyword {}, the source page is {}'.format(keyword, search_page))
return
search_... | ed in mysql,
# we need not crawl the same keyword in this turn
for wb_data in search_list:
rs = get_wb_by_mid(wb_data.weibo_id)
if rs:
crawler.info('keyword {} has been crawled in this turn'.format(keyword))
return
else:
... |
from distutils.core import setup
from | ripwrap import __VERSION__
setup(
name = 'ripwrap',
version = __VERSION__,
description = 'A wrapper for ReSTinPeace, for Django applications.',
long_description = open('README').read()
author = 'P.C. Shyamshankar',
packages = ['ripwrap'],
url = 'http://github.com/sykora/django-ripwrap/', |
license = 'GNU General Public License v3.0',
classifiers = (
'Development Status :: 1 - Planning',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Program... |
at least one value is not NaT
# The cast currently succeeds, but the values are invalid:
cast._simple_strided_call((arr1, arr2))
with pytest.raises(ValueError):
str(arr2[-1]) # e.g. conversion to string fails
return
cast.... | me(self, from_dt, to_dt, expected_casting, nom, denom):
from_dt = np.dtype(from_dt)
if to_dt is not None:
to_dt = np.dtype(to_dt)
# Test a few values for casting (results generated with NumPy 1.19)
values = np.array([-2**63, 1, 2**63-1, 10000, -10000, 2**32])
values ... | t.byteorder))
assert values.dtype.byteorder == from_dt.byteorder
assert np.isnat(values.view(from_dt)[0])
DType = type(from_dt)
cast = get_castingimpl(DType, DType)
casting, (from_res, to_res) = cast._resolve_descriptors((from_dt, to_dt))
assert from_res is from_dt
... |
from unittest import TestCase |
from cloudshell.cp.vcenter.network.vlan.factory import VlanSpecFactory
class TestVlanSpecFactory(TestCase):
def test_get_vlan_spec(self):
vlan_spec_factory = VlanSpecFactory()
vlan_spec = vlan_spec_factory.get_vlan_spec('Access')
| self.assertIsNotNone(vlan_spec)
|
# Austin Jenchi
| # 1/30/2015
# 8th Period
# Paycheck
print "Welcome to How to Job"
print
wage_per_hour = raw_input("How much is your hourly wage? ==> $")
if not wage_per_hour == "":
try:
wage_per_hour = float(wage_per_hour)
except:
wage_per_hour = 12.00
else:
wage_per_hour = 12.00
print "Your pay is $%2.2f ... | .2f" % total_wage
print
print "After taxes of 23%%, your total pay is $%2.2f." % (total_wage * .23)
print
print "After paying your union fees, you recieved a measly $%2.2f of your previous $%2.2f." % ((total_wage * .23) - 25, total_wage)
|
"""
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import os
import posixpath
from django.conf import settings
from django.http import HttpRespo... | .eot', '.woff', '.woff2')):
response['Access-Control-Allow-Origin'] = '*'
# If we have a version and not DEBUG, we can cache it FOREVER
if version is not None and not settings.DEBUG:
response['Cache-Control'] = | FOREVER_CACHE
else:
# Otherwise, we explicitly don't want to cache at all
response['Cache-Control'] = NEVER_CACHE
return response
class TemplateView(BaseTemplateView):
def render_to_response(self, context, **response_kwargs):
return render_to_response(
request=self.re... |
# 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
# d... | gate_id_idx',
'aggregate_id'),
mysql_engine='InnoDB',
mysql_charset='latin1'
)
for table in [resource_providers, inventories, allocations,
resource_provider_aggregates]:
table.creat | e(checkfirst=True)
|
#!/usr/bin/env python
import os
import sys
from optparse import OptionParser
from jobTree.src.bioio import logger, setLoggingFromOptions
from jobTree.scriptTree.stack import Stack
from margin.mappers.last import Last, LastChain, LastRealign
from margin.mappers.bwa import Bwa, BwaChain, BwaRealign
from margin.mappers.gr... | if (options.bwa):
mapper = BwaRealign;
if (options.graphmap):
mapper = GraphMapRealign;
| if (options.graphmapanchor):
mapper = GraphMapAnchorRealign;
#This line invokes jobTree
i = Stack(mapper(readFastqFile=args[0], referenceFastaFile=args[1], outputSamFile=args[2],
options=options)).startJobTree(options)
#The return value of the jobtree scr... |
from ray.rllib.utils.deprecation import deprecation_warning
deprecation_w | arning(
old="ray/rllib/examples/recsim_with_slateq.py",
new="ray/rllib/examples/recommender_sy | stem_with_recsim_and_slateq.py",
error=True,
)
|
import networkx
from yaiep.graph.Node import Node
##
# Classe che rappresenta l'intero spazio di ricerca che viene
# generato via via che il metod | o di ricerca ispeziona nuovi nodi
#
class SearchGraph(networkx.DiGraph):
##
# Crea il grafo di ricerca come un grafo direzionato
# il quale ha come nodo iniziale lo stato iniziale
# dal quale il metodo di ricerca partirà per poter esplorare
# lo spazio delle soluzioni
#
# @param init_state s... | def __init__(self, init_state):
networkx.DiGraph.__init__(self)
self._init_state = Node(init_state.copy(), None)
# inserisci lo stato iniziale a partire dal quale ispezionare lo spazio di ricerca
self.add_node(self._init_state)
##
# Restituisce il riferimento allo stato inizial... |
)
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones... | #html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain c... | If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps doc... |
import math
def isPrime(num):
if num < 2:
return False # 0, 1不是质数
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根
boundary = int(math.sqrt(num)) + 1
for i in range(2, boundary):
if num % i == 0:
return False
return True
def primeSieve(size):... | sieve[0] = False
sieve[1] = True
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 |
boundary = int(math.sqrt(size)) + 1
for i in range(2, boundary):
pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数
while pointer < size:
sieve[pointer] = False
pointer += i
ret = [] # contains all the prime number within "size"
for i in ran... |
import unittest
from graph_theory.spfa import spfa
class GraphTheoryTests(unittest.TestCase):
def setUp(self):
source = 0
num_nodes = 5
neighbour_list = [[1], # 0
| [2], # 1
[3], # 2
[4, 1], # 3
[1], # 4
]
weights = {(0,1): 20,
(1,2) : 1,
(2,3) : 2,
(3,4) : -2,
| (4, 1): -1,
(3, 1): -4,
}
self.example_graph = (source, num_nodes, weights, neighbour_list)
self.example_graph_cycle = [1,2,3]
def is_cyclicily_equal(self, list1, list2):
if len(list1) != len(list2):
return False
... |
= self.size
ec2 = self.get_ec2_connection()
if self.zone_name == None or self.zone_name == '':
# deal with the migration case where the zone is not set in the logical volume:
current_volume = ec2.get_all_volumes([self.volume_id])[0]
self.zone_name = current_volume.zon... | return None
ec2 = self.get_ec2_connection()
ec2.detach_volume(self.volume_id, self.server.instance_id, self.device, force)
self.server = None
self.put()
def checkfs(self, use_cmd=None):
if self.server == No | ne:
raise ValueError, 'server attribute must be set to run this command'
# detemine state of file system on volume, only works if attached
if use_cmd:
cmd = use_cmd
else:
cmd = self.server.get_cmdshell()
status = cmd.run('xfs_check %s' % self.device)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1. | 9.11 on 2017-05-10 15:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sessao', '0001_initial'),
]
operations = [
migrations.AddField(
model_na | me='sessaoplenaria',
name='interativa',
field=models.NullBooleanField(choices=[(True, 'Sim'), (False, 'Não')], verbose_name='Sessão interativa'),
),
]
|
# | Copyright (c) 2017 https://github.com/ping
#
| # This software is released under the MIT License.
# https://opensource.org/licenses/MIT
__version__ = '0.3.9'
|
]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$'),
"agentPoolName": _SERIALIZER.url("agent_pool_name", agent_pool_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_paramete... | gth=1),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=1, pattern=r'^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$'),
"agentPoolName": _SERIALIZER.url("agent_pool_name", agent_pool_name, 'str'),
}
url = _format_ | url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dic... |
ath")
def esc_uscores(self, string):
if string:
return string.replace("_", "\_")
else:
return
def exclude_builtins(self, classes, module):
new_classes = []
for cls in classes:
if module in cls[1].__module__:
... | r):
bl_idname = | "fd_api_doc.create_content_overview"
bl_label = "Create Fluid Content Overview Documentation"
INCLUDE_FILE_NAME = "doc_include.txt"
write_path = bpy.props.StringProperty(name="Write Path", default="")
elements = []
package = None
def write_html(self):
pass
def rea... |
# -*- coding: utf-8 -*-
# Copyright (C) 2009, 2013-2015 Rocky Bernstein
#
# 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 ve... | o = curframe.f_lineno
elif len(args) == 2:
(modfunc, filename, lineno) = self.proc.parse_position(args[1])
if in | spect.ismodule(modfunc) and lineno is None and len(args) > 2:
val = self.proc.get_an_int(args[1],
'Line number expected, got %s.' %
args[1])
if val is None: return
lineno = val
... |
# choco/ui.py
# Copyright (C) 2006-2016 the Choco authors and contributors <see AUTHORS file>
#
# This module is part of Choco and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re
import os
import posixpath
from choco import errors
from choco import util
from choco.ru... | ``uri``.
.. note:: The ``relativeto`` argument is not supported here at
the moment.
"""
# the spefical ui uri with prefix "url://"
uiuri = "ui#" + uri
try:
if self.lookup.filesystem_che | cks:
return self.lookup.check(uiuri, self.lookup.collection[uiuri])
else:
return self.lookup.collection[uiuri]
except KeyError:
u = re.sub(r'^\/+', '', uri)
for dir in self.ui_paths:
# make sure the path seperators are posix - o... |
#!/usr/bin/env python
# coding=utf-8
# Furry Text Escape 2 main script
gamevers = ('v1.0')
n = ('null')
tprint1 = ('1')
tprint2 = ('1')
while n.strip()!="4":
if tprint1==('1'):
t = open('./art/title1.TCR', 'r')
tcr_contents = t.read()
print (chr(27) + "[2J" + chr(27) + "[H" + tcr_contents)
t.close()
tprint... | rint (chr(27) + "[2J" + chr(27) + "[H" + tcr_contents + '''"which way?"''')
t.close()
tprint2 = ('0')
print (
'''episode selection:
1: episode 1: maintenance duties (RED)
: episode 2 -coming soon- (BLUE)
: episode 3 -coming soon- (GREEN)
4: BONUS! Playable flashback to Furry Text Escape 1!
5: return t... | 27) + "[H")
execfile("EP1-intro.py")
execfile("EP-1.py")
execfile("EP1-outro.py")
print(chr(27) + "[2J" + chr(27) + "[H")
tprint2 = ('1')
if episodeselection=="4":
print(chr(27) + "[2J" + chr(27) + "[H")
execfile("DARKROOM.py")
print(chr(27) + "[2J" + chr(27) + "[H")
tprint2 = ('1... |
re all separated by pipe (|) characters."
_iso639_contents = load_file_in_same_dir(__file__, 'ISO-639-2_utf-8.txt')
# drop the BOM from the beginning of the file
_iso639_contents = _iso639_contents[1:]
language_matrix = [ l.strip().split('|')
for l in _iso639_contents.strip().split('\n') ]
# upd... | : ('pt', 'br'),
'pob': ('pt', 'br'),
'br': ('pt', 'b | r'),
'brazilian': ('pt', 'br'),
'català': ('cat', None),
'cz': ('cze', None),
'ua': ('ukr', None),
'cn': ('chi', None),
'chs': ('chi', None),
'jp': ('jpn', None),
'scr'... |
#
# (c) 2017, Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is... | .write(contents)
return filename
def _handle_template(self):
src = self._task.args.get('src')
working_path = self._get_working_path()
if os.path.isabs(src) or urlsplit('src').scheme:
source = src
else:
source = self._loader.path_dwim_relative(working... | not source:
source = self._loader.path_dwim_relative(working_path, src)
if not os.path.exists(source):
raise ValueError('path specified in src not found')
try:
with open(source, 'r') as f:
template_data = to_text(f.read())
except IOError... |
import scipy.stats as estad
from tikon.ecs.aprioris import APrioriDist
from tikon.ecs.árb_mód import Parám
from tikon.móds.rae.orgs.ecs.repr._plntll_ec import EcuaciónReprCoh
class N(Parám):
nombre = 'n'
líms = (0, None)
unids = None
apriori = APrioriDist(estad.expon(scale=500))
class A(Parám):
| nombre = 'a'
líms = (0, None)
unids = None
apriori = APrioriDist(estad. | expon(scale=100))
class B(Parám):
nombre = 'b'
líms = (0, None)
unids = None
apriori = APrioriDist(estad.expon(scale=100))
class C(Parám):
nombre = 'c'
líms = (0, 1)
unids = None
class Triang(EcuaciónReprCoh):
nombre = 'Triang'
cls_ramas = [N, A, B, C]
_cls_dist = estad.tri... |
"""
WSGI config for Courseware project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://doc | s.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Courseware.settings")
from djang | o.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
import _plotly_utils.basev | alidators
class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="tickvals", parent_name="mesh3d.colorbar", **kwargs):
super(TickvalsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=... | )
|
#!/usr/bin/python
"""Updates the timezone data held in bionic and ICU."""
import ftplib
import glob
import httplib
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
regions = ['africa', 'antarctica', 'asia', 'australasia',
'etcetera', 'europe', 'northamerica', '... | a_filename
print 'Downloading data...'
HttpRetrieveFile(http, path, data_filename)
print 'Downloading signature...'
signature_filename = '%s.asc' % data_filename
HttpRetrievefile(http, "%s.asc" % path, signature_filename)
def BuildIcuToolsAndDa | ta(data_filename):
# Keep track of the original cwd so we can go back to it at the end.
original_working_dir = os.getcwd()
# Create a directory to run 'make' from.
icu_working_dir = '%s/icu' % original_working_dir
os.mkdir(icu_working_dir)
os.chdir(icu_working_dir)
# Build the ICU tools.
print 'Config... |
def splice(alists, recycle = True):
"""
Accepts a list of nonempty lists or indexable objects in
argument alists (each element list may not be of the same
length) and a keyword argument recycle which
if true will reuse elements in li | sts of shorter length.
Any error will result in an empty list to be returned.
"""
| try:
nlists = len(alists)
lens = [len(alist) for alist in alists]
if not recycle:
totlen = sum(lens)
else:
totlen = max(lens) * nlists
pos = [0] * nlists
R = [None] * totlen
i, j = 0, 0
while i < totlen:
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'FacebookProfile.polls'
db.add_column(u'socialplatform_facebookprofile', 'polls',
... | ForeignKey', [], {'to': u"orm['auth.User']"}),
'text': ('django.db.models.fields.TextField', [], {})
},
u'socialplatform.tweet': {
'Meta': {'object_name': 'Tweet'},
'content': ('django.db.models.fields.CharFi | eld', [], {'max_length': '140'}),
'created': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tweet_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm[... |
#
# 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... | ANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Add ``dag_code`` table
Revision ID: 952da73b5eff
Revises: 852ae6c715af
Create Date: 2020-03-12 12:39:01.797462
"""
import sqlalchemy as sa
from al... | vision = '952da73b5eff'
down_revision = '852ae6c715af'
branch_labels = None
depends_on = None
airflow_version = '1.10.10'
def upgrade():
"""Create DagCode Table."""
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SerializedDagModel(Base):
__tablename__... |
# Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This p... | ]
for entry in list_entries:
index, octets = entry.split(' ')
conn.retr(index)
conn.dele(index)
logger.debug('Found and deleted {0} messages on {1}'.format(len(list_entries), server_host)) |
conn.quit()
session.did_complete = True
finally:
session.all_done = True
session.end_session()
if conn:
try:
conn.file.close()
except Exception:
pass
try:
... |
Y KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Python utilities required by Keras."""
from __future__ import absolute_import
from __future__ impo... | e + ':' +
| function_name)
return fn
else:
raise ValueError('Could not interpret serialized ' + printable_module_name +
': ' + identifier)
def func_dump(func):
"""Serializes a user defined function.
Arguments:
func: the function to serialize.
Returns:
A tuple `(code,... |
.conference.endpoint,
)
def make_context(self, **kwargs):
data = {
'attachment-count': '1',
'attachment-1': (self.attachment, 'attachment-1'),
'X-Mailgun-Sscore': 0,
'recipient': self.recipient,
| 'stripped-text': self.body,
}
data.update(kwargs.pop('data', {}))
retu | rn super(TestProvisionNode, self).make_context(data=data, **kwargs)
def test_provision(self):
with self.make_context():
msg = message.ConferenceMessage()
utils.provision_node(self.conference, msg, self.node, self.user)
assert_true(self.node.is_public)
assert_in(self.... |
# Copyright 2014 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 logging
import os
import signal
import subprocess
import sys
import tempfile
from profile_chrome import controllers
from profile_chrome import ui
fr... | num=signal.SIGINT)
self._perf_process.wait()
self._perf_control.SetDefaultPerfMode()
def _FailWithLog(self, msg):
self._log_file.seek(0)
log = self._log_file.read()
raise RuntimeError('%s. Log output:\n%s' % (msg, log))
def PullResult(self, output_path):
if not self._device.FileExists(self... | ut_file.name))
self._device.PullFile(self._output_file.name, perf_profile)
if not os.stat(perf_profile).st_size:
os.remove(perf_profile)
self._FailWithLog('Perf recorded a zero-sized file')
self._log_file.close()
self._output_file.close()
return perf_profile
class PerfProfilerControll... |
# encoding: utf-8
import os
import re
import shutil
import subprocess
import tempfile
import textwrap
import time
from test.constant import (ARR_D, ARR_L, ARR_R, ARR_U, BS, ESC, PYTHON3,
SEQUENCES)
def wait_until_file_exists(file_path, times=None, interval=0.01):
while times is None o... | time.sleep(.05)
class VimInterfaceTmux(VimInterface):
def __init__(self, vim_executable, session): |
VimInterface.__init__(self, vim_executable, 'Tmux')
self.session = session
self._check_version()
def send(self, s):
# I did not find any documentation on what needs escaping when sending
# to tmux, but it seems like this is all that is needed for now.
s = s.replace(... |
self.reminderUnitBox = QtGui.QComboBox(self.basicReminderWidget)
self.reminderUnitBox.setEnabled(False)
self.reminderUnitBox.setMinimumSize(QtCore.QSize(110, 0))
self.reminderUnitBox.setObjectName("reminderUnitBox")
self.horizontalLayout.addWidget(self.reminderUnitBox)
self.r... | l_8.setBuddy(self.accessBox)
self.retranslateUi(CalendarEntryEdit)
self.reminderStack.setCurrentIndex(0)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), CalendarEntryEdit.accept)
| QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), CalendarEntryEdit.reject)
QtCore.QObject.connect(self.reminderCheckBox, QtCore.SIGNAL("toggled(bool)"), self.reminderTimeBox.setEnabled)
QtCore.QObject.connect(self.reminderCheckBox, QtCore.SIGNAL("toggled(bool)"), self.reminderUn... |
# Copyright 2019 Pants project c | ontributors (see CONTRIBUTORS.md).
# Licensed under the Apach | e License, Version 2.0 (see LICENSE).
"""Create AWS Lambdas from Python code.
See https://www.pantsbuild.org/docs/awslambda-python.
"""
from pants.backend.awslambda.python import rules as python_rules
from pants.backend.awslambda.python.target_types import PythonAWSLambda
from pants.backend.awslambda.python.target_t... |
"""
Author: Dr. John T. Hwang <hwangjt@umich.edu>
This package is distributed under New BSD license.
Full-factorial sampling.
"""
import numpy as np
from smt.sampling_methods.sampling_method import SamplingMethod
class FullFactorial(SamplingMethod):
def _initialize(self):
self.options.declare(
... | nput space.
"""
xlimits = self.options["xlimits"]
nx = xlimits.shape[0]
if self.options["weights"] is None:
weights = np.ones(nx) / nx
else:
weights = np.atleast_1d(self.options["weights"])
weights /= np.sum(weights)
num_list = np.one... | ] += 1
lins_list = [np.linspace(0.0, 1.0, num_list[kx]) for kx in range(nx)]
x_list = np.meshgrid(*lins_list, indexing="ij")
if self.options["clip"]:
nt = np.prod(num_list)
x = np.zeros((nt, nx))
for kx in range(nx):
x[:, kx] = x_list[kx].reshape(np.pro... |
# -*- coding: utf-8 -*-
# Copyright 2009 James Hensman
# Licensed under the Gnu General Public license, see COPYING
#from numpy import matlib as ml
import numpy as np
from scipy import linalg
class PCA_EM_matrix:
def __init__(self,data,target_dim):
"""Maximum likelihood PCA by the EM algorithm"""
self.X = ml.matr... | .sum([x*x.T for x in self.X2])#precalculate for speed
#initialise paramters:
self.W = ml.randn(self.d,self.q)
self.sigma2 = 1.2
f | or i in range(niters):
#print self.sigma2
self.E_step()
self.M_step()
def E_step(self):
M = self.W.T*self.W + ml.eye(self.q)*self.sigma2
M_inv = ml.linalg.inv(M)
self.m_Z = (M_inv*self.W.T*self.X2.T).T
self.S_z = M_inv*self.sigma2
def M_step(self):
zzT = self.m_Z.T*self.m_Z + self.N*self.S_z
sel... |
from twisted.internet import error as TxErrors
import couchbase._libcouchbase as LCB
from couchbase._libcouchbase import (
Event, TimerEvent, IOEvent,
LCB_READ_EVENT, LCB_WRITE_EVENT, LCB_RW_EVENT,
PYCBC_EVSTATE_ACTIVE,
PYCBC_EVACTION_WATCH,
PYCBC_EVACTION_UNWATCH,
PYCBC_EVACTION_CLEANUP
)
cla... | __slots__ = ['_txev', 'lcb_active']
def __init__(self):
super(TxTimer, self).__init__()
self.lcb_active = False
self._txev = None
def _timer_wrap(self):
if not self.lcb_active:
| return
self.lcb_active = False
self.ready(0)
def schedule(self, usecs, reactor):
nsecs = usecs / 1000000.0
if not self._txev or not self._txev.active():
self._txev = reactor.callLater(nsecs, self._timer_wrap)
else:
self._txev.reset(nsecs)
... |
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-built | in,wrong-import-position,wildcard-import,useless-suppression | ,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('certificates.apps', 'lms.djangoapps.certificates.apps')
from lms.djangoapps.certificates.apps import *
|
# Copyright (c) 2021, CRS4
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribu... | r sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE | SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
#... |
fo_by_enp, match_patient_by_snils, get_dn_info_by_enp
from users.models import DoctorProfile
from utils.common import values_as_structure_data
from utils.data_verification import data_parse
from utils.dates import normalize_date, valid_date, try_strptime
from utils.xh import check_type_research, short_fio_dots
from . i... | = [int(i) for i in type_researches.split(',')]
else:
is_research = -1
if only_signed == '1':
# TODO: вернуть только подписанные и как дату next_time использовать дату подписания, а не подтверждения
# признак – eds_total_signed=True, датавремя полного подписания eds_total_signed_at
... | ext_n) or []
else:
dirs = sql_if.direction_collect(d_start, researches, is_research, next_n) or []
next_time = None
naprs = [d[0] for d in dirs]
if dirs:
next_time = dirs[-1][3]
return Response({"next": naprs, "next_time": next_time, "n": next_n, "fromPk": from_pk, "afterDate": aft... |
cation.address)
self.assertEqual(10.0, loc[0].location.latitude)
self.assertEqual(10.0, loc[0].location.longitude)
alchemy.match(loc[0], session, {"city": u"Frisco"}, keepexisting=True)
self.assertEqual("Frisco, OH, US", loc[0].location.address)
self.assertEqual(10.0, loc[0].loc... | tion, session)
self.assertEqual(1, session.query(Location).count())
self.assertEqual(0, session.query(locationinventor).count())
def test_unmatch_lawyer(self):
law = session.query(RawLawyer).limit(20)
alchemy.match(law, session)
alchemy.unmatch(law[0], session)
self... | est_assigneematch(self):
# blindly assume first 10 are the same
asg0 = session.query(RawAssignee).limit(10)
asg1 = session.query(RawAssignee).limit(10).offset(10)
asgs = session.query(Assignee)
alchemy.match(asg0, session)
alchemy.match(asg1, session)
# create t... |
, target=column, body="I'm the second")
text_breadcrumbs = text_plugin.get_breadcrumb()
self.assertEqual(len(columns.get_breadcrumb()), 1)
self.assertEqual(len(column.get_breadcrumb()), 2)
self.assertEqual(len(text_breadcrumbs), 3)
self.assertTrue(text_breadcrumbs[0]['title'], co... | xt.body)
def test_copy_plugins_method(self):
"""
Test that CMSPlugin copy does not have side effects
"""
# create some objects
page_en = api.create_page("CopyPluginTestPage (EN)", "nav_playground.html", "en")
page_de = api.create_page("CopyPluginTestPage (DE)", "nav_... | text_plugin_en = api.add_plugin(ph_en, "TextPlugin", "en", body="Hello World")
self.assertEqual(text_plugin_en.pk, CMSPlugin.objects.all()[0].pk)
# add a *nested* link plugin
link_plugin_en = api.add_plugin(ph_en, "LinkPlugin", "en", target=text_plugin_en,
... |
# -*- coding: utf-8 -*-
"""
Unit tests for embargo app admin forms.
"""
from __future__ import absolute_import
import six
# Explicitly import the cache from ConfigurationModel so we can reset it after each test
from config_models.models import cache
from django.test import TestCase
from opaque_keys.edx.locator import... |
self.assertFalse(form.is_valid())
msg = 'COURSE NOT FOUND'
self.assertIn(msg, form._errors['course_key'][0]) # | pylint: disable=protected-access
with self.assertRaisesRegexp(
ValueError, "The RestrictedCourse could not be created because the data didn't validate."
):
form.save()
class IPFilterFormTest(TestCase):
"""Test form for adding [black|white]list IP addresses"""
def tea... |
"""Implementation of allocation API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import un | icode_literals
import logging
from treadmill import discovery
from treadmill import context
_LOGGER = logging.getLogger(__name__)
class API:
"""Treadmill Local REST api."""
def __init__(self):
def _get(hostname):
"""Get hostname nodeinfo endpoint info | ."""
_LOGGER.info('Redirect: %s', hostname)
discovery_iter = discovery.iterator(
context.GLOBAL.zk.conn,
'root.%s' % hostname, 'nodeinfo', False
)
for (_app, hostport) in discovery_iter:
if not hostport:
... |
#----------------------------------------------------------------------
#This utility sets up the python configuration files so as to
#allow Python to find files in a specified directory, regardless
#of what directory the user is working from. This is typically
#used to create a directory where the user will put resou... | l startup files
print 'This is a Linux or Mac system. Adding path to shell startup scripts'
#
#csh script: (Note, should als | o do this for .tcshrc if it exists)
cshFile = os.path.join(home,'.cshrc')
print 'csh family -- Editing '+cshFile
#Make backup copy of file
os.system('cp %s %s'%(cshFile,cshFile+'.setPathBackup'))
#Append line to set PYTHONPATH
outfile = open(cshFile,'a')
outfile.write('#Line added by setPath... |
import subprocess
import os
class CommandRunner:
HOST_LIST_TO_RUN_LOCAL = ["localhost", "127.0.0.1"]
def __init__(self, local_hostname, logger):
logger.debug("Creating CommandRunner with Args - local_hostname: {local_hostname}, logger: {logger}".format(**locals()))
self.local_hostname = loca... | _failover_controller fails the child process will fail as well. (unless you're running the systemctl command)
def _run_local_command(self, base_command):
self.logger.debug("Running command as Local command")
output = os.popen(base_command).read()
if output:
output = output.split(... | utput))
return True, output
def _run_ssh_command(self, host, base_command):
self.logger.debug("Running command as SSH command")
if base_command.startswith("sudo"):
command_split = ["ssh", "-tt", host, base_command]
else:
command_split = ["ssh", host, base_com... |
import logging
import ibmsecurity.utilities.tools
logger = logging.getLogger(__name__)
module_uri = "/isam/felb/configuration/services/"
requires_modules = None
requires_versions = None
requires_model = "Appliance"
def add(isamAppliance, service_name, name, value, check_mode=False, force=False):
"""
Creates... | equires_versions,
requires_model=requires_model)
else:
return isamAppliance.create_return_object | (warnings=warnings)
def set(isamAppliance, service_name, attribute_name, attribute_value, check_mode=False, force=False):
"""
Determines if add or update is called
"""
check_value, warnings = _check(isamAppliance, service_name, attribute_name)
if check_value is False:
return add(isamAppl... |
#
# 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 us... | def set(self, x=None, other=None, other_x=Non | e):
if "other" in self._input_kwargs:
self._input_kwargs["other"].set(x=self._input_kwargs["other_x"])
self._x = self._input_kwargs["x"]
a = Setter()
b = Setter()
a.set(x=1, other=b, other_x=2)
self.assertEqual(a._x, 1)
self.as... |
# -*- coding: utf-8 -*-
from harpia.model.connectionmodel import ConnectionModel as ConnectionModel
from harpia.system import System as Sys | tem
class DiagramModel(object):
# ----------------------------------------------------------------------
def __init__(self):
self.last_id = 1 # first block is n1, increments to each new block
self.blocks = {} # GUI blocks
self.connectors = []
self.zoom = 1.0 # pixels per uni... | d"
self.modified = False
self.language = None
self.undo_stack = []
self.redo_stack = []
# ----------------------------------------------------------------------
@property
def patch_name(self):
return self.file_name.split("/").pop()
# --------------------------------... |
# -*- coding: UTF-8 -*-
# Copyright 2019-2020 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
from django.db import models
from lino_xl.lib.ledger.choicelists import VoucherStates
from lino.api import dd, _
class OrderStates(VoucherStates):
pass
add = OrderStates.... | _("Active"), 'active', is_editable=True)
add('30', _("Urgent"), 'urgent', is_editable=True)
add('4 | 0', _("Done"), 'registered')
add('50', _("Cancelled"), 'cancelled')
OrderStates.draft.add_transition(required_states="active urgent registered cancelled")
OrderStates.active.add_transition(required_states="draft urgent registered cancelled")
OrderStates.urgent.add_transition(required_states="draft active registered ca... |
)))
if update_ops_in_cross_replica_mode:
fetches += tuple(ops.get_collection(ops.GraphKeys.UPDATE_OPS))
return control_flow_ops.group(fetches)
iterator = self._get_iterator(distribution.distribute_dataset(dataset_fn))
def run_step():
return distribution.run_steps_on_datas... | return optimizer.minimize(loss_fn())
def dataset_fn():
features = dataset_ops.Dataset.from_tensors([[2.], [7.]])
labels = dataset_ops.Dataset.from_tensors([[6.], [21.]])
return dataset_ops.Dataset.zip((features, labels)).repeat()
def step_fn(ctx, inputs):
del ctx # Unu... | distribution.call_for_each_replica(model_fn, args=(inputs,)))
iterator = self._get_iterator(distribution.distribute_dataset(dataset_fn))
def run_step():
return distribution.run_steps_on_dataset(
step_fn, iterator, iterations=1).run_op
self.evaluate(distribution.initialize())
... |
from django.conf im | port settings
from django.utils.translation import gettext_lazy as _
ASSIGNMENT_ANY = 0
ASSIGNMENT_MATCH = 1
ASSIGNMENT_EXCEPT = 2
ASSIGNMENT_CHOICES = (
(ASSIGNMENT_ANY, _("any")),
(ASSIGNMENT_MATCH, _("matches")),
(ASSIGNMENT_EXCEPT, _("don't match")),
)
DJANGO_ADMIN_SSO_ADD_LOGIN_BUTTON = getattr(
... | settings, "DJANGO_ADMIN_SSO_OAUTH_CLIENT_ID", None
)
DJANGO_ADMIN_SSO_OAUTH_CLIENT_SECRET = getattr(
settings, "DJANGO_ADMIN_SSO_OAUTH_CLIENT_SECRET", None
)
DJANGO_ADMIN_SSO_AUTH_URI = getattr(
settings, "DJANGO_ADMIN_SSO_AUTH_URI", "https://accounts.google.com/o/oauth2/auth"
)
DJANGO_ADMIN_SSO_TOKEN_URI = ... |
#!/usr/bin/env python
#
# Copyright 2005,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your opt... | Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest
import audio_alsa
class qa_alsa (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block (... | self.tb = None
def test_000_nop (self):
"""Just see if we can import the module...
They may not have ALSA drivers, etc. Don't try to run anything"""
pass
if __name__ == '__main__':
gr_unittest.main ()
|
# cod | ing=utf-8
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado | .ioloop import IOLoop
from app import app
if __name__ == "__main__":
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
|
and only behavior with templates.
template_exists = os.path.isfile(self.template)
if not template_exists and self._manifest_is_not_generated():
self.read_manifest()
self.filelist.sort()
self.filelist.remove_duplicates()
return
if not template_exi... | % self.manifest)
return
content = self.filelist.files[:]
content.insert(0, '# file GENERATED by distutils, do NOT edit')
self.execute(file_util.write_file, (self.manifest, content),
| "writing manifest file '%s'" % self.manifest)
def _manifest_is_not_generated(self):
# check for special comment used in 3.1.3 and higher
if not os.path.isfile(self.manifest):
return False
fp = open(self.manifest)
try:
first_line = fp.readline()
fin... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import re
import waffle
from djan | go.conf import settings
from django.shortcuts import redirect |
class SoftLaunchMiddleware(object):
def __init__(self):
self.redirect_url = getattr(settings, 'SOFT_LAUNCH_REDIRECT_URL', '/')
regexes = getattr(settings, 'SOFT_LAUNCH_REGEXES', [])
self.regexes = [re.compile(r) for r in regexes]
def process_view(self, request, view_func, view_args, ... |
# -*- coding: utf-8 -*- |
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from django.core.files imp | ort File
from six import with_metaclass
from django.utils.module_loading import import_string
from rest_framework_tus import signals
from .settings import TUS_SAVE_HANDLER_CLASS
class AbstractUploadSaveHandler(with_metaclass(ABCMeta, object)):
def __init__(self, upload):
self.upload = upload
@abstr... |
[ {"desc": "desc", "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]}])
assert_raises_rpc_error(-8, "Range specified as [begin,end] must not have begin after end", self.nodes[0].scantxoutset, "start", [ {"desc": "desc", "range": [2, 1]}])
assert_raises_rpc_error(-8, "Range is too large", self.nodes[0].... | des[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0'/*h)", "range": 1500}])['total_amount'], Decimal("0.056"))
assert_equal(self.nodes[0].scantxout | set("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0'/*)", "range": 1499}])['total_amount'], Decimal("0.192"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8G... |
"""
Examples of Wavelets
--------------------
Figure 10.9
Wavelets for several values of wavelet par | ameters Q and f0. Solid lines show
the real part and dashed lines show the imaginary part (see eq. 10.16).
"""
# Author: Jake VanderPlas
# License: BSD
# The figure produced by this code is published in the textbook
# "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
# For more information, see ... | m
# To report a bug or issue, use the following forum:
# https://groups.google.com/forum/#!forum/astroml-general
import numpy as np
from matplotlib import pyplot as plt
from astroML.fourier import FT_continuous, IFT_continuous, sinegauss
#----------------------------------------------------------------------
# T... |
fro | m .inverse import RandomInverseModel
from .sciopt import BFGSInverseModel, COBYLAInverseModel
from .nn import NNInverseModel
from .wnn import WeightedNNInverseModel, ESWNNInverseModel
from .cmamodel import CMAESInverseModel
from .jacobian import JacobianIn | verseModel
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import mo | dels, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('depot', '0002_lineitem'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_cr... | ('address', models.TextField()),
('email', models.EmailField(max_length=75)),
],
options={
},
bases=(models.Model,),
),
migrations.AddField(
model_name='lineitem',
name='order',
field=models.Foreign... |
# Plotting performance of string_subst_.py scripts
# bar chart of relative comparison with variances as error bars
import numpy as np
import matplotlib.pyplot as plt
performance = [10.3882388499416,1,10.3212281215746]
variance | = [0.790435196936213,0,0.827207394592818]
scripts = ['string_subst_1.py', 'string_subst_2.py', 'string_subst_3.py']
x_pos = np.arange(len(scripts))
plt.bar(x_pos, perf | ormance, yerr=variance, align='center', alpha=0.5)
plt.xticks(x_pos, scripts)
plt.axhline(y=1, linestyle='--', color='black')
plt.ylim([0,12])
plt.ylabel('rel. performance gain')
plt.title('String substitution - Speed improvements')
#plt.show()
plt.savefig('PNGs/string_subst_bar.png')
|
from datetime import datetime, timedelta
from django import http
from django.conf import settings
from django.core.exceptions import PermissionDenied
import mock
import pytest
from olympia.amo.tests import BaseTestCase, TestCase
from olympia.amo import decorators, get_user, set_user
from olympia.amo.urlresolvers imp... | assert isinstance(response, http.HttpResponse)
assert response.content == '{"x": 1}'
assert response['Content-Type'] == 'application/json'
assert response.status_code == 200
def test_json_view_normal_ | response():
"""Normal responses get passed through."""
expected = http.HttpResponseForbidden()
def func(request):
return expected
response = decorators.json_view(func)(mock.Mock())
assert expected is response
assert response['Content-Type'] == 'text/html; charset=utf-8'
def test_json... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.