prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# -*- coding:utf-8 -*- import sys from datetime import datetime from django.template.loader import get_template from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Post reload(sys) sys.setdefaultencoding('utf-8') # Create your views here. def homepage(request): te...
posts = Post.objects.all() posts_lists = list() now = datetime.now() html = template.render(locals()) print sys.getdefaultencoding() #for count, post in enumerate(posts): # print post # print post.pub_date # print post.slug # #posts_lists.append("NO.{}:".format(str(c...
tr(post.body) + "</small><br /><br />") return HttpResponse(html) def showpost(request,slug): template = get_template('post.html') try: post = Post.objects.get(slug = slug) print post if post != None: html = template.render(locals()) return HttpResponse(html)...
ded as a UTF-8 bytestring. On Python 3, __str__ returns the output of __unicode__. Useful as a mix-in. If you support Python 2 and 3 with a single code base, you can inherit this mix-in and just define __unicode__. """ def __init__(self, *args, **kwargs): warnings.warn("StrAndUnicode is dep...
__str__ method " "and apply the @python_2_unicode_compatible decorator " "instead.", PendingDeprecationWarning, stacklevel=2) super(StrAndUnicode, self).__init__(*args, **kwargs) if six.PY3: def __str__(self): return self._
_unicode__() else: def __str__(self): return self.__unicode__().encode('utf-8') def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base...
def foo(a_new, b_new): print(a_new + b
_new * 123) def f(): a = 1 b = 1 foo(a, b
)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 from django.conf.urls.defaults import * from django.conf import settings INSTANCES = r'^(?P<tenant_id>[^/]+)/instances/(?P<instance_id>[^/]+)/%s$' IMAGES = r'^(?P<tenant_id>[^/]+)/images/(?P<image_id>[^/]+)/%s$' KEYPAIRS = r'^(?P<tenant_id>[^/]+)/keypairs/%s$' urlpatterns ...
% 'console', 'console', name='dash_instances_console'), url(INSTANCES % 'vnc', 'vnc', name='dash_instances_vnc'), ) urlpatterns += patterns('django_openstack.dash.views.images', url(r'^(?P<tenant_id>[^/]+)/images
/$', 'index', name='dash_images'), url(IMAGES % 'launch', 'launch', name='dash_images_launch'), ) urlpatterns += patterns('django_openstack.dash.views.keypairs', url(r'^(?P<tenant_id>[^/]+)/keypairs/$', 'index', name='dash_keypairs'), url(KEYPAIRS % 'create', 'create', name='dash_keypairs_create'), )
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import time from django.db import connection from django_logutils.conf import settings logger = logging.getLogger(__name__) de...
r_email)s %(method)s %(url)s %(status)d " "%(content_length)d (%(request_time).2f seconds)" ) if use_sql_info: sql_time = sum( float(q['time']) for q in connection.queries) * 1000 extra_log = { 'nr_queries': len(connection.queries), 'sql_time': sql_tim...
%(sql_time)f ms)" log_dict.update(extra_log) return log_msg % log_dict if fmt else log_msg class LoggingMiddleware(object): """ Capture request info and logs it. Logs all requests with log level info. If request take longer than REQUEST_TIME_THRESHOLD, log level warningis used. Loggi...
MODULES = { '{flavor}.models.{name}'.format(**spec): import_model(spec) for spec in list_models() } IS_FAST = {'dbg': False, 'hp': True, 'lp': True} def model_is_fast(model): flavor = model.__name__.split('.')[1] return IS_FAST[flavor] def iter_examples(module): assert_hasattr(module, 'EXAMPLE...
shared2 = module.Shared() shared2.protobuf_load(message) assert_close(shared2.dump(), shared.dump()) message.Clear() dumped = shared.dump() module.Shared.to_protobuf(dumped, message) assert_close(module.Shared.from_protobuf(message), dumped) if hasattr(module.Group, 'protobuf_load'): ...
sage) group2 = module.Group() group2.protobuf_load(message) assert_close(group2.dump(), group.dump()) message.Clear() dumped = group.dump() module.Group.to_protobuf(dumped, message) assert_close(module.Group.from_protobuf(message), dumped) @for_each_model() def...
"""Tests for the Volumi
o integration.
"""
# --- running self.isInRunningLst = parent.isInRunningLst self.appendToRunning = parent.appendToRunning self.removeFromRunning = parent.removeFromRunning # --- fault self.isInFaultLst = parent.isInFaultLst self.appendToFault = parent.appendToFault self.rem...
)) traceback.print_exc() class Dog(Logger): def __init__(self, devN
ame, joinerEvent=None, startDelay=None, extraAttrs=None, *args, **kwargs): super(Dog, self).__init__(*args, **kwargs) self._devName = devName self._devProxy = None self._eventId = None self._devState = None # --- fault vbles self._tryFaultRecovery...
-%s' % os.path.basename(__file__)) syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % " ".join(sys.argv[1:])) def notice(msg): syslog.syslog(syslog.LOG_NOTICE, msg) def daemonize_self(): # daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 try: pid = os.fork() ...
only "stderr": stderr,
"msg": traceback.format_exc() } result['ansible_job_id'] = jid jobfile.write(json.dumps(result)) jobfile.close() os.rename(tmp_job_path, job_path) if __name__ == '__main__': if len(sys.argv) < 5: print(json.dumps({ "failed": True, "msg": "usage: a...
to member list when a new group has been created create_next = URL(f="group", args=["[id]", "group_membership"]) teams_orgs = settings.get_hrm_teams_orgs() if teams_orgs: if teams_orgs == 1: multiple = False else: ...
", "organisation_team.organisation_id$name", "organisation_team.organisation_id$acronym", ], label = T("Search"), comment = T("You can search by by group name, description ...
wildcard. Press 'Search' without input to list all."), #_class="filter-search", ), S3OptionsFilter("organisation_team.organisation_id", label = T("Organization"), #hidden=True, ...
# -*- coding: utf-8 -*- # <Lettuce - Behaviour Driven Development for python> # Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundatio...
, curdir from nose.tools import assert_equals, with_setup from tests.asserts import prepare_stdout def test_imports_terrain_under_path_that_is_run(): old_path = abspath(curdir) os.chdir(join(abspath(dirname(__file__)), 'simple_features', '1st_feature_dir')) status, output = subprocess.getstatusoutput('p...
world;assert hasattr(world, \'works_fine\'); print \'it passed!\'"') assert_equals(status, 0) assert_equals(output, "it passed!") os.chdir(old_path) @with_setup(prepare_stdout) def test_after_each_all_is_executed_before_each_all(): "terrain.before.each_all and terrain.after.each_all decorators" ...
try: from setuptools import setup, Extension except ImportError: from di
stutils.core import setup, Extension setup(name='peloton_bloomfilters', author = 'Adam DePrince', author_email = 'adam@pelotoncycle.com', url = 'https://github.com/pelotoncycle/peloton_bloomfilters', version='0.0.1', description="Peloton Cycle's Bloomin fast Bloomfilters", ext_modul...
[ Extension( name='peloton_bloomfilters', sources=['peloton_bloomfiltersmodule.c']), ] ) )
from django.forms.fields import * from corehq.apps.sms.forms import BackendForm from dimagi.utils.django.fields import TrimmedCharField from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class TelerivetBackendForm(BackendForm): api_key = TrimmedCharField() pro...
Circular import from corehq.apps.telerivet.models import TelerivetBackend value = self.cleaned_data.get("webhook_secret", None) backend = TelerivetBackend.by_webhook_secret(
value) if backend is not None and backend._id != self._cchq_backend_id: raise ValidationError(_("Already in use.")) return value
"""Render meshes using OpenDR. Code is from: https://github.com/akanazawa/hmr/blob/master/src/util/renderer.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import cv2 import numpy as np from opendr.camera import ProjectPoints from...
en(rn.v), light_pos=_rotateY(np.array([-200, -100, -100]), yrot), vc=albedo, light_color=np.array([1, 1, 1])) # Construct Left Light rn.vc += LambertianPointLight( f=rn.f, v=rn.v, num_verts=len(rn.v), light_pos=_rotateY(np.array([800, 10, 300]), yrot), vc=albedo, ...
c += LambertianPointLight( f=rn.f, v=rn.v, num_verts=len(rn.v), light_pos=_rotateY(np.array([-500, 500, 1000]), yrot), vc=albedo, light_color=np.array([.7, .7, .7])) return rn.r def get_alpha(imtmp, bgval=1.): h, w = imtmp.shape[:2] alpha = (~np.all(imtmp == bgval, axis=2))....
# --coding: utf8-- import requests from django.contrib.gis.db import models from django.contrib.gis.geos import GEOSGeometry class Country(models.Model): """ Модель страны. """ title = models.CharField( u'название', max_length=255) class Meta: verbose_name = u'страна' ver...
et, self.house] if part) def fetch_coordinates(self): """ Запрос координатов объекта с Яндекса. """ query = ',+'.join(
part for part in [self.country.title, self.area, self.subarea, self.locality, self.street, self.house] if part) url = u'http://geocode-maps.yandex.ru/1.x/?geocode=%s&format=json' % ( query) try: r = requests.get(url).json() except...
from distutils.core import setup from distutils.extension import Extension
setup( name='wordcloud', version='1.1.3', url='https://github.com/amueller/word_cloud', description='A little word cloud generator', license='MIT', ext_modul
es=[Extension("wordcloud.query_integral_image", ["wordcloud/query_integral_image.c"])], packages=['wordcloud'], package_data={'wordcloud': ['stopwords', 'DroidSansMono.ttf']} )
# Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved. import os.path import sys import tempfile import itertools import unittest try: import flask.ext.autodoc except ImportError as e: raise unittest.SkipTest('Flask-Autodoc not installed') try: import digits except ImportError: # Add path fo...
context(): generator = _.ApiDocGenerator(doc) check_doc_file(generator, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'docs',
'API.md')) def test_flask_routes_md(): """FlaskRoutes.md out-of-date""" with app.app_context(): generator = _.FlaskRoutesDocGenerator(doc) check_doc_file(generator, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'docs', 'FlaskRoutes.md'))
#
-*- coding:utf8 -*- a = 3 b
= 4 print a+b
# # Copyright 2009 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 option) # any later version. # #...
tion is boolean. The external representation is specified. Used in the check box form. """ def __init__(self, true, false): self._true = true self._false = false def external_to_internal(self, v): return bool(v) def internal_to_external(self, v): if v: return self._true else: return self._false def hel...
: """ A catchall converter when int and float are not enough. Evaluate the internal representation with python's eval(). Possible uses, set a complex number, constellation points. Used in text box. """ def __init__(self, formatter=lambda x: '%s'%(x)): self._formatter = formatter def external_to_internal(self,...
lf._owner_level = 0 self._prefetch = prefetch self._track_last_enqueued_event_properties = ( track_last_enqueued_event_properties ) self._id = str(uuid.uuid4()) self._internal_kwargs = get_dict_with_loop_if_needed(loop) self._running = False self._con...
f._id, partition_id ) if partition_id not in self._consumers: # task is cancelled before the consumer is created del self._tasks[partition_id] def _create_tasks_for_claimed_ownership( self, claimed_partitions: Iterable[str], ...
claim partition %r", self._id, claimed_partitions ) for partition_id in claimed_partitions: if partition_id not in self._tasks or self._tasks[partition_id].done(): checkpoint = checkpoints.get(partition_id) if checkpoints else None if ...
# 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 may ...
def __init__
( self, **kwargs ): super(Error, self).__init__(**kwargs) self.error = kwargs.get('error', None) class ExtendedErrorInfo(msrest.serialization.Model): """this is the extended error info. :param code: this is the error response code. Possible values include: "NotFound", "Con...
from django.http.response i
mport HttpResponse from django.shortcuts import rende
r_to_response, render from Browser.models import UserInfo from Browser.views import cellar, administrator def simple_response(request, *args, **kwargs): template_name = kwargs["path"] if kwargs["type"] : template_name = kwargs["type"] + "/" + template_name userInfo = UserInfo.getUserInfo(...
import logging import shlex import subprocess import json from airflow.hooks.aws_emr import EMRHook from airflow.hooks.S3_hook import S3Hook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.exceptions import AirflowException from slackclient import SlackClient fr...
ew job is: %s """ % output_id) while True: if job_monitor.isRunning(output_id): sleep(900) elif job_monitor.isSuccessfull(output_id): self.slack_message(""" @channel\n ----------------------------------------\nThe proces...
s Successful.\n Manual check is always a good thing. \n ----------------------------------------\nProcess id = %s """ % output_id) break elif job_monitor.isTerminated(output_id): self.slack_message(""" @channel\n ------------------------------...
import unittest import chainer from chainer import testing from chainer.testing import attr from chainercv.links.model.deeplab import SeparableASPP class TestSeparableASPP(unittest.TestCase): def setUp(self): self.in_channels = 128 self.out_channels = 32 self.link = SeparableASPP( ...
igh=
1, size=(2, self.in_channels, 64, 64) ).astype(xp.float32)) y = self.link(x) self.assertIsInstance(y, chainer.Variable) self.assertIsInstance(y.data, xp.ndarray) self.assertEqual(y.shape, (2, self.out_channels, 64, 64)) @attr.slow def test_call_cpu(self): self.c...
o the StackStorm, Inc ('StackStorm') 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 use this file exce...
one) if r_val is None: return '' if isinstance(r_val, list) or isinstance(r_val, dict):
return r_val if len(r_val) > 0 else '' return r_val @staticmethod def _get_friendly_column_name(name): if not name: return None friendly_name = name.replace('_', ' ').replace('.', ' ').capitalize() return friendly_name @staticmethod def _get_required_col...
or c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += f'({big})' return f'Cycle{s}' def __init__(self, *args): """Load up a Cycle instance with the values for the cycle. Examples ======== >>> Cycle(1, 2, 6) ...
ence in how Permutation and Cycle handle the __call__ syntax. A singleton argument at the start of a Permutation performs instantiation of the Permutation and is permitted: >>> Permutation(5) Permutation([], size=6) A singleton entered after instantiation is a call to the permutation -- a ...
r this reason, it is better to start the cycle with the singleton: The following fails because there is is no element 3: >>> Permutation(1, 2)(3) Traceback (most recent call last): ... IndexError: list index out of range This is ok: only the call to an out of range singleton is prohibited...
""" def __init__(self, name, size, border_layers): if not (type(border_layers) == list): border_layers = [border_layers] Cell.__init__(self, name) self.size_x, self.size_y = size # Create the border of the cell for l in border_layers: self.border ...
next line i = 0 # Restart at left pitch_v = pitch / np.cos(np.deg2rad(rot_angle)) # widthV = width / np.cos(np.deg2rad(rotAngle)) nx = int(array_width / (length + spacing)) ny = int(array_height...
# Define the slits slit = Cell("Slits") rect = Rectangle((-length / 2., -width / 2.), (length / 2., width / 2.), layer=l) rect = rect.copy().rotate(rot_angle) slit.add(rect) slits = CellArray(slit, nx,...
""" Persistence configuration """ PERSISTENCE_BACKEND = 'pyp
eman.persistence.SqliteBackend' PERSISTENCE_CONFIG = {"path":'/tmp/to_be_removed_849827198746.sqlite
'}
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Publ
ic License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob 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 t...
received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. from weboob.tools.test import BackendTest __all__ = ['Minutes20Test'] class Minutes20Test(BackendTest): BACKEND = 'minutes20' def test_new_messages(self): for message in self...
# -*- coding: utf-8 -*- # Copyright (C) 2011-2012 Vodafone España, S.A. # Author: Andrew Bird # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your o...
distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program...
Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from wader.common.consts import WADER_CONNTYPE_USB from core.hardware.zte import (ZTEWCDMADevicePlugin, ZTEWCDMACustomizer, ZTEWrapper) class ZTEMF18...
from __future__ import absolute_import, unicode_literals import mock import pytest from ddns_zones_updater.configreader import ConfigReader from ddns_zones_updater.core import DDNSZoneUpdater @pytest.fixture def fake_config_reader_with_two_hosts(): host_1 = mock.Mock(do_update=mock.Mock()) host_2 = mock.Moc...
o/config.ini") @mock.patch.object(ConfigReader, "read") @mock.patch.object(ConfigReader, "__init__", return_value=None) def test_initializer(mock_init, mock_read): DDNSZoneUpdater("/tmp/foo.ini") mock_init.assert_called_once_with("/tmp/foo.ini") mock_read.assert_called_once_with() def test_get_current_w...
ithout_calling_init): updater = updater_without_calling_init with mock.patch("ipgetter.myip", return_value="149.0.0.31") as mock_my_ip: assert updater.current_wan_ip() == "149.0.0.31" mock_my_ip.assert_called_once_with() def test_run(updater_without_calling_init, fake_config_reader_with_two_ho...
#!/usr/bin/env python import unittest from test import support import socket import urllib.request import sys import os import email.message def _open_with_retry(fun
c, host, *args, **kwargs): # Connecting to remote hosts is flaky. Make it more robust # by retrying the connection several times. last_exc = None for i in range(3): try: return func(host, *args, **kwargs) except IOError as err: last_exc = err continue...
.0 def setUp(self): socket.setdefaulttimeout(self.TIMEOUT) def tearDown(self): socket.setdefaulttimeout(None) def testURLread(self): f = _open_with_retry(urllib.request.urlopen, "http://www.python.org/") x = f.read() class urlopenNetworkTests(unittest.TestCase): """Te...
import json with open('data/78mm.json', 'r') as _78mm: polygons78 = json.load(_78mm)["features"][0]["geometry"]["geometries"] with open('data/100mm.json', 'r') as _100mm: polygons100 = json.load(_100mm)["features"][0]["geometry"]["geometries"] with open('data/130mm.json', 'r') as _130mm: polygons130 = json...
s78[res[1]]["coordinates"][0], 'Orange') # if (res[0] == 130): # print_polygon(polygons78[res[1]]["coordinates"][0], 'Yellow
') # plt.plot(x, y, marker='*') # ax.grid() # ax.axis('equal') # plt.show()
where latitud < -7.177 and latitud > -8.9722 # /* Ancash*/ # select count(*) from t_boya_medicion_minpres # where latitud < -8.9722 and latitud > -10.593 import glob, os import psycopg2 import datetime db_user = "USER" db_host = "IP_ADDRESS" db_password = "PASSWORD" output = "./Output/datos_total_boya3_est7_ca1.csv"...
], row[3], row[4], row[5], row[6]) return b_data def database_select_date_between_lat_avg_caudal(region, start_date, end_date): try: conn = psycopg2.connect("dbname='elnino' user='%s' host='%s' password='%s'"%(db_user, host, password)) except Exception, e: print "I am unable to connect to ...
From t_caudal_medicion c " \ " Where c.region like '%s' AND c.caudal != 9999 " \ " AND concat_ws('-',ano,mes,dia)::date >= '%s'::date " \ " AND concat_ws('-',ano,mes,dia)::date <= '%s'::date;"%(region, start_date, end_date) # print query cur.execute(q...
# encoding: 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/. # from __future__ import absolute_import, division, unicode_literals from jx_base.queries import ...
elative_field(var, origin) fact_dict = {} origin_dict = {} for k, cs in self.namespace.items(): for c in cs: if c.jx_type in STRUCT: cont
inue if startswith_field(get_property_name(k), var): origin_dict.setdefault(c.names[origin], []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(c.name, []).append(c) elif origin == var: o...
__problem_title__ = "Co
mfortable distance" __problem_url___ = "https://projecteuler.net/problem=364" __problem_description__ = "There are seats in a row. people come after each other to fill the " \ "seats according to the following rules: We can verify that T(10) = " \ "61632 and T(1 000) ...
staticmethod def solution1(): pass @staticmethod def time_solutions(): setup = 'from __main__ import Solution' print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1)) if __name__ == '__main__': s = Solution() print(s.solution1()) s.time_solut...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Kylin OS, 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 # #...
itial', {}) instance_id = initial.get('instance_id') self.fields['instance_id'] = forms.CharField(widget=forms.HiddenInput
, initial=instance_id) self.fields['host'].choices = self.populate_host_choices(request, initial) def populate_host_choices(self, request, initial): hosts = initial.get('hosts') ...
, "\nPat", F_["BIN"]), ("Bpc", "\nBpc", F_["BIN"]), ("Bpt", "\nBpt", F_["BIN"]), ("HwBP", "\nHbr", F_["BIN"]), ("Save", "\nSva", F_["BIN"]), # sometimes 4, sometimes 5 ? ("AnalyseHint", "\nAht", F_["BIN"]), ("CMD_PLUGINS", "\nUs0", F_["DDSTRING"]), # multiline, ne...
('p', 'trace_condition1'), ('q', 'trace_condition2'), ('r', 'trace_condition3'), ('s', 'trace_condition4'), ('t', 'trace_command1'), ('u', 'trace_command2'), ('v', 'protocol_start'), ('w', 'proto
col_end'), ('Q', 'log_explanation'), ('R', 'log_condition'), ('S', 'log_expression'), ('U', 'mem_explanation'), ('V', 'mem_condition'), ('W', 'mem_expression'), ('Y', 'hbplog_explanation'), ('Z', 'hbplog_condition'), ('[', 'hbplog_ex...
#!/usr/bin/python import sys, os import select, socket import usbcomm import usb _default_host = 'localhost' _default_port = 23200 _READ_ONLY = select.POLLIN | select.POLLPRI class Stream(object): def __init__(self, host=_default_host, port=_default_port): self.host = host sel
f.port = port self.usb = usbcomm.USBComm(idVendor=usbcomm.ids.Bayer, idProduct=usbcomm.ids.Bayer.Contour) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.setblocking(0) self.poller = select.poll() self.fd_to_socket = {} self.clients = [] def close(self): pri...
dd_client(self, client): print >>sys.stderr, 'MUX > New connection from', client.getpeername() client.setblocking(0) self.fd_to_socket[client.fileno()] = client self.clients.append(client) self.poller.register(client, _READ_ONLY) def remove_client(self, client, why='?'): try: name = cli...
# -*- coding: utf-8 -*- # Generated by Django 1
.10.2 on 2017-02-09 17:08 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('scoping', '0047_auto_20170209_1626'), ] operations = [ migrations.RemoveFie
ld( model_name='query', name='technology', ), migrations.AddField( model_name='query', name='technology', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='scoping.Technology'), ), ]
+ 1)) return read_code naics_codes = naics_codes.dropna() naics_codes['NAICSCode'] = naics_codes['NAICSCode'].apply(range_to_array) naics_codes = naics_codes.explode('NAICSCode') # Add unclassified code which is used in some statistical variables. naics_codes = naics_codes.append( ...
alDronabinol', 'drug/dea/7369': 'DronabinolGelCapsule', 'drug/dea/7370': 'Tetrahydrocannabinol', 'drug/dea/7377': 'Cannabicyclol', 'drug/dea/7379': 'Nabilone', 'drug/dea/7381': 'M
escaline', 'drug/dea/7400': '34Methylenedioxyamphetamine', 'drug/dea/7431': '5MethoxyNNDimethyltryptamine', 'drug/dea/7433': 'Bufotenine', 'drug/dea/7437': 'Psilocybin', 'drug/dea/7438': 'Psilocin', 'drug/dea/7455': 'PCE', 'drug/dea/7471': 'Phencyclidine', 'drug/dea/7540': 'Methylone', ...
#!/usr/local/bin/python3 """ Copyright (c) 2015-2019 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain th...
pen unix domain socket try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(con
figd_socket_name) except socket.error: syslog_error('unable to connect to configd socket (@%s)'%configd_socket_name) print('unable to connect to configd socket (@%s)'%configd_socket_name, file=sys.stderr) return None try: sock.send(exec_command.encode()) data = [] ...
from c2cgeoportal_admin.views.layertree import itemtypes_tables itemtypes
_tables.update({ 'lu_int_wms': 'lux_layer_internal_wms', 'lu_ext_wms':
'lux_layer_external_wms', })
########################################################################### # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/l...
HOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################### # # This code generated (see scripts folder for possible source): ...
######## import argparse import textwrap from starthinker.util.configuration import Configuration from starthinker.task.dcm.run import dcm def recipe_dcm_run(config, auth_read, account, report_id, report_name): """Trigger a CM report run Args: auth_read (authentication) - Credentials used for reading...
# This file is pa
rt of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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) an...
er version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License ...
""" @summary: Module contain matrix base classes @author: CJ Grady @version: 1.0 @status: alpha @license: gpl2 @copyright: Copyright (C) 2014, University of Kansas Center for Research Lifemapper Project, lifemapper [at] ku [dot] edu, Biodiversity Institute, 1345 Jayhawk Boulevard, Lawre...
d a copy of the GNU General Public License along with this program; if not,
write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ class Grid(object): """ @summary: Base class for Lifemapper grids. This class can be used with uncompressed grids. """ # ........................... def ...
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3])...
self._start(forked_branch) else: stage.start() def _shutdown(self, stages: list): for stage in stages: if type(stage) == PipelineF
ork: for forked_branch in stage.forked_branches: self._shutdown(forked_branch) else: stage.shutdown()
# Copyright 2015 Tesora Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
tem CONF = cfg.CONF def update_dict(updates, target): """Recursively update a target dictionary with given updates. Updates are provided as a dictionary of key-value pairs where a value can also be a nested dictionary in which case its key is treated as a sub-sec
tion of the outer key. If a list value is encountered the update is applied iteratively on all its items. :returns: Will always return a dictionary of results (may be empty). """ if target is None: target = {} if isinstance(target, list): for index, item in enumerate(target)...
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import pytest from numpy import isclose from dolfin import (assemble, dx, FiniteElement, FunctionSpace, inner, MixedElement, split, TestFunction, TrialFunction, UnitSquare...
lose(loaded_evaluated_
tensor.get_local(), expected_evaluated_tensor.get_local()).all() elif len(space) == 2: assert isclose(loaded_evaluated_tensor.array(), expected_evaluated_tensor.array()).all() @generate_form_spaces_and_forms def test_tensor_io(mesh, generate_form_space, generate_form, tempdir): test_tensor_save(mesh, ...
# Generated by Dja
ngo 2.0.13 on 2019-08-10 20:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profile_manager', '0004_auto_20190729_2101'), ] operations = [ migrations.AddField( model_name='profile', name='get_messages_by_email...
il.'), ), ]
# -*- 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): # Changing field 'RegisteredIndex.query_hash' db.alter_column('djangodocument_registeredindex', 'query_hash...
), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'param_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'Tru
e'}), 'value': ('django.db.models.fields.TimeField', [], {'null': 'True'}) } } complete_apps = ['djangodocument']
from .local
import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'temp.db', 'USER': '', 'PASSWORD':
'', 'HOST': '', 'PORT': '', } } OPBEAT['APP_ID'] = None
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-23 11:29 from __future__ import unicode_literals from django.db import migrations, models
class Migration(migrations.Migration): dependencies = [ ('gestioneide', '0019_auto_20160517_2232'), ] operations = [ migrations.AlterField( model_name='festivo', name='anotacion', field=models.CharField(default=b'', max_len
gth=50), ), ]
# -*- cod
ing: utf8 -*- # # Created by 'myth' on 2/19/16 import matplotlib as
mpl import settings mpl.use('TkAgg')
import json from flask import g, jsonify, request, current_app, url_for from ..models import User from .. import db from . import main from .authentication import auth_user from .errors import bad_request, unauthorized, forbidden, not_found """read all""" @main.route('/<token>/users/', methods=['GET']) ...
# get and return all: users = User.query.all() list_of_dicts = [json.loads(user.to_json()) for user in users] return json.dumps(list_of_dicts) """read one""" @main.route('/<token>/users/<int:id>/', methods=['GET']) def get_user(token, id): if not auth_user(token): return unauthorized("You
have to be logged in to perform this action") # get and return one with id: user = User.query.get(id) if user == None: not_found("Resource not found"); return user.to_json() """create""" @main.route('/users/', methods=['POST']) #sign-up def new_user(): # create and commit user userna...
import serial import numpy as np import json from datetime import datetime class ElectronicNose: def __init__(self, devAdd='/dev/ttyUSB0', baudrate=115200/3, \ tmax = 1000, outputFile = '', numSensors = 8): ## Creating the serial object self.Sensor = serial.Serial(devAdd, baud...
mples_ += 1 avg[0,1:] += self.convert( r.split('\rV')[1].split('\n')[0][8:39] ) if nsamples_ > 0: avg = avg/float(nsamples_) now = datetime.now() avg[0,0] = now.hour*3600 + now.minute*60 + now.second + now.microsecond/1.e6 self.memory = np.conca...
ros(10) # Converting 8 sensors for j in range(8): s[j] = int( string[j*3:j*3+3] , 16 ) # Converting temperature and humidity s[8] = int( string[24:28] , 16) s[9] = int( string[28:31] , 16) return s if __name__ == "__main__": # Instantiating the class...
str(snapshot.id)).AndReturn(snapshot) api.volume_create(IsA(http.HttpRequest), formData['size'], formData['name'], formData['description'], snapshot_id=snapshot.id).\ A...
.HttpRequest)).AndReturn(self.servers.list()) api.volume_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn(self.volumes.list()) api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list()) self.mox.ReplayAll() url = reverse('horizon:pro...
ssertMessageCount(res, error=1) self.assertEqual(list(res.context['messages'])[0].message, u'Unable to delete volume "%s". ' u'One or more snapshots depend on it.' % volume.display_name) @test.create_stubs({api: ('volume_get',), api...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-20 01:24 from __future__ import unicode_literals from django.db import migrations, model
s import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('forum_conversation', '0009_auto_20160925_2126'), ] operations = [ migrations.AlterField( model_name='topic', name='first_post', field=models.ForeignKey(blank=T...
), ]
""" This GA code creates the gaModel with a circular island model """ from operator import attrgetter # import sys from deap import base, creator, tools import numpy from csep.loglikelihood import calcLogLikelihood as loglikelihood from models.mathUtil import calcNumberBins import models.model import random import arr...
# local_best = comm.recv(source=thread) local_best = comm.recv(source=thread) # req = comm.irecv(source=threa
d) # local_best = req.wait() best_all_pop.append(local_best) maximum = float('-inf') # for value, index in zip(best_all_pop, range(len(best_all_pop))): for local_best in best_all_pop: local_maximum = evaluationFunction(local_best, modelOmega, mean) if maximum < local_maximum[0]: # theBestIndex ...
# -*- coding: utf-8 -*- # # Point Tracker documentation build configuration file, created by # sphinx-quickstart on Mon Oct 25 14:10:24 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. #...
xt.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.jsmath'] # Add any paths that contain templates here, relative to this directory. templ...
he encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Point Tracker' copyright = u'2010, Barbier de Reuille, Pierre' # The version info for the project you're documenting, acts as replacement for # |version| an...
- def
__init__(
self): -
=app.config['COOLDOWN'], max_retries=app.config['MAX_RETRIES']) # If the code was not a good code, record the status as a 404 and raise an exception finally: db.session.commit() return str(response.status_code) def do_capture(status_code, the_record, base_url, model='capture', phantomjs_timeout=ap...
c': capture_name = capture_name.split('.')[0] # Wite our html text that was parsed into our capture folder parsed_text = open(os.path
.join(app.config['LOCAL_STORAGE_FOLDER'], capture_name + '.txt'), 'wb') parsed_text.write(output) # Update the sketch record with the local URLs for the sketch, scrape, and html captures the_record.sketch_url = base_url + '/files/' + capture_name + '.png' the_record.scrape_url = base_url + '/files/' + ...
test_cdphotothread_parsetest_cdphotothread_parse(self): # cd = MediaParser.partial_media_dict_from_url( # "https://www.chiefdelphi.com/media/photos/41999") # self.assertEqual(cd['media_type_enum'], MediaType.CD_PHOTO_THREAD) # self.assertEqual(cd['foreign_key'], "41999") # s...
result['profile_url'], 'https://www.youtube.com/uberbots1124') gapps_result = MediaParser.partial_media_dict_from_url("https://www.youtube.c
om/c/tnt3102org") self.assertEqual(gapps_result['media_type_enum'], MediaType.YOUTUBE_CHANNEL) self.assertEqual(gapps_result['is_social'], True) self.assertEqual(gapps_result['foreign_key'], 'tnt3102org') self.assertEqual(gapps_result['site_name'], MediaType.type_names[MediaType.YOUTUBE_...
import numpy as np from scipy.special import iv def tapering_window(time,D,mywindow): """ tapering_window returns the window for tapering a WOSA segment. Inputs: - time [1-dim numpy array of floats]: times along the WOSA segment. - D [float]: Temporal length of the WOSA segment. - mywindow [int]: Choice of ...
e-D/2.0)/(D/2.0) elif mywindow==3: tapering_window=np.sin(np.pi*time/D) elif mywindow==4: tapering_window=(np.sin(np.pi*time/D))**2 elif mywindow==5: tapering_window=(np.sin(np.pi*time/D))**3 elif mywindow==6: tapering_window=(np.sin(np.pi*time/D))**4 elif mywindow==7: tapering_window=0.54-0.46*np.cos(2....
elif mywindow==8: a0=0.35875 a1=0.48829 a2=0.14128 a3=0.01168 tapering_window=a0-a1*np.cos(2.0*np.pi*time/D)+a2*np.cos(4.0*np.pi*time/D)-a3*np.cos(6.0*np.pi*time/D) elif mywindow==9: alpha=2.5 tapering_window=iv(0,np.pi*alpha*np.sqrt(1.0-((time-D/2.0)/(D/2.0))**2)) elif mywindow==10: sig=D/6.0 taper...
fro
m ga_starters imp
ort *
#!/usr/bin/env python # -*- coding: utf-8 -*- """ progress test (count to 1000) """ from __future__ import absolute_import from __future__ import print_function from __
future__ import unicode_literals from ...utils.timing import TimedTestCase from ..progress impor
t together class test_progress(TimedTestCase): def test_prog(self): self.threshold = 0.1 together(1000)
uest request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: raise models.FabricErrorException(self._deserialize, response) if raw: client...
figuration overrides<msrest:optionsforoperations>`. :return: None or ClientRawResponse if raw=true :rtype: None or ~msrest.pipeline.ClientRawResponse :raises: :class:`FabricErrorException<azure.servicefabric.models.FabricErrorException>` """ api_version = "6.0" ...
# Construct URL url = '/Services/$/{serviceId}/$/GetPartitions/$/Recover' path_format_arguments = { 'serviceId': self._serialize.url("service_id", service_id, 'str', skip_quote=True) } url = self._client.format_url(url, **path_format_arguments) # Construct par...
#!/usr/bin/env python class PLUGIN_test_test2: def __init__(self, screensurf, keylist, vartree): self.screensurf=screensurf self.keylist=keylist #best practice to init keyid variables during init, and default them to "0" (the null keyid) self.keyid="0" def fork(self, tagobj): return #core object. should e...
e active, you MUST return a Rect! #onkey/offkey maski
ng is honored by the system regardless. def core(self, tagobj): if tagobj.tag=="test2": self.xpos=int(tagobj.attrib.get("x")) self.ypos=int(tagobj.attrib.get("y")) #note: these core object tests are in blue self.testrect=pygame.Rect(self.xpos, self.ypos, 60, 20) pygame.draw.rect(self.screensurf, (0, 1...
#!/usr/
bin/env python # -*- coding: UTF-8 -*-
from app import create_app, celery app = create_app()
import collections g=open("depth_29.txt","w") with open('depth_28.txt') as infile: counts = collections.Counter(l.strip() for l in infile) for line, count in counts.most_common(
): g.write(str(line)) #g.wri
te(str(count)) g.write("\n")
from distutils.core import setup setup( name='dkcover
age', version='0.0.0', packages=[''], url='https://github.com/thebjorn/dkcoverage',
license='GPL v2', author='bjorn', author_email='bp@datakortet.no', description='Run tests and compute coverage.' )
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_shear_mite_broodling.iff" res
ult.attribute_template_id = 9 result.stfName("monster_name","shear_mite") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS ####
return result
update_devs_dict(devs, dev, entry) if path.startswith(SYSFS_PATH2): os.path.join(path,"device","block:*") dev = _extract_dev_name(os.path.join(path, 'device')) if devs.has_key(dev): continue hbtl = os.pat...
driver_name) \ and ( filterstr == "any" or match_filterstr(filterstr, driver_name) ): return driver_name else: return "" def match_blacklist(driver_name): return re.search("(" + ")|(".join(DRIVER_BLACKLIST) +
")", driver_name) def match_filterstr(filterstr, driver_name): return re.search("^%s" % filterstr, driver_name) def match_host(s): return re.search("^host[0-9]", s) def match_rport(s): regex = re.compile("^rport-*") return regex.search(s, 0) def match_targets(s): regex = re.compile("^target[0-9...
# test rasl inner loop on simulated data # # pylint:disable=import-error from __future__ import division, print_function import numpy as np from rasl.inner import inner_ialm from rasl import (warp_image_gradient, EuclideanTransform, SimilarityTransform, AffineTransform, ProjectiveTransform) def setup...
.random.random() * 2 - 1) * dtheta, (np.random.random() * 2 - 1) * dx, (np.random.random() * 2 - 1) * dy] for _ in range(N)] inner_jittered([EuclideanTransform(paramv=jitter) for jitter in Jitters]) def test_inner_jittered_similarity(): N = 40 ds, dtheta, dx, ...
dom.random() * 2 - 1) * dx, (np.random.random() * 2 - 1) * dy] for _ in range(N)] inner_jittered([SimilarityTransform(paramv=jitter) for jitter in Jitters]) def test_inner_jittered_affine(): N = 40 ds, dtheta, dx = .05, .05, 1 Jitters = [[(np.random.random() * 2 - 1) * ds...
# -*-
coding: utf-8 -*- """ Package of failing integer functions. """ from metaopt.objective.integer.failing.f import f as f from metaopt.objective.integer.failin
g.g import f as g FUNCTIONS_FAILING = [f, g]
# Copyright 2015 Hewlett-Packard Development Company, L.P # 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....
p_page.find_message_and_dismiss(messages.ERROR)) self.assertEqual('-', floatingip_page.get_fixed_ip(floating_ip)) floatingip_page.release_floatingip(floating_ip) self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS)) self.assertFalse( floatingip_page.find_message_and_dismiss(messages.ERROR)) self.assertFalse(floatingip_page.is_floatingip_present(floating_ip)) instances_page = self.home_pg.go_to_compute_instancespage() instanc...
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 import logging import traceback from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from django.contrib.auth import logout as django_logout from restclients_core.exceptions import DataFailu...
(request) # clear the session data if is_native(request): return HttpResponse() # Redirects to authN service logout page return HttpResponseRedirect(get_logout_url()) def _add_quicklink_context(request, context): link_data = get_quicklink_data(request) for key in link_data: con...
def _add_email_forwarding(request, context): my_uwemail_forwarding = get_email_forwarding_for_current_user(request) c_user = context["user"] if my_uwemail_forwarding and my_uwemail_forwarding.is_active(): try: c_user['email_forward_url'] = get_service_url_for_address( m...
import logging from stubo.ext.xmlutils import XPathValue from stubo.ext.xmlexit import XMLManglerExit log = logging.getLogger(__name
__) elements = dict(year=XPathValue('//dispatchTime/dateTime/year'), month=XPathValue('//dispatchTime/dateTi
me/month'), day=XPathValue('//dispatchTime/dateTime/day'), hour=XPathValue('//dispatchTime/dateTime/hour'), minutes=XPathValue('//dispatchTime/dateTime/minutes'), seconds=XPathValue('//dispatchTime/dateTime/seconds')) attrs = dict(y=XPathValue('//dispatch...
authent.models.default_structure_pk, verbose_name='Related structure', to='authent.Structure')), ], options={ 'ordering': ['network'], 'db_table': 'l_b_reseau', 'verbose_name': 'Network', 'verbose_name_plural': 'Networks', ...
name='PathSource', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('source', models.CharField(max_length=50, verbose_name='Source')), ('structure', models.ForeignKey(db_column='structure',...
ucture_pk, verbose_name='Related structure', to='authent.Structure')), ], options={ 'ordering': ['source'], 'db_table': 'l_b_source_troncon', 'verbose_name': 'Path source', 'verbose_name_plural': 'Path sources', }, ...
a = 'sdlbapm' b = 'alam'
for d in a: p
rint d + b
import unittest from datetime import datetime import tempfile import os from due.agent import Agent from due.episode import Episode from due.event import Event from due.persistence import serialize, deserializ
e from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unittest.TestCase): def test_save_load(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) saved_agent = agent.save() with tempfile.Tempora
ryDirectory() as temp_dir: path = os.path.join(temp_dir, 'serialized_tfidf_agent.due') serialize(saved_agent, path) loaded_agent = Agent.load(deserialize(path)) assert agent.parameters == loaded_agent.parameters assert agent._normalized_past_utterances == loaded_agent._normalized_past_utterances assert ...
#!/usr/bin/python # -*- coding: utf-8 -*- import unicodedata from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Q
ueue import itertools import codecs import csv import sys import ssl import re if len(sys.argv) < 3: print "Usage: %s <csv database> <out csv>" % (sys.argv[0]) exit() # Unicode CSV reader # http://stackoverflow.com/a/6187936 class UnicodeCsvReader(object): def __init__(self, f, encoding="utf-8", **kwargs)...
der = csv.reader(f, **kwargs) self.encoding = encoding def __iter__(self): return self def next(self): # read and split the csv row into fields row = self.csv_reader.next() # now decode return [unicode(cell, self.encoding) for cell in row] @property def...
#!/usr/local/sci/bi
n/python # PYTHON2.7 # import TestLeap # TestVal = TestLeap.TestLeap(year) import numpy as np def TestLeap(year): '''function to test if a year is a leap year''' '''returns 0.0 if it is a leap year''' '''returns a non-zero number if it is not a leap year''' '''ONLY WORKS WITH SCALARS!!!''' # fi...
) - np.round(year/100.)) == 0.): leapoo = leapoo + ((year/400.) - np.round(year/400.)) return leapoo
# coding=utf-8 import time import json import boto3 from botocore.errorfactory import ClientError def lambda_handler(event, context): instance_id = event.get('instance_id') region_id = event.get('region_id', 'us-east-2') image_name = 'beam-automation-'+time.strftime("%Y-%m-%d-%H%M%S", time.gmtime()) ...
te_lambda(image_ids): lm = boto3.client('lambda') en_var = lm.get_function_configuration(FunctionName='simulateBeam')['Environment']['Variables'] en_var.update({ 'us_east_2_IMAGE_ID': image_ids['us-east-2'], 'us_east_1_IMAGE_ID': image_ids['us-east-1'], ...
FunctionName='simulateBeam', Environment={ 'Variables': en_var } ) def check_instance_id(instance_ids): for reservation in ec2.describe_instances()['Reservations']: for instance in reservation['Instances']: if instance['I...
not self.tar: self.tar = tar # return else: for i in tar: self.tar.addfile(i) def is_cached(self, filename): if not self.tar: return False return filename in self.tar.getnames() def _get_file(self, filename): """ D...
tiSite()._merge_statistics(result1, result2) [3, 3, 3, 3] """ if not list1: return list2 if not list2: return list1 number_of_columns = len(list1) result = [0] * number_of_columns for row in (list1, list2): for i, colu
mn in enumerate(row): result[i] += column return result def get_host(self, host_name, backend=None): """ Same as Livestatus.get_host() """ backend = self.get_backend(backend) return backend.get_host(host_name) def get_service(self, host_name, service_description...
from datetime import datetime, timedelta, timezone from django.shortcuts import render from django.core.management import call_command from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext_lazy as _ from fly_project import set...
elif goal_type == constants.GOAL_MYGOAL_TYPE: goal = FinalGoal.objects.get(id=goal_id) except Exception as e: pass return
render(request, 'mygoals/complete/view.html',{ 'settings': settings, 'constants': constants, 'goal_id': int(goal_id), 'goal_type': int(goal_type), 'goal': goal, }) @login_required(login_url='/authentication') def goal_failed_page(request, goal_type, goal_id): goal = No...
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
ing permissions and # limitations under the License. import math from typing import Callable, Tuple, TypeVar T = TypeVar('T') def _
accept(random_sample: float, cost_diff: float, temp: float) -> Tuple[bool, float]: """Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number in the range [0, 1). cost_diff: Cost difference ...
# xVector Engine Client # Copyright (c) 2011 James Buchwald # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This pr...
ty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-...
t traceback from PyQt4 import QtGui from xVClient import ClientGlobals mainlog = logging.getLogger("") # Severity constants FatalError = 1 """Fatal error, forces termination of application.""" NormalError = 2 """Normal error, this has impact but does not crash the program.""" WarningError = 3 """Warning, this does ...
from
bs4 import BeautifulSoup import xlsxwriter workbook= xlsxwriter.Workbook("data.xlsx") worksheet = workbook.add_worksheet() f = open('rough.html',"r") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {"class":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') r...
nd('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6, td[6].text) rowno=rowno+1 workbook.close() print "Done"
import os import numpy def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuratio
n('datasets', parent_package, top_path) config.add_data_dir('data') config.add_data_dir('descr') config.add_data_dir('images') config.add_data_dir(os.path.join('tests', 'data')) config.add_extension('_svmlight_format',
sources=['_svmlight_format.c'], include_dirs=[numpy.get_include()]) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
bar",\n' ' "version": "1.2.3"\n' " },\n" " {\n" ' "name": "foobar",\n' ' "version": "1.2.2"\n' " },\n" " {\n" ' "name": "foobar",\n' ' "version": "1.2.1"\n' " },\n" " {\n" ...
ar", "1.2.3"],
["foobar", "1.2.2"], ["foobar", "1.2.1"], ["foobar", "1.2.0"], ["quux", "0.1.0"], ["gnusto", "0.0.0"], ], } ) spclass = mocker.patch("qypi.api.ServerProxy", return_value=spinstance) r = CliRunner().invoke( ...
# -*- coding: utf-8 -*- """Doctest for method/function calls. We're going the use these types for extra testing >>> from UserList import UserList >>> from UserDict import UserDict We're defining four helper functions >>> def e(a,b): ... print a, b >>> def f(*a, **k): ... print a, t...
) (1, 2, 3, 4, 5) {} >>> f(1, 2, 3, *[4, 5]) (1, 2, 3, 4, 5) {} >>> f(1, 2, 3, *UserList([4, 5])) (1, 2, 3, 4, 5) {} Here we add keyword arguments >>> f(1, 2, 3, **{'a':4, 'b':5}) (1, 2, 3) {'a': 4, 'b': 5} >>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7}) (1, 2, 3, 4, 5) {'a
': 6, 'b': 7} >>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9}) (1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5} >>> f(1, 2, 3, **UserDict(a=4, b=5)) (1, 2, 3) {'a': 4, 'b': 5} >>> f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7)) (1, 2, 3, 4, 5) {'a': 6, 'b': 7} >>> f(1, 2, 3, x=4, y=5, *(6, 7)...
import os # Django settings for mysite project. DEBUG = True BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ADMINS = ( # ('Your Name',
'your_email@example.com'), ) MANAGERS = ADMINS SITE_ROOT
= os.path.join(os.path.abspath(os.path.dirname(__file__)), '..') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(SITE_ROOT, 'db.sqlite3'), # Or path to database file if using sqlite3. # The ...
request) self.assertStatusCode(response, 200) self.assertEqual(response.content, '{"items": [{"id": "one"}, {"id": "two"}]}') nc.keypair_list.assert_called_once_with(request) @mock.patch.object(nova.api, 'nova') def test_keypair_create(self, nc): request...
'"missing required parameter \'source_id\'"') nc.server_create.assert_not_called() @mock.patch.object(nova.api, 'nova') def test_server_create_basic(self, nc): request = self.mock_
rest_request(body='''{"name": "Ni!", "source_id": "image123", "flavor_id": "flavor123", "key_name": "sekrit", "user_data": "base64 yes", "security_groups": [{"name": "root"}]} ''') new = nc.server_create.return_value new.to_dict.return_value = {'id': 'server12...
#!/usr/bin/python3 def sanitize(time_string): if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.strip().split(splitter) return(mins + '.' + secs) d
ef get_coach_data(filename): try: with open(filename) as fn: data = fn.readline()
return(data.strip().split(',')) except IOError as ioerr: print('File Error:' + str(ioerr)) return(None) sarah = get_coach_data('sarah2.txt') (sarah_name, sarach_dob) = sarah.pop(0), sarah.pop(0) print(sarah_name + "'s fastest time are:"+ str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
import os def create_peanut(peanut_name): peanut_dir = './peanuts/%s' % peanut_name if os.path.exists(peanut_dir): print('Peanut already exists') return os.mkdir(peanut_dir) os.mkdir(peanut_dir + '/templates') f = open(peanut_dir + '/__init__.py', 'w') f.w
rite('') f.flush() f.close() f = open(peanut_dir + '/main.py', 'w') f.write('\n__META__ = {\n') f.write(" 'displayName': '%s',\n" % peanut_name) f.write(" 'description': 'Peanut description',\n") f.write(" 'version': '0.1',\n") f.write(" 'enabled': True,\n") f.write("}\n...
peanut_name) f.flush() f.close() def clean(): if os.path.exists('./.__tmp__') and os.path.isdir('./.__tmp__'): import shutil shutil.rmtree('./.__tmp__')
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-03 14:52 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('presence', '0001_initial'),
] operations = [ migrations.CreateModel(
name='Session', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('start', models.DateTimeField()), ('end', models.DateTimeField()), ('created_at', models.DateTimeField(auto_now...
icients, the reflectance and the transmittance of the multilayer system.in the down-up direction of propagation. Returns ------- out : dictionary A dictionary with the reflection and transmission coefficients, the reflectance and the transmittance of the ...
Retreive coefficients. We have to build some # submultilayers first.
# Submultilayer from the top medium to dipole_layer_index. rilist = [self.getRefrIndex(0)] alist = [self.getPropAngle(0)] layers = [self.__stack[0]['medium']] for index in range(1, dipole_layer_index): layers.append([self.__stack[index]['medium'], ...
import sys import operator import collections import random import string import heapq # @include def find_student_with_highest_best_of_three_scores(name_score_data): student_scores = collections.defaultdict(list) for line in name_score_data: name, score = line.split() if len(student_scores[na...
assert result == 'adnan' def main(): simple_test() n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 10000) with open('scores.txt', 'w') as ofs: for i in range(n): test_num = random.randint(0, 20) name = rand_string(random.ra
ndint(5, 10)) for _ in range(test_num): print(name, random.randint(0, 100), file=ofs) with open('scores.txt') as name_score_data: name = find_student_with_highest_best_of_three_scores(name_score_data) name_score_data.seek(0) print('top student is', name) if __name__...
from pathlib import Path import os import structlog log = structlog.get_logger() _config = None def get(): global _config if not isinstance(_config, _build_config): _config = _build_config() return _config class _build_config: def __init_
_(self): self._config = {} self.dos_install_dir = os.environ["DOS_BIN"] self.dos_log_dir = os.environ["DOS_LOG"] self.env_var_contexts = ["dos"] # load from toml file self._load_toml_config() # load from env variables self._load_env_vars() def get(s...
def put(self, key, value, context="default"): self.add_config_value(key, value, context=context) def check(self, key): return key in self._config def add_config_value(self, key, value, context="default"): ctx_key = f"{context}_{key}" self._config[ctx_key] = value log.de...