prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
import vtk reader = vtk.vtkRectilinearGridReader() reader.SetFileName("D:/Notebooks_Bogota2017/SS_2017/data/jet4_0.500.vtk") reader.Update() output = reader.GetOutput() xmi, xma, ymi, yma, zmi, zma = output.GetBounds() # Color Transfer Function and LookUpTable # Create transfer mapping scalar value to color colorTra...
pper to the actor streamlineActor = vtk.vtkActor() streamlineActor.SetMapper(streamlineMapper) streamlineActor.GetProperty().SetLineWidth(2.0) # Add the outline of the data set gOutline = vtk.vtkRectilinearGridOutlineFilter() gOutline.SetInputData(output) gOutlineMapper = vtk.vtkPolyDataMapper() gOutlineMapper.SetInpu...
Actor.SetMapper(gOutlineMapper) gOutlineActor.GetProperty().SetColor(0.5,0.5,0.5) # Rendering / Window renderer = vtk.vtkRenderer() renderer.SetBackground(0.0, 0.0, 0.0) #renderer.AddActor(streamlineActor) # renderer.AddActor(streamRibbonsActor) renderer.AddActor(streamTubeActor) renderer.AddActor(outlineActor) render...
ut() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() older_assigned_and_completed_key = peer.ReviewSummary( assigned_count=1, completed_count=1, reviewee_key=second_reviewee_key, submission_key...
lookup by key to fail. def pick_and_remove(unused_cls, candidates): db.delete(summary_key) return candidates[0] fn = types.MethodType( pick_and_remove, review_module.Manager(), review_module.Manager) self.swap(
review_module.Manager, '_choose_assignment_candidate', fn) self.assertRaises( KeyError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_raises_not_assignable_when_already_assigned(self): summary_key = peer.ReviewSummary( ...
d on rasterio files. Try to load your data with ds.load()' 'first.') class RasterioArrayWrapper(BackendArray): """A wrapper around rasterio dataset objects""" def __init__(self, manager, lock, vrt_params=None): from rasterio.vrt import WarpedVRT self.manager = manager se...
WarpedVRT): vrt = filename filename = vrt.src_dataset.name vrt_params = dict(crs=vrt.crs.to_string(), resampling=vrt.resampling, src_nodata=vrt.src_nodata,
dst_nodata=vrt.dst_nodata, tolerance=vrt.tolerance, transform=vrt.transform, width=vrt.width, height=vrt.height, warp_extras=vrt.warp_extras) if lock is None: ...
#!/usr/bin/python #---------------------------------------------------------------------- # Copyright (c) 2013-2016 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without rest...
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS # IN THE WORK. #---------------------------------------------------------------------- import json import sys from ...
OCSliceConfiguration, VMOCVLANConfiguration # Usage register_controller.sh slice [vlan controller ....] [unregister] if len(sys.argv) < 2: print "Usage: register_controller.py slice [vlan controller ...] [unregister]" sys.exit() print sys.argv[1] print sys.argv[2] slice_id = sys.argv[1] vlan_controllers = j...
import sys sys.path = ['..'] + sys.path import zope from twisted.internet import reactor from thrift.transport import TSocket from thrift.transport import TTransport from thrift.transport import TTwisted from thrift.protocol import TBinaryProtocol from lib.genpy.snowflake import Snowflake from lib.genpy.snowflake.tt...
> <datacenter_id>' print 'e.g. python snowflakeserver.py 1111 1 1' def main(): if len(sys.argv) != 4: return print_us
age() port = int(sys.argv[1]) worker_id = int(sys.argv[2]) datacenter_id = int(sys.argv[3]) reactor.listenTCP(port, TTwisted.ThriftServerFactory( processor=Snowflake.Processor(SnowflakeServer(worker_id, datacenter_id)), iprot_factory=T...
''' Convert an image file to a data uri. Copyright 2012 GoodCrypto Last modifie
d: 2013-11-13 This file is open source, licensed under GPLv3 <http://www.gnu.org/licenses/>. ''' import os.path from django import template import reinhardt.data_image register = template.Library() @register.filter def data_img(filename, browser=None): ''' Encode an image file in base 64 as a data uri...
Example: <img alt="embedded image" src="{{ 'images/myimage.png'|data_img:browser }}"> ''' return reinhardt.data_image.data_image(filename, browser=browser)
# Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ResourceFinder is a helper class for finding resources given their name.""" import codecs import os from py_vulcanize import module from py_vulcaniz...
r absolute path to a file. Returns: A Resource or None. """ if os.path.isabs(some_path): return self.FindResourceGivenAbsolutePath(some_path, binary) else: return self.FindResourceGivenRelativePath(some_path, binary) def FindResourceGivenAbsolutePath(self, absolute_path, binary=Fal...
: if absolute_path.startswith(source_path): candidate_paths.append(source_path) if len(candidate_paths) == 0: return None # Sort by length. Longest match wins. candidate_paths.sort(lambda x, y: len(x) - len(y)) longest_candidate = candidate_paths[-1] return resource_module.Resou...
num_segments=num_segments) return voxel_features, voxel_xyz_indices, segment_ids, voxel_start_location def _pad_or_clip_voxels(voxel_features, voxel_indices, num_valid_voxels, segment_ids, voxels_pad_or_clip_size): """Pads or clips voxels.""" if voxels_pad_or_clip_size: num_val...
sparse_voxel_grid_unbatched( points=points_i, features=features_i, grid_cell_size=grid_cell_size, segment_func=segment_func)) num_valid_voxels_i = tf.shape(voxel_features_i)[0] (voxel_features_i, voxel_indices_i, num_valid_voxels_i, segment_ids_i) = _pad_or_c...
valid_voxels=num_valid_voxels_i, segment_ids=segment_ids_i, voxels_pad_or_clip_size=voxels_pad_or_clip_size) segment_ids_i = tf.pad( segment_ids_i, paddings=[[0, num_points - num_valid_points_i]]) return (voxel_features_i, voxel_indices_i, num_valid_voxels_i, segment_ids_i,...
#!/usr/bin/env python import argparse import os import logging import cdec.configobj import cdec.sa from cdec.sa._sa import monitor_cpu import sys MAX_PHRASE_LENGTH = 4 def precompute(f_sa, max_len, max_nt, max_size, min_gap, rank1, rank2, tight_phrases): lcp = cdec.sa.LCP(f_sa) stats = sorted(lcp.compute_stat...
() logger.info('Compiling bilexical dictionary took %f seconds', stop_time - start_time) # Write configuration config = cdec.configobj.ConfigObj(args.c
onfig, unrepr=True) config['f_sa_file'] = os.path.abspath(f_sa_bin) config['e_file'] = os.path.abspath(e_bin) config['a_file'] = os.path.abspath(a_bin) config['lex_file'] = os.path.abspath(lex_bin) config['precompute_file'] = os.path.abspath(precomp_bin) for name, value in zip(param_names, param...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
, #
59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Define base Blueprint.""" from flask import Blueprint blueprint = Blueprint('base', __name__, template_folder='templates', static_folder='static')
inpu
t = """ x | -x. y | -
y. """ output = """ x | -x. y | -y. """
""" Copyright 2014 Jason Heeris, jason.heeris@gmail.com This file is part of the dungeon excavator web interface ("webcavate"). Webcavate 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 L...
e("/error") def error(): ""
" Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room...
import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, json_output @click.command('create_library') @click.argument("name", type=str) @click.option( "--description", help="Optional data library description", type=str ) @click.option( "--synopsis", ...
synopsis=""): """Create a data library with the properties defined in the arguments. Output: Details of the created library. For example:: {'id': 'f740ab636b360a70', 'name': 'Library from bioblend', '
url': '/api/libraries/f740ab636b360a70'} """ return ctx.gi.libraries.create_library(name, description=description, synopsis=synopsis)
import galaxy.model from logging import getLogger log = getLogger( __name__ ) ROLES_UNSET = object() INVALID_STATES = [ galaxy.model.Dataset.states.ERROR, galaxy.model.Dataset.states.DISCARDED ] class DatasetMatcher( object ): """ Utility class to aid DataToolParameter and similar classes in reasoning about...
True, check_security=False ): """ Return False of this parameter can not be matche
d to a the supplied HDA, otherwise return a description of the match (either a HdaDirectMatch describing a direct match or a HdaImplicitMatch describing an implicit conversion.) """ if self.filter( hda ): return False formats = self.param.formats if hd...
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from jenkinsflow.flow import serial from .framework import api_select prefixed_jobs = """ serial flow: [ job: 'top_quick1' serial flow: [ job: 'top_x_quick2-1' ] ...
i_type, capsys): with api_select.api(__file__, api_type) as api: def job(name): api.job(name, exec_time=0.5, max_fails=0, expect_invocations=0, expect_order=None, params=None) api.flow_job() job('quick1') index = 0 for index in 1, 2, 3: job('x_qui...
_z_quick4') job('y_quick5') with serial(api, timeout=70, report_interval=3, job_name_prefix='top_', just_dump=True) as ctrl1: ctrl1.invoke('quick1') for index in 1, 2, 3: with ctrl1.serial(timeout=20, report_interval=3, job_name_prefix='x_') as ctrl2: ...
mport STUDIO_BASE_URL from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture class XBlockFixtureDesc(object): """ Description of an XBlock, used to configure a course fixture. """ def __init__(self, category, display_name, data=None, metadata=None, grad...
ct.
Returns the `xblock_desc` instance to allow chaining. """ self.children.extend(args) return self def serialize(self): """ Return a JSON representation of the XBlock, suitable for sending as POST data to /xblock XBlocks are always set to public visibili...
# This is the version of this source code. manual_verstr =
"1.5" auto_build_num = "212" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as dist...
on(verstr)
import mcpi.minecraft as minecraft import mcpi.block as block import random import time mc = minecraft.Minecraft.create() #mc.po
stToChat("Heat Vision!") pos = mc.player.getTilePos() #mc.postToChat(pos) #rot = mc.player.getRotation() #pitch = mc.player.getPitch() #direct = mc.player.getDirection() #mc.postToChat(rot) #mc.postToChat(pitch) #mc.postToChat(direct) # those dont work on Pi # activate any tnt around mc.postToChat("Oliver's bo...
range (-4, 4): for yi in range (-1, 3): thisblock = mc.getBlock(x + xi, y + yi, z + zi) #print thisblock if thisblock == 46: mc.setBlock(x + xi, y + yi, z+zi, 46, 1) print "setting on" #mc.setBlock(x + x...
''' Created on Oct 19, 2016 @author: jaime ''' from django.conf.urls import url from django.views.decorators.
csrf import csrf_exempt from products import views urlpatterns = [ url(r'^categories/$', csrf_exempt(views.ProductCategoryView.as_view())), url(r'^categories/(?P<uid>\w+)/$', csrf_exempt(views.ProductCategoryView.as_view())), url(r'^$', csrf_exempt(views.ProductView.as_view())), url(r'^(?P<uid>\w+)...
roductView.as_view())), ]
# -*- encoding: utf-8 -*- import argparse import os import sys import yaml from . import VERSION import actions import core import exception from utils import log def error(errtype, msg, code=42): sys.stderr.write("{t.red}[ERROR] {t.yellow}{er}: {msg}" "{t.normal}\n".format(er=errtype, msg=...
', metavar='ATTR:REGEX', action='append', help="Only download builds with ATTRibute matching python REGEX; can " "be specified multiple times") dl_parser.set_defaults(action=do_download) # move move_parser = subparsers.add_parser( 'move', help="move an update file (create a comm...
.add_argument( 'files', metavar='FILE', type=str, nargs='+', help='update file(s) to move') move_parser.add_argument( '-d', '--dir', type=str, metavar='DIR', help="move update file(s) to this directory instead of using " "update.group") move_parser.set_defaults(actio...
self.pMap[pseudo.unicode] = ttFont.getGlyphName(pseudo.nPseudo) data = data[8 + 6 * numPseudo:] currpos = (sstruct.calcsize(Silf_part1_format) + sstruct.calcsize(Silf_justify_format) * self.numJLevels + sstruct.calcsize(Silf_part2_format) + 2 * self.numCritF...
f.numPasses + 8 + 6 * numPseudo) if version >= 3.0: currpos += sstruct.calcsize(Silf_part1_format_v3) self.classes = Classes() self.classes.decompile(data, ttFont, version) for i in range(self.numPasses):
p = Pass() self.passes.append(p) p.decompile(data[self.oPasses[i]-currpos:self.oPasses[i+1]-currpos], ttFont, version) def compile(self, ttFont, version=2.0): self.numPasses = len(self.passes) self.numJLevels = len(self.jLevels) self....
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. import libvirt import re from libvirt import libvirtError from libvirttestapi.utils import utils required_params = {'guestname', 'checkpoint_name'} optional_params = {'flags': None} def checkpoint_get_xml(params): logg...
o("flag: %s" % flag) if flag == libvirt.VIR_DOMAIN_CHECKPOINT_XML_SIZE: logger.info("Bug 1207659: Don't support this flag.") return 0 try: conn = libvirt.open() dom = conn.lookupByName(guestname) cp = dom.checkpointLookupByName(checkpoint_name) cp_xml =
cp.getXMLDesc(flag) except libvirtError as err: logger.error("API error message: %s" % err.get_error_message()) return 1 checkpoint_xml_path = "/var/lib/libvirt/qemu/checkpoint/%s/%s.xml" % (guestname, checkpoint_name) cp_fd = open(checkpoint_xml_path, 'r') checkpoint_xml = cp_fd.read()...
def factorial(count): return count * fa
ctorial(
count - 1) answer = factorial(6)
import pytest from iotile.core.exceptions import ArgumentError from iotile.sg.model import DeviceModel def test_default_values(): """Make sure we can get properties with default values.""" model = DeviceModel() assert model.get('max_nodes') == 32
assert model.get(u'max_nodes') == 32 model.set('max_nodes', 16) assert model.get('max_nodes') == 16 assert model.get(u'max_nodes') == 16 model.set(u'max_nodes', 17) assert model.get('max_nodes') == 17 assert model.get(u'max_nodes') == 17 with pytest.raises(ArgumentError): model.ge...
meter') with pytest.raises(ArgumentError): model.set('unknown_parameter', 15)
'
'' custom script for platformio ''' from os.path import join from SCons.Script import DefaultEnvironment env
= DefaultEnvironment() #print "post_extra_script running..." #print env.Dump() # compiler and linker flags dont work very well in build_flags of platformio.ini - need to set them here env.Append( LINKFLAGS = [ "--data-loc", 0x30 ], STCGALCMD="/stcgal.py" )
from attributes import * from constants import * # ------------------------------------------------------------------------------ # class UnitManager (Attributes) : """ UnitManager class -- manages a pool """ # -------------------------------------------------------------------------- # ...
the pilot(s). `drain` determines what happens to the units which are managed by the removed pilot(s). If `True`, the pilot removal is delayed until all units reach a final state. If `False` (the default), then `RUNNING` units will be canceled, and `PENDING` units will be re-assinged ...
""" raise Exception ("%s.remove_pilot() is not implemented" % self.__class__.__name__) # -------------------------------------------------------------------------- # def submit_unit (self, description) : """ Instantiate and return (Compute or Data)-Unit object(s) ...
import pytz priorities = ('US/Pacific', 'US/Mountain', 'US/Central', 'US/Eastern',
'Brazil/East', 'UTC') all_tz = pytz.all_t
imezones_set.copy() for priority in priorities: all_tz.remove(priority) all_tz = sorted(list(all_tz)) all_tz[:0] = priorities # prepends list to list # tuples for selection widget all_tz = tuple((tz, tz) for tz in all_tz)
# pylint: disable=missing-docstring from datetime import datetime, timedelta import factory import pytz from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyText from oauth2_provider.models import AccessToken, Application, RefreshToken from openedx.core.djangoapps.oauth_dispatch.models impor...
ngoModelFactory): class Meta: model = AccessToken django_get_or_create = ('user', 'application') token = FuzzyText(length=32) expires = datetime.now(pytz.UTC) + timedelta(days=1) class RefreshTokenFactory(DjangoModelFactory): class Meta: model = RefreshToken django_get...
= FuzzyText(length=32)
{ "name": "Delivery S
equence", "vesion": "12.0.1.0.0", "author": "IT-Projects LLC, Ivan Yelizariev", "license": "LGPL-3", "category": "Custom", "website": "https://yelizariev.github.io", "depends": ["delivery"], "data": ["views.xml"], "
installable": False, }
ction count["section"] += 1 count["subsection"]=0 else : t=sectionstar t=t.replace("_SecNumb_",str(count["section"]) ) t=t.replace("_SecName_",L[1]) return(t) def convertsubsection (m) : L=cb.split(m) if L[0].find("*") == -1 : ...
level] = '</' + v + '>' i += l special = True if not special: if w[i] == '{': ww += '{' level += 1 close[level] = '}' elif w[i] == '}' and level > 0: ww += close[level] level -= 1 ...
ertref(m) : global ref p=re.compile("\\\\ref\s*\\{.*?}|\\\\eqref\s*\\{.*?}") T=p.split(m) M=p.findall(m) w = T[0] for i in range(len(M)) : t=M[i] lab=cb.split(t)[1] lab=lab.replace(":","") if t.find("\\eqref") != -1 : w=w+"<a href=\"#"+lab+"\">("...
# -*- coding: utf-8 -*- import re from ..base.downloader import BaseDownloader class VeehdCom(BaseDownloader): __name__ = "VeehdCom" __type__ = "downloader" __version__ = "0.29" __status__ = "testing" __pattern__ = r"http://veehd\.com/video/\d+_\S+" __config__ = [ ("enabled", "bool",...
self.error(self._("Video title not found")) name = m.group(1) #: Replace unwanted characters in filename if self.config.get("filen
ame_spaces"): pattern = r"[^\w ]+" else: pattern = r"[^\w.]+" return re.sub(pattern, self.config.get("replacement_char"), name) + ".avi" def get_file_url(self): """ Returns the absolute downloadable filepath. """ if not self.data: ...
import csv import datetime import logging import os from celery.task import task from django.conf import settings from django.contrib.auth import get_user_model from django.utils.timezone import now from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \ REMINDER_LAST_REPORT, REMINDER_CLOSE fr...
_date__gte=one_day_ago, ).values_list('phone_number', flat=True) @task def message_reminder_task(message_number, reminder_number, audience, election): """ Make a batch to send out a bunch of reminder messages to a given audience, iffi they haven't sent us the expected report yet. """ logge...
tered" % audience) # Batches need to be owned by somebody - pick a non-random superuser user = get_user_model().objects.filter(is_active=True, is_superuser=True)[0] batch = Batch.objects.create( name="Reminder %d for message_number %d" % (reminder_number, message_number), created_by=user, ...
# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') from common import public import time import re class qyxx_ck(): """采矿许可证""" need_check_ziduan = ['valid_from',
'validto' ] def check_valid_from(self, indexstr, ustr): """有效期限自""" ret = None validdate = indexstr['validdate'].strip() if validdate and len(validdate): err, time = public.get_date(validdate, 0) if err: ret...
ret = u'不等我的是-%s-' % frm return ret def check_validto(self, indexstr, ustr): """有效期限至""" ret = None validdate = indexstr['validdate'].strip() if validdate and len(validdate): err, time = public.get_date(validdate, 1) if err: ret = ...
# -*- coding: utf-8 -*- # Copyright (C) 2011 Romain Bignon, Laurent Bachelier # # This file is part of assnet. # # assnet is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License...
th (see quote_url) """ return ''.join([UNSAFE_CHARS.get(c, c) for c in path]) def quote_url(url): """ Quote the path part of an URL object and return the full URL a
s a string. Special characters in the URL are not considered as the query string or any other parameters, they should be in their dedicated variables of the URL class. """ purl = urlsplit(url.url) # do not escape the scheme and netloc if purl.scheme and purl.netloc: path = urlunsplit...
import radon.complexity import radon.visitors from coalib.bears.LocalBear import LocalBear from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY from coalib.results.SourceRange import SourceRange from coalib.settings.Setting import typed_list class RadonBear(LocalBear): ...
_SEVERITY.INFO: radon_ranks_info, RESULT_SEVERITY.NORMAL: radon_ranks_normal, RESULT_SEVERITY.MAJOR: radon_ranks_major } for visitor in radon.complexity.cc_visit("".join(file)): rank = radon.complexity.cc_
rank(visitor.complexity) severity = None for result_severity, rank_list in severity_map.items(): if rank in rank_list: severity = result_severity if severity is None: continue visitor_range = SourceRange.from_values( ...
""
"Place all plugins in this directory."""
import os import datetime from utils.util import run_command __author__ = 'maa' class MsBuilder: def __init__(self, msbuild): if msbuild == None: self.msbuild = r"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" else: self.msbuild = msbuild def build_with...
if not os.path.isfile(self.msbuild): raise Exception('MsBuild.exe not found. path = ' + self.msbuild)
start = datetime.datetime.now() print('STARTED BUILD - ' + start.strftime('%Y-%m-%d %H:%M:%S')) params = [self.msbuild, csprojPath] + list(args) return run_command(params) def get_files_from_project_bin_folder(self, csproj, configuration, do_return_full_paths=False): name =...
# -*- coding: utf-8 -*- # Mathmaker creates automatically maths exercises sheets # with their answers # Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com> # This file is part of Mathmaker. # Mathmaker is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License...
(0.8, 3)\n'\ '\n'\ 'draw\n'\ ' (A.B.C.D)\n'\ ' $\\rotatebox{11}{\sffamily 4~cm}$ A 11 - 12.7 deg 4.1\n'\ ' $\\rotatebox{86}{\sffamily 3~cm}$ B 86 - 8.9 deg 4.9\n'\ ' $\\rotatebox{23}{\sffamily
2~cm}$ C 203 - 12.2 deg 4.2\n'\ ' $\\rotatebox{83}{\sffamily 6.5~cm}$ D 263 - 12.9 deg 4.1\n'\ ' $\\rotatebox{47.3}{\sffamily 64\\textdegree}$ A 47.3 deg 2.7\n'\ ' $\\rotatebox{-41.3}{\sffamily 128\\textdegree}$ B 138.7 deg 2.7\n'\ ' $\\rotatebox{54.3}{\sffamily 32\\textdegree}$ C 2...
from idl.Annotatable import Annotatable from idl.IDLSyntaxError import IDLSyntaxError from idl.Type import Type class EnumField(Annotatable): ''' Object that represents a single enumeration field. ''' def __init__(self, enum, name, value): Annotatable.__init__(self) self....
# Dupl
icate value check for i in self._fields: if i.value == value: raise IDLSyntaxError(self.module, field.line, 'Duplicate explicit field value %d given for field %r in enume...
# -*- coding: utf-8 -*- # # Copyright (C) 2006, TUBITAK/UEKAE # # 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. # # Plea...
l(self, sig): if sig not in self.signals.keys(): self.signals[sig] = Signal(sig) signal.signal(sig, self.signal_handler) d
ef enable_signal(self, sig): if sig in self.signals.keys(): if self.signals[sig].oldhandler: oldhandler = self.signals[sig].oldhandler else: oldhandler = signal.SIG_DFL pending = self.signals[sig].pending del self.signals[sig] ...
----- If the input arrays are of dimension deficient by one, for example if the coordinates array is two dimensional, the time is a single scalar or cell_lengths and cell_angles are a 1d array of length three, that is okay. You'll simply be saving a single frame. """ self...
nvalid argument') def tell(self): """Current file position Returns ------- offset : int The current frame in the file. """ return int(self._frame_index)
def close(self): """Close
nd std of the images on the training set PARAMETER_MAX = 10 # What is the max 'level' a transform could be predicted def get_mean_and_std(): if FLAGS.task_name == "cifar10": means = [0.49139968, 0.48215841, 0.44653091] stds = [0.24703223, 0.24348513, 0.26158784] elif FLAGS.task_name == "svhn": means ...
_ = create_cutout_mask(img_height, img_width, num_channels, siz
e) return img * mask def float_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval . Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Return...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Righ
ts Reserved. # # This program is free software: you can redistribute it and/or modify #
it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warra...
#!/usr/bin/python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Lic...
r the License. import zookeeper, zktestbase, unittest, threading class DeletionTest(zktestbase.TestBase): """Test whether we can delete znodes""" def test_sync_delete(self): ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"} self.assertEqual(self.connected, True) r...
tetest") ret = zookeeper.delete(self.handle,"/zk-python-deletetest") self.assertEqual(ret, zookeeper.OK) children = zookeeper.get_children(self.handle, "/") self.assertEqual(False, "zk-python-deletetest" in children) # test exception self.assertRaises(zookeeper.NoNodeExc...
from selenium import webd
river import logging logger = logging.getLogger() driver =
webdriver.Firefox()
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0201 from recipe_engine import recipe_api from recipe_engine import config_types class CheckoutApi(recipe_api.RecipeApi): @propert...
g. Therefore, # always specify patch=True for non-trybot runs. patch=not (self.m.vars.is_trybot and parent_rev), patch_refs=patch_refs, ) if checkout_chromium or checkout_flutter: gclient_env = {'DEPOT_TOOLS_UPDATE': '0'} if extra_gclient_env: gclient_env.upd...
ut_root, env=gclient_env): self.m.gclient.runhooks() return update_step.presentation.properties['got_revision']
""" Tablib - DataFrame Support. """ import sys if sys.version_info[0] > 2: from io import BytesIO else: from cStringIO import StringIO as BytesIO try: from pandas import DataFrame except ImportError: DataFrame = None import tablib from tablib
.compat import unicode title = 'df' extensions = ('df', ) def detect(stream): """Returns True if given stream is a DataFrame.""" if DataFrame is None: return False
try: DataFrame(stream) return True except ValueError: return False def export_set(dset, index=None): """Returns DataFrame representation of DataBook.""" if DataFrame is None: raise NotImplementedError( 'DataFrame Format requires `pandas` to be installed.' ...
import os from lxml import etree class device: def __init__(self,ipadress,name): self.ipadress=str(ipadress) self.name=str(name) self.status="off" def turn_on(self): self.status="on" def turn_off(self): self.status="off" def getstatus(devices): ips=
[] for instance in devices: instance.turn_off() test=os.popen("nmap -sP --unprivileged 192.168.2.0/24")
for i in test.readlines(): if i.split(' ')[0]=='Nmap' and i.split(' ')[1]=='scan' : ips.append(i.split('(')[1][:-2]) for i in xrange(0,len(ips)): for j in xrange(0,len(devices)): if ips[i]== devices[j].ipadress: devices[j].turn_on() return devices def ...
#!/usr/bin/env python import os from setuptools import setup def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup(name='django-darkknight', version='0.9.0', license="BSD", description="He's a silent guardian, a watchful protector", ...
extras_require = { 'gpg': ['gnupg>=2.0.2,<3', 'django-apptemplates'], }, classifiers=[ "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "License :: OSI Ap...
nguage :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", "Topic :: Security :: Cryptography", ], )
from .app import App from .model import User, Group, ResetNonce class ViewPermission: pass class EditPermission: pass @App.permission_rule(model=object, permission=object) def admin_has_global_permission(identity, model, permission): user = User.get(email=identity.userid) return Group.get(name="Ad...
t None and Group.get(name="Admin") in user.groups: return True else: return model.email == identity.userid @App.permission_rule(model=ResetNonce, permission=EditPermission) def user_has_permission_to_reset_nonce(identity, model, permission): user = User.get(email=identity.userid) if user i...
return user.id == int(model.id)
def _filename(obj): try: return obj.__fil
ename__() except: pass return
str(obj)
honcom.CLSCTX_SERVER): IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx) if createClass is None: createClass = CDispatch lazydata = None try: if typeinfo is None: typeinfo = IDispatch.GetTypeInfo() try: #try for a typecomp typecomp = typeinfo.GetTypeComp() laz...
(typeinfo, attr, None, 0) else: olerepr = build.LazyDispatchItem(attr, None) except pythoncom.ole_error: pass if olerepr is None: olerepr = build.DispatchItem() return olerepr def DumbDispatch(IDispatch, userName = None, createClass = None,UnicodeToString=NeedUnicodeConversions, clsctx=pyth
oncom.CLSCTX_SERVER): "Dispatch with no type info" IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx) if createClass is None: createClass = CDispatch return createClass(IDispatch, build.DispatchItem(), userName,UnicodeToString) class CDispatch: def __init__(self, IDispatch, ole...
e element list (GH 15447) res = sparse.reindex(["A"], level=0) exp = orig.reindex(["A"], level=0).to_sparse() tm.assert_sp_series_equal(res, exp) with pytest.raises(TypeError): # Incomplete keys are not accepted for reindexing: sparse.reindex(["A", "C"]) ...
sparse = orig.to_sparse() assert sparse.iloc[1, 1] == 3 assert np.isnan(sparse.iloc[2, 0]) tm.assert_sp_series_equal(sparse.iloc[0], orig.loc[0].to_sparse(kind="integer")) tm.assert_sp_series_equal(sparse.iloc[1], orig.loc[1].to_sparse(kind="integer")) tm.assert_sp_serie...
tm.assert_sp_series_equal( sparse.iloc[2, :], orig.iloc[2, :].to_sparse(kind="integer") ) tm.assert_sp_series_equal(sparse.iloc[:, 1], orig.iloc[:, 1].to_sparse()) tm.assert_sp_series_equal(sparse.iloc[:, 1], orig.iloc[:, 1].to_sparse()) result = sparse.iloc[[1, 2]]...
from quotes.m
odels import Quote fro
m django.contrib import admin class QuoteAdmin(admin.ModelAdmin): list_display = ('message', 'name', 'program', 'class_of', 'submission_time') admin.site.register(Quote, QuoteAdmin)
#!/usr/bin/env python # vim: set expandtab shiftwidth=4: # http://www.voip-info.org/wiki/view/asterisk+manager+events import sys,time import simplejson as json from stompy.simple import Client import ConfigParser config = ConfigParser.ConfigParser() devel_config = ConfigParser.ConfigParser() config.read('/opt/ucall/...
('STOMP', 'username') stomp_password = config.get('STOMP', 'password') stomp_queue = "/queue/messages/" + devel_config.get
('GENERAL', 'agent') print '='*80 print 'Stomp host:', stomp_host print 'Stomp username:', stomp_username print 'Stomp password:', stomp_password print 'Stomp queue:', stomp_queue print '='*80 stomp = Client(stomp_host) stomp.connect(stomp_username, stomp_password) stomp.subscribe("jms.queue.msg.ctrl") while True...
def _
magic_get_file_type(f, _): file_type = magic.from_buffer(f.read(1024), mime=True) f.seek(0) return file_type.decode('utf-8') def _guess
_file_type(_, filename): return mimetypes.guess_type(filename)[0] try: import magic except ImportError: import mimetypes get_file_type = _guess_file_type else: get_file_type = _magic_get_file_type
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apach...
tion resp, body = cls.client.create_floating_ip() cls.floating_ip_id = body['id'] cls.floating_ip = body['ip'] # Ge
nerating a nonexistent floatingIP id cls.floating_ip_ids = [] resp, body = cls.client.list_floating_ips() for i in range(len(body)): cls.floating_ip_ids.append(body[i]['id']) while True: cls.non_exist_id = data_utils.rand_int_id(start=999) if cls.confi...
# coding:utf-8 ''' Created on 2017/11/7. @author: chk01 ''' import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict np.random....
at32, name='y-input') cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y) with tf.Session() as sess: cost = sess.run(cost, feed_dict={z: logits, y: labels}) return cost # GRADED FUNCTION: one_hot_matrix def one_hot_matrix(labels, C): """ Creates a matrix where the i-th r...
and the jth column corresponds to the jth training example. So if example j had a label i. Then entry (i,j) will be 1. Arguments: labels -- vector containing the labels C -- number of classes, the depth of the one hot dimension Returns: one_hot -- one hot...
""" raven.core.processors ~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import re from raven.utils import varmap from raven.utils import six class Processor(object): def _...
ata, **kwargs) if resp: data = resp if 'exception' in data: if 'values' in data['exception']: for value in data['exception'].get('values', []): if 'stacktrace' in value: self.filter_stacktrace(value['stacktrace']) ...
n data def filter_stacktrace(self, data): pass def filter_http(self, data): pass def filter_extra(self, data): return data class RemovePostDataProcessor(Processor): """ Removes HTTP post data. """ def filter_http(self, data, **kwargs): data.pop('data', No...
# -*- coding: utf-8 -*- # # This file is part of HEPData. # Copyright (C) 2016 CERN. # # HEPData 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...
ion_entry_points=['invenio_base.api_apps'], blueprint_en
try_points=['invenio_base.api_blueprints'], instance_path=instance_path, ) create_app = create_app_factory( 'hepdata', config_loader=conf_loader, extension_entry_points=['invenio_base.apps'], blueprint_entry_points=['invenio_base.blueprints'], wsgi_factory=create_wsgi_factory({'/api': create_a...
from datetime import datetime from django.db import models from uuidfield.fields import UUIDField from access import acl import amo.models from translations.fields import save_signal from mkt.constants import comm as const class CommunicationPermissionModel(amo.models.ModelBase): # Read permissions imply writ...
COUNT) def reset_uuid(self): # Generate a new UUID. self.uuid = UUIDField()._create_uuid(
).hex models.signals.pre_save.connect(save_signal, sender=CommunicationNote, dispatch_uid='comm_thread_notes_translations')
""" This class represents a Queue Node to store values and also links others Nodes with values.""" class Node: """ It starts with a value at all times. A note can not be created without a value associated. """
def __init__(self, value): self.value = val
ue self.next = None """ This class represents a Queue to store values. The Queue starts with a node called head. Every single element is going to be added after the last node entered.""" class Queue: """ The Queue is created with it's size zero and the head element head is None (undefined)...
NAME = 'django-adminactions' VERSION = __version__ = (0, 4, 0, 'final', 0) __author__ = 'sax' import subprocess import datetime import os def get_version(version=None): """Derives a PEP386-compliant version number from VERSION.""" if version is None: version = VERSION assert len(version) == 5 ...
', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4]) return main + sub def get_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so i...
############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SO...
############# """`APIdoc` skin. $Id$ """ __docformat__ = "reStructuredText" from zope.publisher.interfaces.browser import IB
rowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer class apidoc(IBrowserRequest): """The `apidoc` layer.""" class APIDOC(apidoc, IDefaultBrowserLayer): """The `APIDOC` skin.""" # BBB 2006/02/18, to be removed after 12 months import zope.app.skins zope.app.skins.set('APIDOC', API...
# Copyright (c) 2013, Kevin Greenan (kmgreen2@gmail.com) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of c...
LDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL
, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN...
""" tflite backend (https://github.com/tensorflow/tensorflow/lite) """ # pylint: disable=unused-argument,missing-docstring,useless-super-delegation from threading import Lock try: # try dedicated tflite package first import tflite_runtime import tflite_runtime.interpreter as tflite _version = tflite_...
def image_format(self): # tflite is always NHWC return "NHWC" def load(self, model_path, inputs=None, outputs=None): self.sess = tflite.Interpreter(model_path=model_path) self.sess.allocate_tensors() # keep input/output name to index mapping self.input2index = ...
2index = {i["name"]: i["index"] for i in self.sess.get_output_details()} # keep input/output names self.inputs = list(self.input2index.keys()) self.outputs = list(self.output2index.keys()) return self def predict(self, feed): self.lock.acquire() # set inputs ...
assert sympify('2.6e+2/17', rational=True) == Rational(260, 17) assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000) assert sympify('2.1+3/4', rational=True) == \ Rational(21, 10) + Rational(3, 4) assert sympify('2.234456', rational=True) == Rational(279307, 125000) assert sympify(...
math.mpf(1.0)) assert value == Float(1.0) and type(value) is Float mpmath.mp.dps = 12 assert sympify( mpmath.pi).epsilon_eq(Float("
3.14159265359"), Float("1e-12")) is True assert sympify( mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) is False mpmath.mp.dps = 6 assert sympify( mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) is True assert sympify( mpmath.pi).epsilon_eq(Float("3.14159")...
from .ScatterplotStructure import ScatterplotStructure from .BasicHTMLFromScatterplotStructure import BasicHTMLFromScatterplotSt
ructure from scattertext.viz.PairPlotFromScattertextStructure import PairPlotFromScatterplotStructure from .VizDataAdapter imp
ort VizDataAdapter from .HTMLSemioticSquareViz import HTMLSemioticSquareViz
''' Creat
ed by auto_sdk on 2013.11.26 ''' from top.api.base import
RestApi class PictureIsreferencedGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.picture_id = None def getapiname(self): return 'taobao.picture.isreferenced.get'
""" Meteo
rology visualisation examples =======
=========================== """
def test_assert(): assert 'soup' == 'soup' def test_pass(): pass def test_fail(): ass
ert False test_fail.w
ill_fail = True
#! /usr/bin/env python # -*- coding: UTF-8 -*- # --------------------------------------------------------------------------- # ___ __ ___ ___ ____ ____ __ # | \ | \ | | / | | | \ Automatic # |__/ |__/ | | |
|__ |__ | | Conference # | |\_ | | | | | | | Proceedings # | | \ |___| \___ |___ |___ |__/ Generator # ========================================================== # # http://www.lpl-aix.fr/~bigi/ # # -------------------------------------...
igi # # Use of this software is governed by the GPL, v3 # This banner notice must not be removed # --------------------------------------------------------------------------- # # Proceed is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publish...
""" POZ Development Application. """ import numpy as np # import cv2 import pozutil as pu import test_util as tpu def perspective_test(_y, _z, _ele, _azi): print "--------------------------------------" print "Perspective Transform tests" print cam = pu.CameraHelper() # som...
et for testing cam_elev = vis_map[key].el + known_cam_el
print "-----------" # print "Known Camera Elev =", cam_elev xyz = [cam_x, known_cam_y, cam_z] angs = [cam_azim, cam_elev] print "Landmark {:s}. Camera Azim = {:8.2f}".format(key, cam_azim) lm1 = tpu.mark1[key] f, x, z, a = tpu.landmark_test(lm1, tpu.mark2[...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='pysensu-yelp',
version='0.4.4', provides=['pysensu_yelp'], description='Emits Yelp-flavored Sensu events to
a Sensu Client', url='https://github.com/Yelp/pysensu-yelp', author='Yelp Operations Team', author_email='operations@yelp.com', packages=find_packages(exclude=['tests']), install_requires=['six'], license='Copyright Yelp 2014, all rights reserved', )
# Peerz - P2P python library using ZeroMQ sockets and gevent # Copyright (C) 2014-2015 Steve Henderson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
tion) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR
POSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import time from transitions import Machine class MessageState(object): states = ['initialised', 'waiting res...
import hashlib puzzle_input = 'iwrupvqb' current = 0 done = False while not done: combined_input = puzzle_input + str(current) solution = hashlib.md5(combined_input.encode()) solution = str(solution.hexdigest()) print(solution) if solution.startswith('00000
0'):
done = True print(current) current += 1
LinearSVC) @pytest.mark.parametrize('ensemble', [True, False]) def test_calibration_cv_splitter(data, ensemble): # Check when `cv` is a CV splitter X, y = data splits = 5 kfold = KFold(n_splits=splits) calib_clf = CalibratedClassifierCV(cv=kfold, ensemble=ensemble) assert isinstance(calib_clf...
, y = make_blobs(n_samples=500, n_features=100, random_state=seed, centers=10,
cluster_std=15.0) # Use an unbalanced dataset by collapsing 8 clusters into one class # to make the naive calibration based on a softmax more unlikely # to work. y[y > 2] = 2 n_classes = np.unique(y).shape[0] X_train, y_train = X[::2], y[::2] X_test, y_test = X[1::2], y[1::2] clf.fit(X...
portError: from md5 import md5 try: import json except ImportError: import simplejson as json from mwlib import filequeue, log, podclient, utils, wsgi, _version # ============================================================================== log = log.Log('mwlib.serve') # ===============================...
post_data.get('writer', self.default_writer) except KeyError, exc: return self.error_response('POST argument required: %s' % exc) writer_options = post_data.get('writer_options', '') template_blacklist = post_data.get('template_blacklist', '') template_exclusion_category = po...
script_extension = post_data.get('script_extension', '') if not collection_id: collection_id = self.new_collection(post_data) log.info('render %s %s' % (collection_id, writer)) response = { 'collection_id': collection_id, 'writ...
#!/usr/bin/env python """ Simple-stupid time tracker script ================================= Timetrack opyright (C) 2010, Branko Vukelic <studio@brankovukelic.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Soft...
: print "'%s' is not a valid pid, please use a 3 letter sequence" % pid print "Project ID is %s" % pid desc = raw_input("Job: ") desc = clean_strin
g(desc) if pid and desc: timestamp, starttime = generate_timestamp() print "Timer started at %s" % timestamp raw_input("Press Enter to stop the timer or Ctrl+C to abort") endtimestamp, endtime = generate_timestamp() print "Timer stopped at %s" ...
from typing import Dict, Set from django.db import transaction from django.db import models from django.utils import timezone from data_refinery_common.models.models import Sample, Experiment, OriginalFile class SurveyJob(models.Model): """Records information about a Surveyor Job.""" class Meta: db...
models.CharField(max_length=256) success = models.NullBooleanField(n
ull=True) no_retry = models.BooleanField(default=False) nomad_job_id = models.CharField(max_length=256, null=True) ram_amount = models.IntegerField(default=256) # The start time of the job start_time = models.DateTimeField(null=True) # The end time of the job end_time = models.DateTimeFie...
import cp
p11_decltype a = cpp11_decltype.A() a.i = 5 if a.i != 5:
raise RuntimeError, "Assignment to a.i failed." a.j = 10 if a.j != 10: raise RuntimeError, "Assignment to a.j failed." b = a.foo(5) if b != 10: raise RuntimeError, "foo(5) should return 10." b = a.foo(6) if b != 0: raise RuntimeError, "foo(6) should return 0."
import numpy as np import cudarray as ca from .base import PickleMixin _FLT_MIN = np.finfo(ca.float_).tiny class Loss(PickleMixin): # abll: I suspect that this interface is not ideal. It would be more # elegant if Loss only provided loss() and grad(). However, where should # we place the logic from fpro...
def __init__(self): self.name = 'mse' se
lf.n_targets = None def _setup(self, x_shape): self.n_targets = x_shape[1] def loss(self, y, y_pred): return ca.mean((y-y_pred)**2, axis=1) def grad(self, y, y_pred): return 2.0 / self.n_targets * (y_pred - y)
from rest_framew
ork import serializers class BaseModelSerializer(serializers.ModelSerializer): id = serializers.SerializerMethodField() def get_id(self, instance): return str(in
stance.id)
from website.addons.base.serializer import CitationsAddonSerializer class MendeleySerializer(CitationsAddonSerializer): addon_short_name = 'mendeley'
def for_config(cls, config): cachedir = cls.cache_dir_from_config(config) if config.getoption("cacheclear") and cachedir.exists(): rmtree(cachedir, force=True) cachedir.mkdir() return cls(cachedir, config) @staticmethod def cache_dir_from_config(config): ...
FPlugin(object): """ Plugin which implements the --nf (run new-first) option """ def __init__(self, config): self.config = config self.active = config.option.newfirst self.cached_nodeids = config.cache.get("cache/nodeids", []) def pytest_collection_modifyitems(self, session, config...
if item.nodeid not in self.cached_nodeids: new_items[item.nodeid] = item else: other_items[item.nodeid] = item items[:] = self._get_increasing_order( six.itervalues(new_items) ) + self._get_increasing_order(six.itervalues(...
import os, sys import myfun import numpy as np import matplotlib as mpl mpl.use('ps') import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import interpolate import lagrangian_stats import scipy.fftpack ## READ archive (too many points... somehow) # args: name, dayi, dayf, days #label ...
**-( -3+5/3.), '-5/3',fontsize=18) plt.text(6*10**-2, 5*10**-( -3+3.), '-3',fontsize=18) plt.text(6*10**-2, 5*10**-(
-3+1.), '-1',fontsize=18) plt.text(10**-3, 10**2,str(time*360./3600)+'hr',fontsize=18) plt.xlabel(r'k $[m^{-1}]$',fontsize=20) plt.ylabel(r'PSD',fontsize=20) plt.yticks(fontsize=18) plt.xticks(fontsize=18) plt.xlim([1/2000.,1/10.]) plt.savefig('./plot/'+label+'/Divergence_'+str(z)+'_CG_'+label+'_'+tlab...
# -*- coding: utf-8 -*- __versi
on__ = '0.7.0'
not match.group(0).endswith('.history') and not match.group(0).endswith('.partial')): return True return False def decode_segment_name(path): """ Retrieve the timeline, log ID and segment ID from the name of a xlog segment It can handle either a full file path or ...
int """ lsn_list = lsn_string.split('/') if len(lsn_list) != 2: raise ValueError('Invalid LSN: %s', lsn_string) return (int(lsn_list[0], 16) << 32) + int(lsn_list[1], 16) def diff_lsn(lsn_string1, lsn_string2): """ Calculate the difference in bytes
between two string XLOG location, formatted as %X/%X Tis function is a Python implementation of the ``pg_xlog_location_diff(str, str)`` PostgreSQL function. :param str lsn_string1: the string XLOG location, i.e. '2/82000168' :param str lsn_string2: the string XLOG location, i.e. '2/82000168' ...
e
rsion self.code = code self.reason = reason def __str_
_(self): return "%s %s %s" % (self.version, self.code, self.reason) class HttpMessageWriter(object): """Writes an HTTP message to a socket. """ def __init__(self, sock, msg, write_timeout): """Initializes this class and writes an HTTP message to a socket. @type sock: socket @param sock: Socket...
# GemRB - Infinity Engine Emulator # Copyright (C) 2003 The GemRB Project # # 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 versi...
) SchoolList = GemRB.LoadTable("magesch") #there is only a specialist mage window for bg1 KitWindow = GemRB.LoadWindow(12) for i in range(8): Button = KitWindow.GetControl(i+2) Button.SetState(IE_GUI_BUTTON_DISABLED) Button.SetFlags(IE_GUI_BUTTON_RADIOBUTTON, OP_OR) if not KitTable: RowCount = 1 else:...
+2) if not KitTable: if ClassID == 1: Kit=GemRB.GetVar("MAGESCHOOL") KitName = SchoolList.GetValue(i, 0) else: Kit = 0 KitName = CommonTables.Classes.GetValue(GemRB.GetVar("Class")-1, 0) else: Kit = KitTable.GetValue(i,0) if ClassID == 1: if Kit: Kit = Kit - 21 KitName = Sc...
""" Class to handle date-parsing and formatting """ # Workaround for http://bugs.python.org/issue8098 import _strptime # pylint: disable=unused-import from
datetime import datetime import time class Date
Utils(object): """ Class to handle date-parsing and formatting """ date_format = '%Y-%m-%dT%H:%M:%SZ' json_date_format = '%Y-%m-%dT%H:%M:%S.%fZ' kodi_date_format = '%Y-%m-%d %H:%M' def get_str_date(self, date): """ Formats datetime to str of format %Y-%m-%dT%H:%M:%SZ Argume...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Adriano Monteiro Marques # # Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com> # # This program is free
software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it w
ill be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http...
rayonnement[i]=RArray return rayonnement def convertGeoToAlt(dicoGeo): def mean(values): return np.nanmean(values) Altitude={} cstGravit=9.80665 footprint = np.array([[0,1,0], [1,0,1], [0,1,0]]) for i in dicoGeo...
(grid)-(float(grid)/2)) dicoLatLong={} dicoLatLong[0]=lat dicoLatLong[1]=lon return dicoLatLong def writeTiffFromDicoArray(DicoArray,outputImg,shape,geoparam,proj=None,format=gdal.GDT_Float32): gdalFormat = 'GTiff' driver = gdal.GetDriverByName(gdalFormat) dst_ds = driver.Cr...
RasterBand(j) band.SetNoDataValue(0) j+=1 originX = geoparam[0] originY = geoparam[1] pixelWidth = geoparam[2] pixelHeight = geoparam[3] dst_ds.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight)) def WriteTxtFileForEachPixel(outputFolder,et0_0,et0_1,et0_...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
IS" BASIS, WITHOUT # WARR
ANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from troveclient import client as tc from troveclient.openstack.common.apiclient import exceptions from heat.common import exception from heat.commo...
# import python modules import os import time import logging import multiprocessing # import django modules # import third party modules # import project specific model classes from config.models import Origin # import app specific utility classes # import app specific utility functions from .utils import packet_c...
plant_
flag=False ) discovery_process = multiprocessing.Process(target=read_pcap, args=(filepath, packets ...
) return status def addOneElement(sharedList): status = getOneStatusTS() ps = ParserStatus(status) tweet = Tweet(ps.getTweet()) sharedList.addElement(tweet) def addManyElements(sharedList, randomElements): status = getOneStatusTS() localList = [] for i in range(0, randomElements): ...
d(Streaming(randomStreaming(1))) bs.communicator.service.postStreamings(streamingList) searchList = ObjectList() searchList.append(Search(randomSearch(1))
) bs.communicator.service.postSearches(searchList) bs.start() # Create barrier for client cBarrier = Barrier(2) # Create client thread.start_new_thread(oneThread, (cBarrier, fakeClient, bs.getHostName(), 13001,)) cBarrier.wait() time.sleep(5) # Sto...
import sys from django.core.management.base import BaseCommand from ietf.community.constants import SIGNIFICANT_STATES from ietf.community.models import DocumentChangeDates from ietf.doc.models import Document class Command(BaseCommand): help = (u"Update drafts in community lists by reviewing their rules") ...
date = new_version and new_version.time.date() changes.normal_change_date = normal_change and normal_change.time.date() changes.significant_change_date = significant_change and sig
nificant_change.time.date() changes.save() sys.stdout.write('Document %s/%s\r' % (index, total)) sys.stdout.flush() index += 1 print
# -*- coding: ISO-8859-15 -*- # ============================================================================= # Copyright (c) 2004, 2006 Sean C. Gillies # Copyright (c) 2009 STFC <http://www.stfc.ac.uk> # # Authors : # Domi
nic Lowe <dominic.lowe@stfc.ac.uk> # # Contact email: dominic.lowe@stfc.ac.uk # ===================
========================================================== """ Web Feature Server (WFS) methods and metadata. Factory function. """ from feature import wfs100, wfs200 def WebFeatureService(url, version='1.0.0', xml=None): ''' wfs factory function, returns a version specific WebFeatureService object ''' if ve...
#!/usr/bin/env python # -*- coding: utf
-8 -*- import os import sys if __name__ == "__main__": settings_name = "settings.local" if os.name == 'nt' else "settings.remote" os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_name) from django.core.management im
port execute_from_command_line execute_from_command_line(sys.argv)
ypes (b,i,l,f,s,u,bb,d,dt,td,t,st) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", [None] * 12) c.execute("select b,i,l,f,s,u,bb,d,dt,td,t,st from test_datatypes") r = c.fetchone() self.assertEqual(tuple([None] * 12), r) c.execute("delete from test_datatypes") ...
stCase
): cursor_type = pymysql.cursors.DictCursor def setUp