prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# coding=utf-8 from safe.common.exceptions import NoAttributeInLayerError from safe.impact_functions.bases.utilities import check_attribute_exist __author__ = 'Rizky Maulana Nugraha "lucernae" <lana.pcfre@gmail.com>' __date__ = '08/05/15' class ClassifiedVectorExposureMixin(object): def __init__(self): ...
alues in layer if exposure_layer: attr_index = exposure_layer.dataProvider().\ fieldNameIndex(value) unique_list = list() for feature in exposure_layer.getFeatures(): feature_value = feature.attributes()[attr_index] if fe
ature_value not in unique_list: unique_list.append(feature_value) self.exposure_unique_values = unique_list @property def exposure_unique_values(self): return self._exposure_unique_values @exposure_unique_values.setter def exposure_unique_values(self, value): ...
# Copyright (C) 2010 Trinity Western University from cube.books.models import Book from cube.twupass.settings import TWUPASS_LOGOUT_URL from django.contrib.auth.models import User from django.contrib import admin from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template, redi...
atus'), url(r'^reports/books_sold_within_date/$', 'books_sold_within_date', name='books_sold_within_date'), url(r'^reports/user/(\d+)/$', 'user', name='user'), url(r'^reports/book/(\d+)/$', 'book', name='book'), url(r'^reports/metabook/(\d+)/$', 'metabook', name='metabook'), url(r'^reports/h...
ok_list', name="list_metabooks"), url(r'metabooks/update/$', 'update', name="update_metabooks"), ) urlpatterns += patterns('cube.books.views.staff', url(r'^staff/$','staff_list', name="staff"), url(r'^staff_edit/$','staff_edit', name="staff_edit"), url(r'^update_staff/$','update_staff', name="update_st...
''' https://leetcode.com/problems/path-sum/#/description Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below bina
ry tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. ''' # Definition for a binary tree node. # class TreeNode(ob
ject): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ answer = False total = 0 ...
import csv import math import numpy as np from PIL import Image width = 854 height = 480 fov_multiplier = 1.73 # For 60 degrees, set to 1.73. For 90 degrees, set to 1. minwh2 = 0.5 * min(width, height) class Star: def __init__(self, ra, dec, parallax, g_flux, bp_flux, rp_flux): self.ra = ra self...
ck, base_color, CappedRange(0, 0.5, g_normalized)) else: return MixColors(bas
e_color, white, CappedRange(0.5, 1, g_normalized)) # Normalizes a raw flux value into the range [0,1]. def FluxPercentile(flux, sorted_sample): lo = 0 hi = len(sorted_sample) while hi - lo > 1: mid = int((lo + hi) / 2) if flux >= sorted_sample[mid]: lo = mid else: ...
# -*- coding: utf-8 -*- # Some utils import hashlib import uuid def get
_hash(data): """Returns hashed string""" return hashlib.sha256(data
).hexdigest() def get_token(): return str(uuid.uuid4())
se the casenames in public.resource.org can be so # long this varies too much. # if stats['case_name_similarities'][i] < 0.125: # # The case name is wildly different # continue if stats['length_diffs'][i] > 400: # The documents have wildly different lengths ...
self._check_fix_list(self.sha1_hash, self.case_name_dict) if saved_case_name: case_name = saved_case_name else:
print self.url if BROWSER: subprocess.Popen([BROWSER, self.url], shell=False).communicate() case_name = raw_input("Short case name: ") self.case_name_fix_file.write("%s|%s\n" % (self.sha1_hash, case_name)) return case_name, stat...
from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded from urllib.parse import urlparse from httpobs.conf import (RETRIEVER_CONNECT_TIMEOUT, RETRIEVER_CORS_ORIGIN, RETRIEVER_READ_TIMEOUT, RETRIEVER_USER_AGENT) from httpobs.s...
for self-signed certificates s.verify = kwargs['verify'] # Add the headers to the session if kwargs['headers']: s.headers.update(kwargs['headers']) # Set all the cookies and force th
em to be sent only over HTTPS; this might change in the future if kwargs['cookies']: s.cookies.update(kwargs['cookies']) for cookie in s.cookies: cookie.secure = True # Override the User-Agent; some sites (like twitter) don't send the CSP header unless you have a modern # user ...
import unittest import datetime import httpretty as HP import json from urllib.parse import parse_qsl from malaysiaflights.aa import AirAsia as AA class AARequestTests(unittest.TestCase): def url_helper(self, from_, to, date): host = 'https://argon.airasia.com' path = '/api/7.0/search' ...
f.assertTrue(actual) def test_is_connecting_flights_should_return_false_for_direct(self):
json = self.single actual = AA.is_connecting_flights(json, 2) self.assertFalse(actual) class TimeConversionTest(unittest.TestCase): def test_convert_to_api_format_returns_correct_output(self): date_object = datetime.datetime(2015, 9, 25) expected = '25-09-2015' actual = AA...
, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) def lazy_import(): from plaid.model.distribution_breakdown import DistributionBreakdown globals()['DistributionBreakdown'] = Distribut...
API document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Confi
guration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of ...
import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.p
ath.append(os.path.dirname(BASE_DIR)) from global_variables import * from evaluation_helper import * cls_names = g_shape_names img_name_file_list = [os.path.join(g_real_images_voc12val_det_bbox_folder, name+'.txt') for
name in cls_names] det_bbox_mat_file_list = [os.path.join(g_detection_results_folder, x.rstrip()) for x in open(g_rcnn_detection_bbox_mat_filelist)] result_folder = os.path.join(BASE_DIR, 'avp_test_results') test_avp_nv(cls_names, img_name_file_list, det_bbox_mat_file_list, result_folder) img_name_file_list = [os.path...
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # hgweb/__init__.py - web interface to a mercurial repository # # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net> # Copyright 2005 ...
o the terms of the # GN
U General Public License version 2 or any later version. from __future__ import absolute_import import os from .. import error, pycompat, util from ..i18n import _ from . import hgweb_mod, hgwebdir_mod, server def hgweb(config, name=None, baseui=None): """create an hgweb wsgi object config can be one of: ...
rn value a struct with bit fields") def test_inspecttype(self): ffi = FFI(backend=self.Backend()) assert ffi.typeof("long").kind == "primitive" assert ffi.typeof("long(*)(long, long**, ...)").cname == ( "long(*)(long, long * *, ...)") assert ffi.typeof("long(*)(long, lon...
h_value(int fieldnum, long long value); """) fnames = [name for name, cfield in ctype.fields if name and cfield.bitsize > 0] setters = ['case %d: s.%s = value; break;' % iname
for iname in enumerate(fnames)] lib = ffi1.verify(""" struct s1 { %s }; struct sa { char a; struct s1 b; }; #define Gofs_y offsetof(struct s1, y) #define Galign offsetof(struct sa, b) #define Gsize sizeof(struct s1) struct s1 *try_with...
#!/usr/bin/python # coding: utf-8 class Solution(object): def convertToTitle(self, n): """
:type n: int :rtype: str """ return "" if n == 0 else self.convertToTitle((n - 1) / 26) + chr((n
- 1) % 26 + ord('A'))
ismethoddescrip
tor(obj) or inspect.isfunction(obj): return 'function' # Everything else... return 'instance' @property def type(self): """Imitate the tree.Node.type values.""" cls = self._
get_class() if inspect.isclass(cls): return 'classdef' elif inspect.ismodule(cls): return 'file_input' elif inspect.isbuiltin(cls) or inspect.ismethod(cls) or \ inspect.ismethoddescriptor(cls): return 'funcdef' @underscore_memoization ...
AINAGE, format_str='{:>10}', default=None, no_of_dps=3) obj2 = do.FloatData(rdt.ELEVATION, format_str='{:>10}', default=None, no_of_dps=3) obj3 = do.FloatData(rdt.ROUGHNESS, format_str='{:>10}', default=0.0, no_of_dps=3) localcol = rdc.RowDataCollection() localcol._collection.append(obj1...
return False, 'Collections are different lengths' for i in range(0, len
(c1._collection)): if not c1._collection[i].data_type == c2._collection[i].data_type: return False, 'Collections have different data_types' if not c1._collection[i].format_str == c2._collection[i].format_str: return False, 'Collections have different format_str' ...
# coding: utf-8 import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-nomad-activity-feed', v...
'Topic :: Software Development :: Libraries :: Python Modules', ],
)
import pytest from sqlobject import boundattributes from sqlobject import declarative pytestmark = pytest.mark.skipif( True, reason='The module "boundattributes" and its tests were not finished yet') class SOTestMe(object): pass class AttrReplace(boundattributes.BoundAttribute): __unpackargs__ = ...
ef make_object(self, cls, added_class, attr_name, **attrs): if
not self: return cls.singleton().make_object( added_class, attr_name, **attrs) self.replace.added_class = added_class self.replace.name = attr_name assert attrs['replace'] is self.replace del attrs['replace'] self.replace.attrs = attrs return s...
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
replace(c, '_') return s class TensorBoardStaticSerializer(object): """Serialize all the routes from a TensorBoard server to static json.""" def __init__(self, connection, target_path): self.connection = connection EnsureDirectoryExists(os.path.join(target_path, 'data')) self.path = target_path ...
response() destination = self.path + '/data/' + Clean(url) if response.status != 200: raise IOError(url) content = response.read() with open(destination, 'w') as f: f.write(content) return content def GetRouteAndSave(self, route, params=None): """GET given route and params. Seria...
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) an
y later version. # See LICENSE.txt in the main project directory, for more information. """add custom head tags add setting for custom tags (HTML) in <head
> section added: 2012-02-13 (v0.10dev) previously migrate script v054 Revision ID: 280565a54124 Revises: 4d27ff5680e5 Create Date: 2013-05-14 22:38:02.552230 """ # revision identifiers, used by Alembic. revision = '280565a54124' down_revision = '4d27ff5680e5' from alembic.op import execute, inline_literal from sqla...
if not isinstance(loglevel, int): loglevel = getattr(logging, loglevel.upper(), None) if not isinstance(loglevel, int): print('Invalid log level: %s' % loglevel) exit(1) # remove logfile if it already exists if logfname is not None and os.path.exists(logfname): os.remove(log...
= cfg["master_ref"] if master_ref not in refs: raise ValueError("master ref choice must be one of the final refs (" + " ".join(refs.astype(str)) + ")") nonmaster_refs = [i for i in refs if i != master_ref] nonrefs = [i for i in range(nt) if i not in refs] # Ensure that ...
cubes have the same wavelengths. if not all(np.all(cubes[i].wave == wave) for i in range(1, nt)): raise ValueError("all data must have same wavelengths") # ------------------------------------------------------------------------- # PSF for each observation logging.info("setting up PSF for all ...
#!/usr/bin/env python # coding=utf-8 import struct from twisted.internet import defer from txportal.packet import cmcc, huawei from txportal.simulator.handlers import base_han
dler import functools class AuthHandler(base_handler.BasicHandler): def proc_cmccv1(self, req, rundata): resp = cmcc.Portal.newMessage( cmcc.ACK_AUTH, req.userIp, req.serialNo, req.reqId, secret=self.secret ) resp.attrNum = 1 ...
cmcc.ACK_AUTH, req.userIp, req.serialNo, req.reqId, secret=self.secret ) resp.attrNum = 1 resp.attrs = [ (0x05, 'success'), ] return resp def proc_huaweiv1(self, req, rundata): resp = huawei.Portal.newMessa...
"""Support for Satel Integra zone states- represented as binary sensors.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ( CONF_OUTPUTS, CONF_ZONE_NAM...
arySensorDevice): """Representation of an Satel Integra binary sensor.""" def __init__(self, device_number, device_name, zone_type, react_to_signal): """Initialize the
binary_sensor.""" self._device_number = device_number self._name = device_name self._zone_type = zone_type self._state = 0 self._react_to_signal = react_to_signal async def async_added_to_hass(self): """Register callbacks.""" if self._react_to_signal == SIGN...
()) def _get_ordinals_from_text(self, input): # https://github.com/IronLanguages/main/issues/1237 if IRONPYTHON and isinstance(input, bytearray): input = bytes(input) for char in input: ordinal = char if is_integer(char) else ord(char) yield self._test_or...
s(self, input, length
): if not is_string(input): return input input = ''.join(input.split()) if len(input) % length != 0: raise RuntimeError('Expected input to be multiple of %d.' % length) return (input[i:i+length] for i in range(0, len(input), length)) def create_list(self, *it...
self.description = "Remove a package required by othe
r packages" lp1 = pmpkg("pkg1") self.addpkg2db("local", lp1) lp2 = pmpkg("pkg2") lp2.depends = ["pkg1"] self.addpkg2db("local", lp2) lp3 = pmpkg("pkg3") lp3.depends = ["pkg1"] self.addpkg2db("local", lp3) lp4 = pmpkg("pkg4") lp4.d
epends = ["pkg1"] self.addpkg2db("local", lp4) self.args = "-R pkg1 pkg2" self.addrule("!PACMAN_RETCODE=0") self.addrule("PKG_EXIST=pkg1") self.addrule("PKG_EXIST=pkg2") self.addrule("PKG_EXIST=pkg3") self.addrule("PKG_EXIST=pkg4")
class A(Aa): @property def <warning descr="Getter signatu
re should be (self)">x<caret></warning>(self, r):
return "" @x.setter def <warning descr="Setter should not return a value">x</warning>(self, r): return r
ement_shape(element_shape), element_dtype=element_dtype, max_num_elements=max_num_elements, name=name) def _set_handle_data(list_handle, element_shape, element_dtype): """Sets type information on `list_handle` for consistency with graphs.""" # TODO(b/169968286): It would be better if we had a co...
se: num_elements = None if dlist is None: dlist = empty_tensor_list( element_dtype=t.dtype,
element_shape=gen_list_ops.tensor_list_element_shape( op.outputs[0], shape_type=dtypes.int32)) tensor_grad = gen_list_ops.tensor_list_stack( dlist, element_shape=array_ops.slice(array_ops.shape(t), [1], [-1]), element_dtype=t.dtype, num_elements=num_elements) shape_grad =...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as 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 'SocialAccount.uid' db.alter_column(u'socialaccount_soc...
), 'extra_data': ('allauth.socialaccount.fields.JSONField', [], {'default': "'{}'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'provider': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'uid': ('django.db.models.fields.CharField', [], {'max_length': '191'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}) }, u'socialaccount.socialapp': { ...
"""This demo demonstrates how to move the vertex coordinates of a boundary mesh and then updating the interior vertex coordinates of the original mesh by suitably interpolating the vertex coordinates (useful for implementation of ALE methods).""" # Copyright (C) 2008 Solveig Bruvoll and Anders Logg # # This file is pa...
ave received a copy of the GNU Lesser General Public License # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>. # # First added: 2008-05-02 # Last changed: 2008-12-12 from dolfin import * print "This demo is presently broken. See https://bugs.launchpad.net/dolfin/+bug/1047641
" exit() # Create mesh mesh = UnitSquareMesh(20, 20) # Create boundary mesh boundary = BoundaryMesh(mesh) # Move vertices in boundary for x in boundary.coordinates(): x[0] *= 3.0 x[1] += 0.1*sin(5.0*x[0]) # Move mesh mesh.move(boundary) # Plot mesh plot(mesh, interactive=True)
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~...
class Device(Component): class Inventory(Component.Inventory): from RendererFacility import RendererFacility renderer = RendererF
acility() renderer.meta['tip'] = 'the facility that controls how the messages are formatted' def createDevice(self): raise NotImplementedError("class '%s' must override 'device'" % self.__class__.__name__) def __init__(self, name): Component.__init__(self, name, "journal-device") ...
import random import datetime import time import hashlib from django.db import models from django.conf import settings from django.urls import reverse from django.contrib.auth.models import User, Group from django.db.models.signals import post_save from djangopress.core.models import Property from django.utils import ...
elf.banned == True: # if we banned them, they can't then login self.user.is_active = False self.user.save() if self._avatar != self.avatar and self.avatar: image = Image.open(self.avatar) size = settings.ACCOUNTS_USER_LIMITS.get('avatar', {}).get('size...
image.save(self.avatar.path) super(UserProfile, self).save(force_insert, force_update) self._banned = self.banned self._avatar = self.avatar def set_activate_key(self): salt = hashlib.sha1((str(random.random()) + str(random.random())).encode('utf-8')).hexdigest()[:5] key...
#!/usr/bin/env python #------------------------------------------------------------------------------- import os import sys bin_dir = os.path.dirname(os.path.abspath(__file__)) pkg_dir = os.path.abspath(os.path.join(bin_dir, "..")) sys.path.append(pkg_dir) #-----------------------------------------------------------...
lp='lib file(s) with model (e.g. nch, pch) defintions') parser.add_argument('--cell', help='name of t
he cell to be analyzed ' '(top cell by default)') arg_ns = parser.parse_args(args) #--------------------------------------------------------------------------- ckt = cktapps.Ckt() if arg_ns.lib: ckt.read_spice(arg_ns.lib) for spice_file in arg_n...
ted with ACI Fabric 1.0(3f)+ notes: - The C(tenant) and C(filter) used must exist before using this module in your playbook. The M(aci_tenant) and M(aci_filter) modules can be used for this. options: arp_flag: description: - The arp flag to use when the ether_type is arp. choices: [ arp_reply, arp_reque...
='present', choices=['absent', 'present', 'query']), stateful=dict(type='str', choices=['no', 'yes']), tenant=dict(type="str", aliases=['tenant_name']) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) arp_flag = module.params['arp_flag'...
port = module.params['dst_port'] if dst_port in FILTER_PORT_MAPPING.keys(): dst_port = FILTER_PORT_MAPPING[dst_port] dst_end = module.params['dst_port_end'] if dst_end in FILTER_PORT_MAPPING.keys(): dst_end = FILTER_PORT_MAPPING[dst_end] dst_start = module.params['dst_port_start'] if...
# -*- coding: utf-8 -
*- from django.db import models, migrations class Migration(migra
tions.Migration): dependencies = [ ('events', '0021_auto_20171023_1358'), ] operations = [ migrations.AlterField( model_name='inductioninterest', name='age', field=models.CharField(max_length=100, choices=[(b'', b'-----'), (b'20to25', b'20 to 25 years'),...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014-2015 # # STIC - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of Modelado de Servicios TIC. # # Modelado de Servicios TIC is free software: you can redistribute it and/or modify it under # the terms of the GNU Affe...
nagstr2 += "}\n\n" #CREACION FICHEROS HOST_GROUP nagstr3 += "## host/" + generacionpaginas.formatstring(i[3][0]) + ".cfg \n\n" nagstr3 += " " ficheroservicio.write(nag
str1) ficherohost.write(nagstr3) ficherohost_group.write(nagstr2) ficheroservicio.close ficherohost.close ficherohost_group.close GeneraNagios()
args.get('reboot') force_s = request.args.get('force') template = request.args.get('template') reboot=False force=False skipscan=True skip_del=False if template != 'dom0': usage += "\n The only supported template is 'dom0'" return json_msg(usage) if reboot_s == "Tru...
= 'Usage: ' + request.url_root + 'container/send_image?url=<image url>&template=<template name>' overc=Overc.Overc() url = request.args.get('url') template = request.args.
get('template') if url is None or template is None: return json_msg(usage) template_list = os.listdir("/etc/overc/container") if template not in template_list: usage += "\n The template name is not valid" return json_msg(usage) req = urllib2.Request(url) req.get_method = lam...
from django.contrib import admin from . import models from django_markdown.admin import MarkdownModelAdmin from django_markdown.widgets import AdminMarkdownWidget from django.db.models import TextField # Register your models here. class SnippetTagAdmin(admin.ModelAdmin): list_display = ('slug',) class SnippetAdm...
: ['modified_date'], 'classes': ['collapse']}), ('Tag Library', {'fields': ['snippet_tags']}) ] list_display = ('snippet_title', 'author', 'create_date', 'modified_date') search_fields = ['snippet_title'] formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}} list_filter = ['crea...
.SnippetTag, SnippetTagAdmin)
for time_record in time_records: response_object.append(time_record.json_object()) if more: self.response.headers.add('X-Cursor', next_cursor.urlsafe()) else: # List all Time Records time_records, next_cursor...
Create with a Object other than the Project as this Comment's parent if parent_type == 'milestones': # Milestones milestone = model.Milestone.for_number(project_key, int(parent_id)) if not milestone: self.abort(404) ...
d) if (not parent_key or (project_key != parent_key.parent())): self.abort(400) parent = parent_key.get() if not (parent and isinstance(parent, model.TimeRecord)): self.abort(404) # Create with `Project` and `Parent` ...
from setuptools import setup from ast import literal_eval def get_version(source='xpclr/__init__.py'): with open(source) as sf: for line in sf: if line.startswith('__version__'):
return literal_eval(line.split('=')[-1].lstrip()) raise ValueError("__version__ not found") VERSION = get_versi
on() DISTNAME = 'xpclr' PACKAGE_NAME = 'xpclr' DESCRIPTION = 'Code to compute xpclr as described in Chen 2010' with open('README.md') as f: LONG_DESCRIPTION = f.read() MAINTAINER = 'Nicholas Harding', MAINTAINER_EMAIL = 'nicholas.harding@bdi.ox.ac.uk', URL = 'https://github.com/hardingnj/xpclr' DOWNLOAD_URL...
#!/usr/bin/python import apt import apt.progress import apt_pkg import logging import re import sys logging.basicConfig(filename1='/var/log/supervisor/rps.log', format='%(asctime)s %(levelname)s: deb_install: %(message)s', level=logging.INFO) logging.getLogger().setLevel(logging.INFO) class control_p...
continue p.candidate = highest_v logging.info("package %s, selected version: %s, priority: %s/%d", name, p.candidate.version, p.candidate.priority, p.candidate.policy_priority) logging.info("Going to install package %s", name) ...
# do not run for the subsequent ORed packages break if not have_version: logging.fatal("Could not find suitable package %s", pstr) def install(self): self.cache.commit() if __name__ == '__main__': if len(sys.argv) != 2: print "E: usage: %s /...
from django.db import models from django.utils import timezone import datetime class Question(models.Model): """ Question object model """
question_text = models.CharField(max_length=200) pub_dat
e = models.DateTimeField('date published') def __unicode__(self): # __unicode__ on Python 2 return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) was_published_recently.admin_order_field = 'pub_date' ...
#!/usr/bin/python import simplejson as json i = open('/proc/cpuinfo') my_text = i.readlines() i.close() username = "" for line in my_text: line = line.strip() ar = line.split(' ') if ar[0].startswith('Serial'): username = "a" + ar[1] if not username: exit(-1) o = open('/home/p
i/.cgminer/cgminer.conf', 'w'); pools = [] pools.append({"url": "stratum+tcp://ghash
.io:3333", "user": username, "pass": "12345"}) conf = {"pools": pools, "api-listen" : "true", "api-port" : "4028", "api-allow" : "W:127.0.0.1"} txt = json.dumps(conf, sort_keys=True, indent=4 * ' ') o.write(txt) o.write("\n"); o.close()
from django.conf.urls.defaults import * from django.contrib import admin from fumblerooski.feeds import CoachesFeed feeds = { 'coaches': CoachesFeed, } admin.autodiscover() urlpatterns = patterns('', url(r'^admin/coach_totals/', "fumblerooski.college.views.admin_coach_totals"), url(r'^admin/doc/', incl...
-a-z]+)/vs/$', 'coach_vs', name="coach_vs"), url(r'^coaches/detail/(?P<coach>\d+-[-a-z]+)/vs/(?P<coach2>\d+-[-a-z]+)/$', 'coach_compare', name="coach_compare"), url(r'^coaches/assistants/$', 'assistant_index'), url(r'^coaches/common/(?P<coach>\d+-[-a-z]+)/(?P<coach2>\d+-[-a-z]+)/$', 'coach_common'), ...
), url(r'^coaches/hires/(?P<year>\d\d\d\d)/$', 'coaching_hires'), )
# -*- coding: utf-8 -*- ''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms...
ADER='Fiware-ServicePath' SMPP_URL='http://sbc04:5371' SMPP_FROM='682996050' DEF_ENTITY_TYPE='th
ing' DEF_TYPE='string' PATH_UL20_COMMAND='/iot/ngsi/d/updateContext' PATH_MQTT_COMMAND='/iot/ngsi/mqtt/updateContext' PATH_UL20_SIMULATOR='/simulaClient/ul20Command' TIMEOUT_COMMAND=10 MQTT_APIKEY='1234' UL20_APIKEY='apikey3'
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from unittest.mock import Mock, call from tinyrpc.server import RPCServer from tinyrpc.transports import ServerTransport from tinyrpc.protocols import RPCProtocol, RPCResponse from tinyrpc.dispatch import RPCDispatcher CONTEXT='sapperdeflap' RECMSG='out of...
r = RPCServer(transport, protoco
l, dispatcher) server.receive_one_message() transport.receive_message.assert_called() protocol.parse_request.assert_called_with(RECMSG) dispatcher.dispatch.assert_called_with(PARMSG, None) dispatcher.dispatch().serialize.assert_called() transport.send_reply.assert_called_with(CONTEXT, SERMSG) ...
# -*- coding: utf-8 -*- # # Copyright (C) 2017 European Synchrotron Radiation Facility, Grenoble, France # # Principal author: Wout De Nolf (wout.de_nolf@esrf.eu) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software")...
ify, merge, publish, distribute, sublicense, and/or 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, EXPR...
#!/usr/bin/env python """Grover's quantum search algorithm example.""" from sympy import pprint from sympy.physics.quantum import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (OracleGate, superposition_basis, WGate, grover_iteration) def demo_vgate_app(v):...
ction f(x)') print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)') print('> and 0 (False in our
case) otherwise') print() nqubits = 2 print('nqubits = ', nqubits) v = OracleGate(nqubits, black_box) print('Oracle or v = OracleGate(%r, black_box)' % nqubits) print() psi = superposition_basis(nqubits) print('psi:') pprint(psi) demo_vgate_app(v) print('qapply(v*psi)') ...
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import numba from src_legacy.fourier_series.buffer.ringbuffer import Ringbuffer @numba.vectorize(nopython=True) def legendre_recursio...
array_size=self.size, dtype=float, start_index=self.start_index, array_size_increment=None, array_margin=0) deg = self.start_index
while self.max_degree is None or deg <= self.max_degree - 1: p1 = buffer[deg - 1, :] p2 = buffer[deg - 2, :] arr = legendre_recursion(deg, self.arg, p1, p2) # ~73% buffer[:] = arr # ~27% if skip == 0: yield ...
# encoding: utf-8 """ corduroy.config Internal state """ from __future__ import with_statement import os, sys from .atoms import odict, adict, Document # LATER: add some sort of rcfile support... # from inspect import getouterframes, currentframe # _,filename,_,_,_,_ = getouterframes(currentframe())[-1] # print "fro...
"dict":adict }), "http":adict({ "max_clients":10, "max_redirects":6, "timeout":60*60, "io_loop":None }) }) try: import simplejson as _json except ImportError: import json as _json class json(
object): @classmethod def decode(cls, string, **opts): """Decode the given JSON string. :param string: the JSON string to decode :type string: basestring :return: the corresponding Python data structure :rtype: object """ return _json.loads(string, ob...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Rackspace Hosting # # 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...
link=("horizon:project:database_backups:detail"), verbose_name=_("Name")) created = tables.Column("created", verbose_name=_("Created At"), filters=
[filters.parse_isotime]) location = tables.Column(lambda obj: _("Download"), link=lambda obj: obj.locationRef, verbose_name=_("Backup File")) instance = tables.Column(db_name, link=db_link, verbose_name=_("Database")) sta...
""" Forum attachments models ======================== This module defines models provided by the ``forum_attac
hments`` application. """ from machina.apps.forum_conversation.forum_attachments.abstract_models import AbstractAttachment from machina.core.db.models import model_factory A
ttachment = model_factory(AbstractAttachment)
from nose.tools import eq_, ok_ from remo.base.tests import RemoTestCase from remo.base.utils import get_date from remo.profiles.forms import ChangeUserForm, UserStatusForm from remo.profiles.models import UserStatus from remo.profiles.tests import UserFactory, UserStatusFactory class ChangeUserFormTest(RemoTestCase...
_date=start_date) form = UserStatusForm(data, instance=user_status) ok_(form.is_valid()) ok_(not user_status.end_date) db_obj = form.save() eq_(db_obj.expected_date, get_date()) eq_(db_obj.user.
get_full_name(), user.get_full_name()) ok_(db_obj.return_date)
"""Public API for Fortran parser. Module content -------------- """ from __future__ import absolute_import #Author: Pearu Peterson <pearu@cens.ioc.ee> #Created: Oct 2006 __autodoc__ = ['get_reader', 'parse', 'walk'] from . import Fortran2003 # import all Statement classes: from .base_classes import EndStatement, cla...
`tree` BeginSource blocktype='beginsource' name='<cStringIO.StringI object at 0x1798030> mode=fix90' a=AttributeHolder: external_subprogram=<dict with keys ['foo']>
content: Subroutine args=['a'] item=Line('subroutine foo(a)',(3, 3),'') a=AttributeHolder: variables=<dict with keys ['a']> content: Integer select...
#!/usr/bin/env python3 ''' Make a stream emit at the pace of a slower stream Pros: Introduce a delay between events in an otherwise rapid stream (like range) Cons: When the stream being delayed runs out of events to push, the zipped stream will keep pushing events, defined with the lambda fn ...
, it will keep sending empty # events to the subscribers lambda _, n: n ) sub1 = source.subscribe( lambda v : print("Value published to observer 1: {0}
".format(v)), lambda e : print("Error! {0}".format(e)), lambda : print("Completed!") ) sub2 = source.subscribe( lambda v : print("Value published to observer 2: {0}".format(v)), lambda e : print("Error! {0}".format(e)), lambda : print("Completed!") ) # As noted above, we have to dispose the subscr...
alt13 = 1 elif ((FIRST <= LA13_0 <= THIRD)) : alt13 = 2 else: nvae = NoViableAltException("", 13, 0, self.input) raise nvae if alt13 == 1: pass self.match(se...
et([7, 8]) FOLLOW_monthday_in_monthdays320 = frozenset([1, 10]) FOLLOW_set_in_monthday340 = frozenset([1]) FOLLOW_DAY_in_weekdays365 = frozenset([1]) FOLLOW_weekday_in_weekdays373 = frozenset([1, 10]) FOLLOW_COMMA_in_weekdays376 = frozenset([19, 20, 21, 22, 23, 24, 25, 26]) FOLLOW_weekday_in_wee...
W_month_in_months486 = frozenset([1, 10]) FOLLOW_COMMA_in_months489 = frozenset([27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]) FOLLOW_month_in_months491 = frozenset([1, 10]) FOLLOW_set_in_month510 = frozenset([1]) FOLLOW_QUARTER_in_quarterspec583 = frozenset([1]) FOLLOW_quarter_ordinals_in_qu...
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('contentstore.management.commands.tests.test_sync_c...
from cms.djangoapps.contentst
ore.management.commands.tests.test_sync_courses import *
) self.max_dist = max_dist self.hicmesh = None def _plot(self, region=None, cax=None): if region is None: raise ValueError("Cannot plot triangle plot for whole genome.") hm, sr = sub_matrix_regions(self.hic_matrix, self.regions, region) hm[np.tril_indices(hm.sha...
.start) if self.max_dist is not None and self.max_dist/2 < ylim_max: ylim_max = self.max_dist/2 self.ax.set_ylim(0, ylim_max) # remove y ticks self.ax.set_yticks([])
# hide background patch self.ax.patch.set_visible(False) if self.show_colorbar: self.add_colorbar(cax) def set_clim(self, vmin, vmax): self.hicmesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.co...
from django.db import models from django.contrib.auth.models import User class OrganisationType(models.Model): type_desc = models.CharField(max_length=200) def __unicode__(self): return self.type_desc class Address(models.Model): street_address = models.CharField(max_length=100) city = model...
itle = models.CharField(max_length=200) organisation_type = models.ForeignKey(OrganisationType) def __unicode__(self)
: return self.title class Customer(HattiUser): title = models.CharField(max_length=200, blank=True, null=True) is_org = models.BooleanField(); org_type = models.ForeignKey(OrganisationType) company = models.CharField(max_length = 200) def __unicode__(self, arg): return unicode(self.user) ...
# Please see the file LICENSE.txt for details. # from __future__ import print_function import sys, os import logging, logging.handlers from ginga import AstroImage from ginga.gtkw import GtkHelp from ginga.gtkw.ImageViewGtk import CanvasView from ginga.canvas.CanvasObject import get_canvas_types from ginga import colo...
False) roo
t.add(vbox) def get_widget(self): return self.root def set_drawparams(self, w): index = self.wdrawtype.get_active() kind = self.drawtypes[index] index = self.wdrawcolor.get_active() fill = self.wfill.get_active() alpha = self.walpha.get_value() params =...
# (c) 2016 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 dis...
if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except: pas
s fixture_data[path] = data return data class TestMlnxosModule(ModuleTestCase): def execute_module(self, failed=False, changed=False, commands=None, is_updates=False, sort=True, transport='cli'): self.load_fixtures(commands, transport=transport) if failed: result = self.fai...
"""Various useful tools.""" import copy import datetime import logging # FIXME: temporary backward compatibility from eaf.core import Vec3 as Point LOG_FORMAT = ( "[%(asctime)s] %(levelname)-8s %(name)s[%(funcName)s]:%(lineno)s: " "%(message)s" ) """Log message format string.""" TIME_FORMAT = "%H:%M:%S,%03...
_val") return min(max(val, min_val), max_val) class dotdict(dict): # pylint: disable=invalid-name """Container for dot element
s access.""" def __init__(self, *args, **kwargs): super(dotdict, self).__init__(*args, **kwargs) self.__dict__ = self self._wrap_nested() def _wrap_nested(self): """Wrap nested dicts for deep dot access.""" for key, value in self.items(): if isinstance(valu...
# -*- coding: utf-8 -*- import json from flask import jsonify from flask import render_template, request, url_for, redirect import time, random #------------------------------------------------------------------------------ def get_desktop_items_data(): """ Returns items for Desktop in JSON array: title ...
ndered dialog" dlg = request.args.get("dlg", "") title = request.args.get("title", "") win_id = int(time.time()) template = "dialogs/%s.html" % dlg content = { "title": title, "dlg": dlg, "win_id": win_id,
"wnd_left": 400, "wnd_top": 300, "width": 290, "height": 150, } return render_template(template, **content) #------------------------------------------------------------------------------
#!/usr/bin/env python3 from http.server import H
TTPServer, CGIHTTPRequestHandler port = 8000 httpd = HTTPServer(('', port), CGIHTTPRequestHandler) print("Starting simple_httpd on port: " + str(httpd.server_port)) h
ttpd.serve_forever()
""" Unittest for time.strftime """ import calendar import sys import os import re from test import test_support import time import unittest # helper functions def fixasctime(s): if s[8] == ' ': s = s[:8] + '0' + s[9:] return s def escapestr(text, ampm): """ Escape text to deal with possible ...
# %x see below ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%y', '%02d' % (now[0]%100), 'year without century'), ('%Y', '%d' % now[0], 'year with century'), # %Z see below ('%%', '%', 'single percent sign'), ) for e in ...
value error try: result = time.strftime(e[0], now) except ValueError, error: self.fail("strftime '%s' format gave error: %s" % (e[0], error)) if re.match(escapestr(e[1], self.ampm), result): continue if not result or result...
# pylint: disable=I0011,C0301 from __future__ import absolute_import, unicode_literals import os from setuptools import find_packages, setup from namespaced_session import __version__ with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run fr...
bspath(__file__), os.pard
ir))) setup( name='django-namespaced-session', version=__version__, packages=find_packages(exclude=['tests']), include_package_data=True, test_suite="runtests.main", license='MIT', description='Django app which makes it easier to work with dictionaries in sessions', long_description=REA...
test = { 'name': '', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> type(imdb_by_year) == tables.Table True
>>> imdb_by_year.column('Title').take(range(3)) array(['The Kid (1921)', 'The Gold Rush (1925
)', 'The General (1926)'], dtype='<U75') """, 'hidden': False, 'locked': False }, ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest' } ] }
. By default this will create: * User `testuser` with password `testpassword` * User `certuser` with password `certpass` * Two security sources * Permissions on * riak_kv.get * riak_kv.put * riak_kv.delete * riak_kv.index * riak_kv.list_keys * riak_kv.lis...
conf) conf = re.sub(r'storage_backend\s+=\s+\S+', r'storage_backend = leveldb', conf) conf = re.sub(r's
sl.keyfile\s+=\s+\S+', r'ssl.keyfile = ' + self.cert_dir + '/server.key', conf) conf = re.sub(r'ssl.cacertfile\s+=\s+\S+', r'ssl.cacertfile = ' + self.cert_dir + '/ca.crt', conf) conf = re.sub(r...
# -*- coding: utf-8 -*- # Copyright 2015-2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.addons.connector_carepoint.unit import mapper from .common import SetUpCarepointBase class TestCarepointImporterMapper(SetUpCarepointBase): def setUp(self): super(Te...
mporter.backend_id(True) expect = {'backend_id': self.importer.backend_record.id} self.assertDictEqual(expect, res) def test_company_id(self): """ It should map company_id correctly """
res = self.importer.company_id(True) expect = {'company_id': self.importer.backend_record.company_id.id} self.assertDictEqual(expect, res)
r_node(node) if item is None: return parent_index = self.index_for_item(item.parent_item) if parent_index is None: return row = item.row() self.removeRow(row, parent_index) self.insertRow(row, parent_index, node) # CK: This is a pretty ineffec...
s project " "so that you can edit it?" % node.get('name') or node.tag) b = (QMessageBox.Yes, QMessageBox.No) ans = QMessageBox.question(None, title, msg, *b) if ans == QMessageBox.Yes: self.make_item_local(i
tem) else: return False del title, msg, b, ans # Clean up namespace if value.toInt()[0] == Qt.Checked: value = QVariant('True') else: value = QVariant('False') # convert the value to a string and set the...
from setuptools import setup setup( name='quotequail', version='0.2.3', url='http://github.com/closeio/quotequail', license='MIT', author='Thomas Steinacher', author_email='engineering@close.io', maintainer='Thomas Steinacher', maintainer_email='engineering@close.io', description='A...
cription=__doc__, packages=[ 'quotequail', ], test_suite='tests', tests_require=['lxml'], platforms='any', classifiers=[ 'Environment ::
Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Lan...
#!/usr/bin/env python # -*- coding: utf-8 -*- import time class CameraClass(object): ''' docstring for CameraClass ''' def __init__(self): super(CameraClass, self).__init__() def visible_target(self): ''' Returns true if target is visible ''' retur...
= PiCamera()
try: camera.start_preview() time.sleep(10) camera.stop_preview() finally: camera.close() except ImportError: pass
import sys import socket from PyQt5.QtWidgets import QApplication from qt_DisplayWindow import DisplayWindow from Server import Server def main(camID): hostname = socket.gethostname() ip_address = socket.gethostbyname_ex(hostname)[2][-1] print(hostname, ip_address) port = 12349 app = QApplicat...
() # connect server -> display slots server.selfie.connect(display.selfie) s
erver.email.connect(display.email) server.status.connect(display.show_msg) server.start() ret = app.exec_() server.join() sys.exit(ret) if __name__ == '__main__': main(0)
import os from pathlib import Path from PIL import Image import pyconfig import pydice class ImageNotSupported(Exception): pass class BeardedDie: def __init__(self, die): self.die = die # Time to strap our to_image to pydice's Die if pyconfig.get('dicebeard.images_path'): ...
os.path.dirname(__file__)) / 'images' def __getattr__(self, attr): return getattr(self.die, attr) def to_image(self): '''Emits a PIL.Image of the die is possible''' die_image_path = (self.images_path / 'd{}'.format(self.faces.stop-1) / ...
Image.open(str(die_image_path)) except FileNotFoundError: raise ImageNotSupported( '{} is not currently supported.'.format(self.name))
# encoding: 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 'Group.auth' db.add_column('people_group', 'auth', self.gf('django.db.models.fields.Boolean...
.DateField', [], {'null': 'True', 'blank': 'True'}), 'ddate': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'fname': ('django.db.mode
ls.fields.CharField', [], {'max_length': '150'}), 'gender': ('django.db.models.fields.CharField', [], {'default': "'ns'", 'max_length': '10'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['people.Group']", 'null': 'True', 'blank': 'True'}...
from pprint import pprint from base.models import Colaborador def get_create_colaborador_by_user(user): try: colab = Colaborador.objects.get(user__username=user.username) except Colaborador.DoesNotExist:
colab = Co
laborador( user=user, matricula=72000+user.id, cpf=72000+user.id, ) colab.save() return colab
import json import copy from util.json_request import JsonResponse from django.http import HttpResponseBadRequest from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django_future.csrf import ensure_csrf_cookie from edxmako.shortcuts import rende...
json representing all checklists. checklist_in
dex is not supported for GET at this time. POST or PUT json: updates the checked state for items within a particular checklist. checklist_index is required. """ course_key = CourseKey.from_string(course_key_string) if not has_course_access(request.user, course_key): raise PermissionDenie...
imp
ort numpy as np import sys R = np.eye
(int(sys.argv[2])) np.savetxt(sys.argv[1]+'/R.txt', R)
from symbol.builder import FasterRcnn as Detector from models.dcn.builder import DCNResNetC4 as Backbone from symbol.builder import Neck from symbol.builder import RpnHead from symbol.builder import RoiAlign as RoiExtractor from symbol.builder import BboxC5V1Head as BboxHead from mxnext.complicate import normalizer_fac...
" class pretrain: prefix = "pretrain_model/resnet%s_v1b" % BackboneParam.depth epoch = 0 fixed_param =
["conv0", "stage1", "gamma", "beta"] class OptimizeParam: class optimizer: type = "sgd" lr = 0.01 / 8 * len(KvstoreParam.gpus) * KvstoreParam.batch_image momentum = 0.9 wd = 0.0001 clip_gradient = 35 class schedule: begin_ep...
# -*- coding: utf-8 -*- """ :copyright: 2005-2008 by The PIDA Project :license: GPL 2 or later (see README/COPYING/LICENSE) """ import gtk from pygtkhelpers.delegates import SlaveView # locale from pida.core.locale import Locale locale
= Locale('pida') _ = locale.get
text class PidaView(SlaveView): # Set this to make your views memorable. key = None icon_name = gtk.STOCK_INFO label_text = _('Pida View') pane = None def create_ui(self): """Create the user interface here""" def create_tab_label_icon(self): return gtk.image_new_from_...
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
tal/brain/notebooks",
"root location where to store notebooks") ORIG_ARGV = sys.argv # Main notebook process calls itself with argv[1]="kernel" to start kernel # subprocesses. IS_KERNEL = len(sys.argv) > 1 and sys.argv[1] == "kernel" def main(unused_argv): sys.argv = ORIG_ARGV if not IS_KERNEL: # Drop...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See t
he top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class REvd(RPackage): """evd: Functions for Extreme Value Distributions""" homepage = "https://cloud.r-project.org/package=evd" url = "https://cloud.r-project.org/src/contrib/evd_2.3-3.tar....
97433d90fb80b8c363877baee4559b4')
-------------------------------------------------- from __future__ import absolute_import, division, print_function import unittest import inspect import warnings from skbio.util._decorator import classproperty, overrides from skbio.util._decorator import (stable, experimental, deprecated, ...
Add 42, or something else, to x.\n\n" " State: Stable as of 0.1.1.\n\n"
" Parameters") self.assertTrue(f.__doc__.startswith(e1)) def test_function_signature(self): f = self._get_f('0.1.0') expected = inspect.ArgSpec( args=['x', 'y'], varargs=None, keywords=None, defaults=(42,)) self.assertEqual(inspect.getargspec(f), expected)...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import django_castle try: from setuptools import setup except ImportError: from distutils.core import setup version = django_castle.__version__ if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('pytho...
-castle', version=version, description="""A dj
ango integration for the castle.io service""", long_description=readme + '\n\n' + history, author='Jens Alm', author_email='jens.alm@prorenata.se', url='https://github.com/ulmus/django-castle', packages=[ 'django_castle', ], include_package_data=True, install_requires=[ ], ...
# The MIT License # # Copyright (c) 2008 James Piechota # # 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...
"" self._maxInfluences = 0 self.deformers = [] self.weights = [] def name(self): return self._fullName def read( self, fullName ): '''Load skin weights fro
m a Massive .w (weights) file''' try: if not os.path.isfile(fullName): return self._fullName = fullName self._path = os.path.dirname( fullName ) fileHandle = open(self._fullName, "r") deformers = [] tokens = [] weights = [] maxInfluences = 0 for line in fileHandle: ...
# Generated by Django 2.2.11 on 2020-11-09 17:00 import daphne_context.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
RemoveField( model_name='userinformation', name='mycroft_session', ), migrations.CreateModel( name='MycroftUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('...
.utils.generate_mycroft_session, max_length=9)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Archive', fields=[ ('id', models.AutoField(verb...
me='ID', serialize=False, auto_created=True, primary_key=True)), ('eadid', models.CharField(unique=True, max_length=50, verbose_name=b'EAD Identifier')), ('title', models.CharField(max_length=200)), ('date', models.DateTimeField(auto_now_add=True, verbose_name=b'Date remo...
eleted. These comments will be displayed to anyone who had the finding aid bookmarked and returns after it is gone.', max_length=400, blank=True)), ], options={ 'verbose_name': 'Deleted Record', }, bases=(models.Model,), ), ]
import logging import inspect import numpy as np from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask, make_xtalk_mask, make_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager impor...
ands(commands) with self.readout(PlsrDAC=scan_parameter_value): cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0] scan_loop(self, cal_lvl1_command, repeat_command=self.n_injectio...
_function=None, digital_injection=False, enable_shift_masks=self.enable_shift_masks, disable_shift_masks=self.disable_shift_masks, restore_shift_masks=False, mask=invert_pixel_mask(self.register.get_pixel_register_value('Enable')) if self.use_enable_mask else None, double_column_correction=self.pulser_dac_correction) ...
#!/usr/bin/env python """ Parse a file and write output to another. """ from optparse import OptionParser import re from collections import OrderedDict parser = OptionParser() parser.add_option("-i", "--input", dest="input_filepath", help="input filepath") parser.add_option("-o", "--output", dest="output_filepat...
1])) output_file.write("{0} => __( '
{1}', 'ev' ),\n".format(line[0], line[1])) print "Completed"
def f(m,n):
ans = 1 while (m - n >= 0): (ans,m) = (ans*2,m-n) return(ans)
"""Test that resize event works correctly. Expected behaviour: One window will be opened. Resize the window and ensure that the dimensions printed to the terminal are correct. You should see a green border inside the window but no red. Close the window or press ESC to end the test. """ import unit...
% (width, height)) def test_resize(self): w = window.Window(200, 200, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close()
from z
ope.interface import Interface class IUWOshThemeLayer(Interface): """ Marker
interface that defines a browser layer """
ylename", "Style name", "StyleName", None), ("width", "Width", "Width", None), ("height", "Height", "Height", None), ("size", "Size", "Size", None), ("title", "Title", "Title", None), ("zindex", "Z Index", "zIndex", None), ] @classm...
getTitle(self): return DOM.getAttribute(self.element, "title") def setElement(self, element):
"""Set the DOM element associated with the UIObject.""" self.element = element def setHeight(self, height): """Set the height of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ if height is None: ...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import import os import unittest from pymatgen.io.lammps.sets import LammpsInputSet __author__ = 'Kiran Mathew' __email__ = '...
data_file = os.path.join(test_dir, "data.peptide") self.data_filename = "test_data.peptide" self.inpu
t_filename = "test_input.peptide" self.settings = { "pair_style": "lj/charmm/coul/long 8.0 10.0 10.0", "kspace_style": "pppm 0.0001", "fix_1": "1 all nvt temp 275.0 275.0 100.0 tchain 1", "fix_2": "2 all shake 0.0001 10 100 b 4 6 8 10 12 14 18 a 31" } ...
from csv import DictReader import os from rest_framework import status from rest_framework.viewsets import ViewSet from rest_framework.exceptions import NotFound from rest_framework.response import Response import odatagym_app.settings as ods import logging logger = logging.getLogger('odata_gym') class DatasetsHan...
ter]) data = [x for x in reader] return Response(data, status=status.HTTP_200_OK) else: raise NotFound('There is no da
taset %s for %s' % (dataset_name, dataset_folder))
#!/usr/bin/env python import re import os import time import sys import unittest import ConfigParser from setuptools import setup, Command def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() class SQLiteTest(Command): """ Run the tests on SQLite """ description = ...
ODULE), test_suite='tests', test_loader='trytond.test_loader:Loader', cmdclass={ 'test': SQLiteTest, 'test_on_postgre
s': PostgresTest, } )
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefau
lt('DJANGO_SETTINGS_MODULE', 'settings.prod') from django.core.management i
mport execute_from_command_line execute_from_command_line(sys.argv)
e 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. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or F...
ess_token_secret = response.content['oauth_token_secret'] ) if req.oauth1_debug: req.g['oauth1_debug_msg'] += str(response.content) + "<br/>" email, identity = self._get_user_email_and_id(response.content, req) if identity: # If identity...
s found, add the name of the provider at the # beginning of the identity because different providers may have # different users with same id. identity = "%s:%s" % (req.g['oauth1_provider_name'], identity) else: req.g['oauth1_msg'] = 23 # Delete the token ...
# All nodes are of the form [path1, child1, path2, child2] # or <value> from ethereum import utils from ethereum.db import EphemDB, ListeningDB import rlp, sys import copy hashfunc = utils.sha3 HASHLEN = 32 # 0100000101010111010000110100100101001001 -> ASCII def decode_bin(x): return ''.join([chr(int(x[i:i+8],...
x[i] = evaluate_node(dbget(x[i], db)) elif isinstance(x, list): x[i] = evaluate_node(x[
i]) return x o2 = rlp.encode(evaluate_node(o)) return o2 def decompress_branch(branch): branch = rlp.decode(branch) db = EphemDB() def evaluate_node(x): if isinstance(x, list): x = [evaluate_node(n) for n in x] x = dbput(x, db) return x evaluate_no...
# Copyright 2010 Ramon Xuriguera # # This file is part of BibtexIndexMaker. # # BibtexIndexMaker 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 late...
def get_path(self): return self.__path def set_path(self, value): self.__path = value self.pathChanged.emit() path = QtCore.pyqtProperty(QtCore.QString, get_path, set_path) @QtCore.pyqtSlot() def chooseFile(self): if self.mode == self.DIR: self.path = QtG...
e.setText(self.path) class LogsTextEdit(QtGui.QTextEdit): colors = {'DEBUG':QtGui.QColor(100, 100, 100), 'INFO':QtGui.QColor(0, 0, 0), 'WARNING':QtGui.QColor(222, 145, 2), 'ERROR':QtGui.QColor(191, 21, 43), 'CRITICAL':QtGui.QColor(191, 21, 43)} ...
#!/usr/bin/python import urllib2 import json, csv import subprocess import sys import platform import getopt all_flag = False download_flag = False filename=None offcore_events=[] try: opts, args = getopt.getopt(sys.argv[1:],'a,f:,d',['all','file=','download']) for o, a in opts: if o i...
ame') and name.lower() in event['EventName'].lower(): print (event['EventName']+':'+event['BriefDescription']) for ev_code in event['EventCode'].split(', '): print ('cpu/umask=%s,event=%s,name=%s%s%s%s%s/' % ( event['UMask'], ev_code, event['EventName'...
se '', (',inv=%s' % (event['Invert'])) if event['Invert'] != '0' else '', (',any=%s' % (event['AnyThread'])) if event['AnyThread'] != '0' else '', (',edge') if event['EdgeDetect'] != '0' else '')) name=raw_input("Event to query (empty enter...
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.template.response import TemplateResponse from django.test import TestCase from django.test.utils import
override_settings from .models import Action @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminCustomUrlsTest(TestCase): fixtures = ['users.json', 'actions.json'] def setUp(self): self.client.login(username='super', password='secret') def tearD...
self.client.get('/custom_urls/admin/admin_custom_urls/action/!add/') self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def testAddWithGETArgs(self): response = self.client.get('/custom_urls/admin/admin_custom_urls/action/!add/', {'name': 'My Actio...