prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# -*- coding: utf-8 -*- # © 2012-2016 Camptocamp SA # License AGPL-3.0 or lat
er (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', 'version': '10.0.2.1.1', 'author': "Camptocam
p,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'http://www.camptocamp.com', 'license': 'AGPL-3', 'depends': [ 'base', 'account', 'report', 'l10n_ch_base_bank', 'base_transaction_id', # OCA/bank-statement-reconcile ], 'data': [ "views/company.xml", "...
info_system = 'http://webpac.lib.nthu.edu.tw/F/' top_circulations = 'http://www.lib.nthu.edu.tw/guide/topcirculation
s/index.htm' top_circulations_bc2007 = 'http://www.lib.nthu.edu.tw/guide/topcirculations/bc2007.htm' rss_recent_books = 'http://webpac.lib.nthu.edu.tw:8080/nbr/reader/rbn_rss.jsp' lo
st_found_url = 'http://adage.lib.nthu.edu.tw/find/search_it.php'
import pyglet from pyglet.window import key window = pyglet.window.Window() @window.event def on_key_p
ress(symbol, modifiers): print('A key was pressed') if symbol == key.A: print('The "A" key was pressed.') elif symbol == key.LEFT: pri
nt('The left arrow key was pressed.') elif symbol == key.ENTER: print('The enter key was pressed.') @window.event def on_draw(): window.clear() pyglet.app.run()
blems = Problems(changes=[]) review = Review(self.repo, self.pr) sha = 'abc123' review.publish(problems, sha) assert self.pr.create_comment.called, 'Should create a comment' msg = ('Could not review pull request. ' 'It may be too large, or contain no reviewable ...
ew(self.repo, self.pr) review.publish_summary(problems) assert self.pr.create_comment.called eq_(1, self.pr.create_comment.call_count) msg = """There are 2 errors: * Console/Command/Task/AssetBuildTask.php, line 117 -
Something bad * Console/Command/Task/AssetBuildTask.php, line 119 - Something bad """ self.pr.create_comment.assert_called_with(msg) class TestProblems(TestCase): two_files_json = load_fixture('two_file_pull_request.json') # Block offset so lines don't match offsets block_offset = load_fixture('...
fr
om typing import TypeVar, Dict, Iterable, Any T = TypeVar("T") def foo(values: Dict[T, Iterable[Any]]): for e in []: values.setdefault(e, un
defined)
# -*- coding: utf-8 -*- # Copyright (C) 2013 Michael Hogg # This file is part of bonemapy - See LICENSE.txt for information on usage and redistribution import bonemapy from distutils.core import setup setup( name = 'bonemapy', version = bonemapy.__version__, description = 'An ABAQUS plug-in to map bo...
ithub.com/mhogg/bonemapy/releases", classifiers = [ "Programming Language :: Python",
"Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Environment :: Plugins...
import logbook import show_off_web_app.infrastructure.static_cache as static_cache import pyramid.httpexceptions as exc from show_off_web_app.infrastructure.supressor import suppress import show_off_web_app.infrastructure.cookie_auth as cookie_auth from show_off_web_app.services.account_service import AccountService ...
self.request = request self.build_cache_id = static_cache.build_cache_id log_name = 'Ctrls/' + type(self).__name__.replace("Controller", "") self.log = logbook.Logger(log_name) @property def is_logged_i
n(self): return cookie_auth.get_user_id_via_auth_cookie(self.request) is not None # noinspection PyMethodMayBeStatic @suppress() def redirect(self, to_url, permanent=False): if permanent: raise exc.HTTPMovedPermanently(to_url) raise exc.HTTPFound(to_url) @property ...
#!/usr/bin/python # -*- coding: utf-8 -*- #----------------------------------------------------------------- #-- Ser
vo class #-- Juan Gonzalez-Gomez (obijuan). May-2013 #----------------------------------------------------------------- #-- Controlling the position of servos from the PC #-- The Arduino / skymega or another arduino compatible board #-- should have the firmware FingerServer uploaded #---------------------------------...
class. For accessing to all the Servos""" def __init__(self, sp, dir = 0): """Arguments: serial port and servo number""" self.sp = sp #-- Serial device self.dir = dir #-- Servo number self._pos = 0; #-- Current pos def __str__(self): str1 = "Servo: {0}\n".format(self.dir) str2 =...
import zipfile try: import zlib COMPRESSION = zipfile.ZIP_DEFLATED except: COMPRESSION = zipfile.ZIP_STORED try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.core.files.uploadedfile import SimpleUploadedFile class NotACompressedFile(Exception): ...
uteError: # If not, keep it self.zf.write(file_input, arcname=arcname, compress_type=COMPRESSION) else: self.zf.writestr(arcname, file_input.read()) def contents(self): return [filename for fi
lename in self.zf.namelist() if not filename.endswith('/')] def get_content(self, filename): return self.zf.read(filename) def write(self, filename=None): # fix for Linux zip files read in Windows for file in self.zf.filelist: file.create_system = 0 self.descriptor...
import frappe def execute(): frappe.reload_doc("core", "doctype", "tod
o") try: frappe.db.sql("""update tabToDo set status = if(ifnull(checked,0)=0, 'Open', 'Closed
')""") except: pass
__version__ =
"2.
0"
#!/usr/bin/env python # Calder Phillips-Grafflin - WPI/ARC Lab import rospy import math import tf from tf
.transformations import * from visualization_msgs.msg import * from geometry_msgs.msg import * class RobotMarkerPublisher: def __init__(self, root_frame, rate): self.root_frame = root_frame self.rate =
rate self.marker_pub = rospy.Publisher("robot_markers_debug", Marker) rate = rospy.Rate(self.rate) while not rospy.is_shutdown(): self.display_table() rate.sleep() def display_table(self): # Make table top marker_msg = Marker() marker_msg.type...
# -*- coding: utf-8 -*- # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Summary', 'summary': 'Summary Module used by CLVsol Solutions.', 'version': '12.0.4.0', 'author': 'Carlos Eduardo Vercelino - CLVsol', 'ca...
ary_security.xml', 'security/ir.model.access.csv', 'views/summary_template_view.xml', 'views/summary_view.xml', 'views/summary_log_view.xml', 'views/file_system_view.xml', ], 'demo': [], 'test': [], 'init_xml': [], 'test': [], 'update_xml': [], 'instal...
False, 'active': False, 'css': [], }
ate the `min_diff_loss`. This should only be set if neither `sensitive_group_dataset` or `nonsensitive_group_dataset` is passed in. Furthermore, the `x` component for every batch should have the same structure as that of the `original_dataset` batches' `x` components. This function should be...
Assert that all min_diff_xs have the same structure as original_x. # TODO: Should we assert that Tensor shapes are the same (other # than number of examples). min_diff_xs = [ tf.keras.utils.unpack_x_y_sample_weight(batch)[0] # First element is x. for batch in structure_u...
f_structure(min_diff_batch) ] for min_diff_x in min_diff_xs: try: tf.nest.assert_same_structure(original_x, min_diff_x) except Exception as e: raise type(e)( "The x component structure of (one of) the `min_diff_dataset`(s) " "does not match that of the origina...
stle_battlement_stairs_a",0,"castle_battlement_stairs_a","bo_castle_battlement_stairs_a", []), ("castle_battlement_stairs_b",0,"castle_battlement_stairs_b","bo_castle_battlement_stairs_b", []), ("castle_gate_house_a",0,"castle_gate_house_a","bo_castle_gate_house_a", []), ("castle_round_tower_a",0,"castle_round_tower...
er_of_targets_destroyed", 1), (try_end), (try_end), #giving gold for destroying target (for trebuchet) #step-1 calculating total damage given to that scene prop (assign, ":total_damage_given", 0), (get_max_players, ":num_players"), (try_for_range, ":player_no", 0, ":num...
(player_is_active, ":player_no"), (try_begin), (eq, "spr_trebuchet_destructible", "$g_destructible_target_1"), (player_get_slot, ":damage_given", ":player_no", slot_player_damage_given_to_target_1), (else_try), (player_get_slot, ":damage_given", ":player_no", slot_player_da...
import urwid import logging class UserInput(object): def __init__(self): self._viewMap = None self._mainLoop = None def set
Map(self, ** viewMap): self._viewMap = viewMap def setLoop(self, loop): self._mainLoop = loop def __call__(self, keypress): logging.debug('keypress={}'.format(keypress)) if keypress in ('q', 'Q'): raise urwid.ExitMainLoop() if type(keypress) is not str: ...
return view = self._viewMap[keypress.upper()] self._mainLoop.widget = view.widget()
# # SVC (SVM Multi classifier) # # @ author becxer # @ e-mail becxer87@gmail.com # import numpy as np from pytrain.SVM import SVM from pytrain.lib import convert from pytrain.lib import ptmath class SVC: def __init__(self, mat_data,
label_data): self.x = np.mat(convert.list2npfloat(mat_data)) self.ys = np.mat(np.sign(convert.list2npfloat(label_data) - 0.5)) self.outbit = self.ys.shape[1] self.svm4bit = [] for i in range(self.outbit): self.svm4bit.append(SVM(self.x, self.ys[:,i])) de...
r i in range(self.outbit): self.svm4bit[i].fit(C, toler, epoch, kernel, kernel_params) def predict(self, array_input): array_input = np.mat(convert.list2npfloat(array_input)) output = [] for i in range(self.outbit): output.append(self.svm4bit[i].predict(array...
import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing.label import _check_numpy_unicode_bug from sklearn.utils import column_or_1d from ..base import SparkBroadcasterMixin, SparkTransformerMixin class SparkLabelEncoder(LabelEncoder, SparkTransformerMixin, ...
els to normalized encoding. Parameters ---------- y : ArrayRDD [n_samples] Target values. Returns ------- y : ArrayRDD [n_samples] """
mapper = super(SparkLabelEncoder, self).transform mapper = self.broadcast(mapper, y.context) return y.transform(mapper) def inverse_transform(self, y): """Transform labels back to original encoding. Parameters ---------- y : numpy array of shape [n_samples] ...
"""grace Revision ID: 3d30c324ed4 Revises: 8c78a916f1 Create Date: 2015-09-07 08:51:46.375707 """ # revision identifiers, used by Alembic. revision = '3d30c324ed4' down_revision = '8c78a916f1' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands aut...
## end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### pass ### end Alembic com
mands ###
#!/usr/bin/env python network_device = { 'ip_addr' : '81.1.1.3', 'username' : 'user1', 'passwd' : 'pass
123', 'vendor' : 'cisco', 'model' : '3940', } for k,v in network_device.items(): print k,v network_device['passwd']='newpass' netwo
rk_device['secret']='enable' for k,v in network_device.items(): print k,v try: print network_device['device_type'] except KeyError: print "Device type not found\n"
from OpenGLCffi.GLES2 impo
rt params @params(api='gles2', prms=['n', 'ids']) def glGenQueriesEXT(n, ids): pass @params(api='gles2', prms=['n', 'ids']) def glDeleteQueriesEXT(n, ids): pass @params(api='gles2
', prms=['id']) def glIsQueryEXT(id): pass @params(api='gles2', prms=['target', 'id']) def glBeginQueryEXT(target, id): pass @params(api='gles2', prms=['target']) def glEndQueryEXT(target): pass @params(api='gles2', prms=['target', 'pname', 'params']) def glGetQueryivEXT(target, pname): pass @params(api='gl...
# Create the directory to send data to/from gem5 system self.logger.info("Creating temporary directory for interaction " " with gem5 via virtIO: {}" .format(self.gem5_interact_dir)) os.mkdir(self.gem5_interact_dir) ...
# pylint: disable=no-member ts = self.target.execute(cmd.format(self.target.busybox)).strip() filepath = filepath.format(ts=ts) successful_capture = False if len(screen_caps) == 1: # Bail out if we do not have image, and resort to the slower, built #...
age = os.path.join(self.gem5_out_dir, "file.png") im = Image.open(gem5_image) im.save(temp_image, "PNG") shutil.copy(temp_image, filepath) os.remove(temp_image) # pylint: disable=undefined-variable gem5_logger.info("capture_...
import pytes
t, sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../") from unittest import TestCase from pylogic.case import Case class TestBaseOperand(TestCase): def test_eq_case(self): case1 = Case("parent", "homer", "bart") case2 = Case("parent", "homer", "bart") assert case...
case2 = Case("parent", "homer", "lisa") assert case1 != case2 def test_not_eq_case2(self): case1 = Case("parent", "homer", "bart") case2 = Case("brother", "homer", "lisa") assert case1 != case2
import unittest from prtgcli.cli import main class TestQuery(unittest.TestCase): def setUp(self): pass def test_list_devices(self): pass def test_list_sensors(self): pass def test_status(self):
pass def test_update(s
elf): pass
# -*- coding: utf-8 -*- # Generated by Dja
ngo 1.9.4 on 2016-04-26 16:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pppcemr', '0122_auto_20160425_1327'), ] operations = [ migrations.AddField( model_name='treatment', ...
e), ), migrations.AlterField( model_name='treatment', name='weight_kg', field=models.FloatField(blank=True, help_text='kg', null=True), ), ]
# TempConv.py # Celcius to Fahreinheit def Fahreinheit(temp): temp
= float(temp) temp = (temp*9/5)+32 return temp # Fahreinheit to Ce
lcius def Celcius(temp): temp = float(temp) temp = (temp-32)*5/9 return temp
###### # # FDAction class and related functions # ################################################################################ class FDAction(FDReady): """ A task that yields an instance of this class will be suspended until an I/O operation on a specified file descriptor is complete. """ ...
A task that yields the result of this function will be resumed when sock is readable, and the value of the yield expression will be the result of receiving from sock. If a timeout keyword is given and is not None, a Timeout exception will be raised in the yielding task if sock is not readable aft...
data, address = (yield recvfrom(sock, 1024, timeout=5)) except Timeout: # No data after 5 seconds """ return FDAction(sock, sock.recvfrom, args, kwargs, read=True) def send(sock, *args, **kwargs): """ A task that yields the result of this function will be resumed when soc...
cept Exception as e: pass # Start printing stuff again. settings["verbose"] = True os.chdir(cwd) return _d def noaa(D="", path="", wds_url="", lpd_url="", version=""): """ Convert between NOAA and LiPD files | Example: LiPD to NOAA converter | 1: L = lipd.readLipd() | 2: l...
str lpd_url: URL where LiPD file will be stored on NOAA's FTP server :param str version: Version of the dataset :return none: """ global files, cwd try: # When going from NOAA to LPD, use the global "files" variable. # When going from LPD to NOAA, use the data from the LiPD Library...
mode: Convert LiPD files to NOAA files if _mode == "1": # _project, _version = noaa_prompt_1() if not version or not lpd_url: print("Missing parameters: Please try again and provide all parameters.") return if not D: print("Erro...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Httpie(PythonPackage): """Modern, user-friendly command-line HTTP client for the API era."...
ends_on('python@3.6:', when='@2.5:', type=('build', 'run')) depends_on('py-setuptools', type=('build', 'run')) depends_on('py-charset-normalizer@2:', when='@2.6:', type=('build', 'run')) depends_on('py-defusedxml@0.6:', when='@2.5:', type=('build', 'run')) depends_on('py-
pygments@2.1.3:', type=('build', 'run')) depends_on('py-pygments@2.5.2:', when='@2.5:', type=('build', 'run')) depends_on('py-requests@2.11:', type=('build', 'run')) depends_on('py-requests@2.22:+socks', when='@2.5:', type=('build', 'run')) depends_on('py-requests-toolbelt@0.9.1:', when='@2.5:', type=('...
fro
m vmware.models import VM, VMwareHost from rest_framework import serializers class VMSerializer(serializers.ModelSerializer): class Meta: model = VM fields = ('name', 'moid', 'vcenter', 'host', 'instance_uuid', ...
ded_time', 'is_template', 'state') class VMWareHostSerializer(serializers.ModelSerializer): baremetal = serializers.HyperlinkedRelatedField(many=False, view_name='baremetal-detail', read_only=True) class Meta: model = VMwareHost fields = ('name', ...
import os import stat import time from inaugurator import sh class TargetDevice: _found = None @classmethod def device(cls, candidates): if cls._found is None: cls._found = cls._find(candidates) return cls._found pass @classmethod def _find(cls, candidates): ...
raise Exception( "DOK was found on SDA. cannot continue: its likely the " "the HD driver was not lo
aded correctly") except: pass print "Found target device %s" % device return device print "didn't find target device, sleeping before retry %d" % retry time.sleep(1) os.system("/usr/sbin/busybox mdev -s") rai...
from django.db import models from jsonfield import JSONField from collections import OrderedDict class BaseObject(models.Model): """ The base model from which all apps inherit """ # Type represents the app that uses it. Assets, Persons, Orgs, etc type = models.CharField(max_length=256) # Rel...
ributes = JSONField(load_kwargs={'object_pairs_hook': OrderedDict}, blank=True) def __init__(self, *args, **kwargs): super(BaseObject, self).__init__(*args, **kwargs) if not self.pk and not self.type: self.type = self.TYPE class BasePropertyManager(models.Manager): def create_att...
property_set = [] for attr, value in attributes.items(): property_set.append(BaseProperty(baseobject=baseobject, key=attr, value=value)) self.bulk_create(property_set) class BaseProperty(models.Model): """ Key-Value attributes of objects are stored here. """ baseob...
""" Default settings for the ``mezzanine.generic`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before ...
"will receive an email notification each time a " "new comment is posted on the site."), editable=True, default="", ) register_setting( name="COMMENTS_NUM_LATEST", label=_("Admin comments"), description=_("Number of latest comments...
itable=True, default=5, ) register_setting( name="COMMENTS_UNAPPROVED_VISIBLE", label=_("Show unapproved comments"), description=_("If ``True``, comments that have ``is_public`` " "unchecked will still be displayed, but replaced with a " "``waiting to be ...
# -*- coding: utf-8 -*- ######################################
######################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can red
istribute 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...
#!/usr/bin/env python3 """ Lazy 'tox' to quickly check if branch is up to PR standards. This is NOT a tox replacement, only a quick check during development. """ import os import asyncio import sys import re import shlex from collections import namedtuple try: from colorlog.escape_codes import escape_codes except...
__)))) files = await git() if not files: print( "No changed files found. Please ensure you have added your "
"changes with git add & git commit" ) return pyfile = re.compile(r".+\.py$") pyfiles = [file for file in files if pyfile.match(file)] print("=============================") printc("bold", "CHANGED FILES:\n", "\n ".join(pyfiles)) print("=============================") skip_lin...
#!/usr/bin/env python """shuffle a dataset""" import random import sys def sol_shuffle(filena
me, out_filename): try: file = open(filename, 'rb') lines = file.readlines() if len(lines) == 0: print 'empty file' file.close() sys.exit() if lines[-1][-1] != '\n': lines[-1]+='\n' random.shuffle(lines) wfile = open(ou...
import abc class RuleLearner: """2D 2-person board game rule learner base class TODO """ def __init__(self, board_height, board_width): """Initialize the rule learner Subclasses should call this constructor. :type board_height: positive integer :param board_height: ...
:param board_width: the width (number of columns) of the board """ self._board_height = board_height self._board_width = board_width @abc.abstractmethod def get_valid_moves(self, board): """Get the valid moves for the board. :type board: Boards.Board :p...
alid set to 1, the rest set to 0 """ pass
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
# limitations under the License. """ The devices file. """ class Devices: def __init__(self): fo = open("/proc/devices") self._charmap = {} self._blockmap = {} for line in fo.readlines(): if line.start
swith("Character"): curmap = self._charmap continue elif line.startswith("Block"): curmap = self._blockmap continue elif len(line) > 4: [num, fmt] = line.split() num = int(num) curmap[...
import glob def handle(userToken, _
): # Get usertoken data userID = userToken.userID # Make sure the match exists matchID = userToken.matchID if mat
chID not in glob.matches.matches: return match = glob.matches.matches[matchID] # Get our slotID and change ready status slotID = match.getUserSlotID(userID) if slotID != None: match.toggleSlotReady(slotID)
### # # W A R N I N G # # This recipe is obsolete! # # When you are looking for copying and pickling functionality for generators # implemented in pure Python download the # # generator_tools # # package at the cheeseshop or at www.fiber-space.de # ### import new import copy imp...
de = f_gen.gi_frame.f_code offset = f_gen.gi_frame.f_lasti locals = f_gen.gi_frame.f_l
ocals if offset == -1: # clone the generator argcount = f_code.co_argcount else: # bytecode hack - insert jump to current offset # the offset depends on the version of the Python interpreter if sys.version_info[:2] == (2,4): offset +=4 elif sys.version_info...
# coding: utf-8 # # Copyright © 2017 weirdgiraffe <giraffe@cyberzoo.xyz> # # Distributed under terms of the MIT license. # import sys try: # real kodi import xbmc import xbmcaddon import xbmcgui import xbmcplugin except ImportError: # mocked kodi from mock_kodi import xbmc from mock_kodi imp...
essage) / 10 * 2000 title = title.replace('"', '\\"') message = message.replace('"', '\\"') xbmc.executebuiltin('Notification("{0}",
"{1}","{2}","{3}")'.format( title.encode('ascii', 'ignore'), message.encode('ascii', 'ignore'), timeout, self.icon))
uiltin_recipe_collection = get_builtin_recipe_collection() self.scheduler_config = SchedulerConfig() try: with zipfile.ZipFile(P('builtin_recipes.zip', allow_user_override=False), 'r') as zf: self.favicons = dict([(x.filename, x) for x in zf.infolist() if ...
ge', 'und') if lang: lang = lang.replace('-', '_') if lang not in lang_map: lang_map[lang] = factory(NewsCategory, new_root, lang)
factory(NewsItem, lang_map[lang], urn, x.get('title')) self.showing_count += 1 self.builtin_count += 1 for x in self.scheduler_config.iter_recipes(): urn = x.get('id') if urn not in self.all_urns: self.scheduler_config.un_sche...
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>) # Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can re...
'type': 'ir.actions.client', 'tag': 'action_warn', 'name': _('Failure'), 'params': { 'title': _('Package #%s Cancellation Failed') % package.packge_no, 'text': err, ...
'ship_message' : 'Shipment Cancelled', 'tracking_no': '' }, context=context) return super(stock_packages, self).cancel_postage(cr, uid, ids, context=context) stock_packages() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- # Copyright 2012 splinter authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. class InheritedDocs(type): def __new__(mcs, class_name, bases, dict): items_to_patch = [ (k, v) for k, v in dic...
name): doc = getattr(base, name).__doc__ if doc: if isinstance(obj, property) and not obj.fset: obj.fget.__doc__ = doc dict[name] = property(fget=obj.fget) else: ...
bases, dict)
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import
cint, cstr, flt, nowdate, comma_and, date_diff fro
m frappe import msgprint, _ from frappe.model.document import Document class LeaveControlPanel(Document): def get_employees(self): conditions, values = [], [] for field in ["employment_type", "branch", "designation", "department"]: if self.get(field): conditions.append("{0}=%s".format(field)) values.ap...
#!/usr/bin/env python # -*- coding: utf-8 -*- import latin_noun import latin_pronoun import latin_adj import latin_conj import latin_prep import latin_verb_reg import latin_verb_irreg import util class LatinDic: dic = {} auto_macron_mode = False def flatten(text): ret
urn text.replace(u'ā',u'a').replace(u'ē',u'e').replace(u'ī',u'i').replace(u'ō',u'o').replace(u'ū',u'u').replace(u'ȳ',u'y').lower() def register(surface, info): if not info.has_key('pos'): return if LatinDic.auto_macron_mode: surface = flatten(surface) if LatinDic.dic.has_key(surface): La...
else: LatinDic.dic[surface] = [info] def register_items(items): for item in items: register(item['surface'], item) def lookup(word): return LatinDic.dic.get(word, None) def dump(): for k, v in LatinDic.dic.items(): print util.render2(k, v) def load_def(file, tags={}): ...
from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import IntegrityError from django.shortcuts import render, redirect from django.contrib import messages from django import forms as django_forms from django.views.decorators.cache import cache_page from django...
ate, context) @log @cache_page(60 * 3) def page(request, page_slug, template='user/blog/page.html', context={}): blog_logic = logic.BlogLogic(request) context['page'] = blog_logic.page(page_slug) return render(request, tem
plate, context) ''' Posts ''' @log def posts(request, template='user/blog/posts.html', context={}): blog_logic = logic.BlogLogic(request) context['posts'] = blog_logic.posts() return render(request, template, context) @log @cache_page(60 * 3) def post(request, post_id, post_slug, template='user/blog/p...
__all__ = [ 'fixed_value', 'coalesce', ] try: from itertools import ifilter as filter except ImportError: pass class _FixedValue(object):
def __init__(self, value): self._value = value def __call__(self, *args, **kwargs): return self._value def fixed_value(value):
return _FixedValue(value) class _Coalesce(object): def _filter(self, x): return x is not None def __init__(self, callbacks, else_=None): self._callbacks = callbacks self._else = else_ def __call__(self, invoice): results = ( callback(invoice) ...
#MenuTitle: Set Preferred Names (Name IDs 16 a
nd 17) for Width Variants # -*- coding: utf-8 -*- __doc__=""" Sets Preferred Names custom pa
rameters (Name IDs 16 and 17) for all instances, so that width variants will appear in separate menus in Adobe apps. """ thisFont = Glyphs.font # frontmost font widths = ( "Narrow", "Seminarrow", "Semi Narrow", "Extranarrow", "Extra Narrow", "Ultranarrow", "Ultra Narrow", "Condensed", "Semicondensed", "Semi Condens...
import os import yaml DEFAULT_DIR = '../etc/' class BaseConfig(object): __config = {} __default_dir = None @classmethod def load(cls, filename, default_path=DEFAULT_DI
R): """ Setup configuration """ path = "%s/%s.yaml" % (default_path, filename) cls.__default_dir = default_path
if os.path.exists(path): with open(path, 'rt') as filehandle: cls.__config = dict(yaml.load(filehandle.read()).items() + \ cls.__config.items()) else: raise OSError("Config doesn't exists: %s" % path) @classmethod def get_default_path(...
"""Check for partitioning errors.""" FR = self.states.FR FL = self.states.FL FS = self.states.FS FO = self.states.FO checksum = FR+(FL+FS+FO)*(1.-FR) - 1. if abs(checksum) >= 0.0001: msg = ("Error in partitioning!\n") msg += ("Checksum: %f, FR...
else: # Nitrogen stress is more severe than water stress resulting in # less partitioning to leaves and more to stems FLVMOD = exp(-params.NPART * (1.0-NNI)) states.FL = params.FLTB(DVS) * FLVMOD states.FS = params.FSTB(DVS) + params.FLTB(DVS) - states.FL ...
arams.FOTB(DVS) # Pack partitioning factors into tuple states.PF = PartioningFactors(states.FR, states.FL, states.FS, states.FO) self._check_partitioning() def calc_rates(self, day, drv): """ Return partitioning factors based on current D...
from temboo.Library.Amazon.SNS.AddPermission import AddPermission, AddPermissionInputSet, AddPermissionResultSet, AddPermissionChoreographyExecution from temboo.Library.Amazon.SNS.ConfirmSubscripti
on import ConfirmSubscription, ConfirmSubscriptionInputSet, ConfirmSubscriptionResultSet, ConfirmSubscriptionChoreographyExecution from temboo.Library.Amazon.SNS.CreateTopic import CreateTopic, CreateTopicInputSet, Cre
ateTopicResultSet, CreateTopicChoreographyExecution from temboo.Library.Amazon.SNS.DeleteTopic import DeleteTopic, DeleteTopicInputSet, DeleteTopicResultSet, DeleteTopicChoreographyExecution from temboo.Library.Amazon.SNS.GetTopicAttributes import GetTopicAttributes, GetTopicAttributesInputSet, GetTopicAttributesResult...
eeGroup, Subsession as OtreeSubsession, Constants import json import channels import logging from otree import constants_internal import django.test from otree.common_internal import (get_admin_secret_code) client = django.test.Client() ADMIN_SECRET_CODE = get_admin_secret_code() # For automatic inactive pushing #??...
nt.post( p.participant._current_form_page_url, data={ constants_internal.timeout_happened: True,
constants_internal.admin_secret_code: ADMIN_SECRET_CODE }, follow=True ) else: resp = client.get(p.participant._start_url(), follow=True) ...
# i2c_esp.py Test program for asi2c.py # Tests Responder on ESP8266 # The MIT License (MIT) # # Copyright (c) 2018 Peter Hinch # # Permission is hereby granted, free of charge, to any per
son obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Soft...
oftware. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIAB...
# Borrowed and modif
ied from xbmcswift import logging import xbmc from pulsar.ad
don import ADDON_ID class XBMCHandler(logging.StreamHandler): xbmc_levels = { 'DEBUG': 0, 'INFO': 2, 'WARNING': 3, 'ERROR': 4, 'LOGCRITICAL': 5, } def emit(self, record): xbmc_level = self.xbmc_levels.get(record.levelname) xbmc.log(self.format(record...
options.listhosts or options.listtasks or options.listtags or options.syntax: self._tqm = None else: self._tqm = TaskQueueManager(inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=self.passwords) def run(self): ''' Ru...
ng a listing entry = {'playbook': playbook_path} entry['plays'] = [] else: # make sure the tqm has callbacks loaded self._tqm.load_callbacks() self._tqm.send_callback('v2_playbook_on_start', pb) ...
icode(playbook_path))) for play in plays: if play._included_path is not None: self._loader.set_basedir(play._included_path) else: self._loader.set_basedir(pb._basedir) # clear any filters which ...
#!/usr/bin/python from pisi.ac
tionsapi import shelltools, get, cmaketools, pisitools def setup(): cmaketools.configure() def build(): cmaketools.make() def install(): cmaketools.install() pisitools.dodo
c ("AUTHORS", "ChangeLog", "COPYING")
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'pyramid_debugtoolbar', 'waitress', ] setup(name='tilecost',...
_safe=False, install_requires=requires, tests_require=requires, test_suite="tilecost", entry_points="""\ [paste.app_factory] main = tilecost:main """,
)
__author__ = 'mwagner' from PyQt4.Qt import Qt from PyQt4.QtGui import QDialog, QIcon from ..view.Ui_VertexDialog import Ui_VertexDialog from ..model.VertexToolsError import * class VertexDialog(QDialog, Ui_VertexDialog): def __init__(self, plugin, parent=None): super(VertexDialog, self).__init__(pare...
help.gif")) self.se
tWindowIcon(QIcon(":beninCad/info.png"))
# -*- coding: utf-8 -*- # Open Source Initiative OSI - The MIT License (MIT):Licensing # # The MIT License (MIT) # Copyright (c) 2012 DotCloud Inc (opensource@dotcloud.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Softwa...
ita(self): return 42 srv = MySrv() srv.bind(endpoint) gevent.spawn(sr
v.run) client = zerorpc.Client(endpoint) assert client.lolita() == 42
import json import requests import key API_key = key.getAPIkey() #load all champion pictures def load_champion_pictures(champion_json): print len(champion_json['data']) version = champion_json['version'] print "version: " + version for champion in champion_json['data']: print champion r = requests.get('http:...
champion_json['status']['message'] return load_champion_pictures(champion_json) # quick fix to change MonkeyKing to Wukong so that sort_keys sorts it properly champion_json['data']['Wukong'] = champion_json['data']['MonkeyKing'] del champion_json['data']['Monke
yKing'] except ValueError as e: print e.message return with open('static/json/champion.json', 'w') as f: json.dump(champion_json, f, sort_keys=True) load_champion_json()
# Standard import os import sys # Third Party import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import seaborn as sns import pyfilm as pf from skimage.measure import label from skimage import filters plt.rcParams.update({'figure.autolayout': True}) mpl.rcParams['axes.unicode_mi...
un, perc_thresh): nlabels = np.empty(run.nt, dtype=int) labelled_image = np.empty([run.nt, run.nx, run.ny], dtype=int) for it in range(run.nt): tmp = run.ntot_i[it,:,:].copy() # Apply Gaussian filter tmp = filters.gaussian(tmp, sigma=1) thresh = np.percentile(tmp, perc_thre...
_thresh] = 0 tmp[tmp > tmp_thresh] = 1 # Label the resulting structures labelled_image[it,:,:], nlabels[it] = label(tmp, return_num=True, background=0) return(labelled_image, nlabels) def count_structures(run, labelled_image, nlabels): ...
#!/usr/bin/env python # This file mainly exists to allow python setup.py test to work. # # You can test all the variations of
tests by running: # # ./manage.py test && python runtests.py && ./setup.py test && echo OK # import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings' from django.core.management im
port call_command def runtests(): # use the call_command approach so that we are as similar to running # './manage.py test' as possible. Notably we need the South migrations to be # run. call_command('test', verbosity=2) sys.exit(0) if __name__ == '__main__': runtests()
marcxml, req=req, **argd)) else: _ = gettext_set_language(argd['ln']) req.write(template.tmpl_page(top=_('Unknown type: %s') % argd['type'], **argd)) def record_get_keywords(record, main_field=bconfig.CFG_MAIN_FI...
elds with fields from th
e file add - add (even duplicate) fields delete - delete fields which are inside the file @keyword recids: list of record ids, this arg comes from the bibclassify daemon and it is used when the recids contains one entry (recid) - ie. one individual document was processed. We ...
#!/usr/bin/env python import mredis import time ports = [6379, 6380] servers = [] for port in ports: servers.append({'host': 'localhost', 'port': port, 'db': 0}) mr = mredis.MRedis(servers) # Destructive test of the database #
print mr.flushall() #print mr.flushdb() print mr.ping() # Build a set of keys for operations keys = set() for x in xrange(0, 100): key = 'key:%.8f' % time.time() keys.add(key) for key in keys: mr.set(key, time.time()) fetched = mr.keys('key:*') results = [] for server in fetched: for key
in fetched[server]: results.append('%s->%s' % (key, mr.get(key))) print '%i keys fetched' % len(results) for key in keys: mr.delete(key) print mr.bgrewriteaof() print mr.dbsize() print mr.lastsave() #print mr.info() print mr.randomkey()
#!/usr/bin/python3 import argparse, random, textwrap from datetime import datetime from urllib import request from xml.etree import ElementTree labels = { "clouds": "%", "humidity": "%", "precipitation": "%", "temp": "°F", "wind-direction": "°", "wind-speed": " mph", } parser = argparse.Argume...
("erro
r: " + error)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import errno import hashlib import os from django.conf import settings from django.core.files import File from django.core.files.storage import FileSystemStorage from django.utils.encoding import force_unicode __all__ = ["HashedFileSystemStorage"] __aut...
content.seek(cursor) def save(self, name, content):
if getattr(settings, "DEBUG", None) is True: print "{}::save({})".format(self.__class__.__name__, name) if name is None: name = content.name name = self._get_content_name(name, content) name = self._save(name, content) return force_unicode(name.replace('\\', ...
"""Extensions which provide a block segments.""" from __future__
import division from __future__ import a
bsolute_import from __future__ import print_function from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404 from django.views import generic from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from rest_framework import reverse from druidapi.query.models impo
rt QueryModel from models import Result from forms import SearchForm import requests import json class IndexView(generic.View): """ The view for the main page, where the search form is """ def get(self, request): form = SearchForm return render(request, 'index.html', {'form': form}) ...
Little bit of cheating, ideally the html would handle this # but, I felt like building the webapp in django... # alternatively, I could just reach over and build this. start = form.cleaned_data['start'].isoformat() end = form.cleaned_data['end'].isoformat() # ...
rom importlib import import_module from ijson import common from ijson.backends.python import basic_parse, Lexer from ijson.compat import IS_PY2 JSON = b''' { "docs": [ { "null": null, "boolean": false, "true": true, "integer": 0, "double": 0.5, "exponent": 1.0e+2, "lo...
('null', None), ('map_key', 'boolean'), ('boolean', False), ('m
ap_key', 'true'), ('boolean', True), ('map_key', 'integer'), ('number', 0), ('map_key', 'double'), ('number', Decimal('0.5')), ('map_key', 'exponent'), ('number', 100), ('map_key', 'long'), ...
import os, random rfilename=random.choice(os.listdir("/storage/pictures")) rextension=os.path.splitext(rfilename)[1] picturespath='/storage/pictures/' #TODO Probably dont need a forloop can possibly do random* #TODO What if the directory is empty? for filename in os.listdir(picturespath): if filename.startswith("ran...
respath + str(random.random()).rsplit('.',1)[1] + extension # rename the existing random wallpaper to something random filename=picturespath+filename os.rename(filename, newname) # now rename the newly randomly founded file to be random rfilename=picturespath+rfilename os.rename(rfilename, picturespath+
'random'+rextension)
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-11-14 21:43 from __future__ import unicode_literals from django.db import migrations class Migr
ation(migrations.Migration): dependencies = [ ('recipe', '0010_auto_20171114_1443'), ] operations = [ migrations.RemoveField( model_name='direction', name='recipe', ), migrations.DeleteModel( name='Direction',
), ]
from __future__ import division from __future__ import print_function import os import sys import functools # Update path root = os.path.join(os.getcwd().split('proj1')[0], 'proj1') if root not in sys.path: sys.path.append(root) import numpy as np import pandas as pd import multiprocessing from pdb import set_tra...
data.to_csv(os.path.abspath(os.path.join(root,"tasks/task5.csv"))) def task5_plot(): data = pd.read_csv(os.path.abspath("tasks/task5.csv")) plot_runtime(data["Rho"], data["Seconds"]) set_trace() def compare_plot(): rho_list = np.arange(0.05, 1, 0.1) average_rho = [np.mean([rand.exponential(la...
plot_runtime(data["Rho"], average_rho) if __name__ == "__main__": task_5() task5_plot() compare_plot()
# Copyright (C) 2016 Intel Corporation # Released under the MIT license (see COPYING.MIT) from oeqa.core.exception import OEQAMissingVariable from . import OETestDecorator, registerDecorator def has_feature(td, feature): """ Checks for feature in DISTRO_FEATURES or IMAGE_FEATURES. """ if (featur...
') or feature in td.get('IMAGE_FEATURES', '')): return True return False @registerDecorator class skipIfDataVar(OETestDecorator): """ Skip test based on value of a data store's variable. It will get the info of var f
rom the data store and will check it against value; if are equal it will skip the test with msg as the reason. """ attrs = ('var', 'value', 'msg') def setUpDecorator(self): msg = ('Checking if %r value is %r to skip test' % (self.var, self.value)) self.logger...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 # ...
tion.equipage.signaux.repete import SignalRepete from secondaires.navigatio
n.equipage.signaux.termine import SignalTermine
task: res = self.interface.add_cleaning_network(task) add_ports_mock.assert_called_once_with( task, CONF.neutron.cleaning_network, security_groups=CONF.neutron.cleaning_network_security_groups) rollback_mock.assert_called_once_with( ta...
_mock.return_value.update_port = upd_mock with task_manager.acquire(self.cont
ext, self.node.id) as task: self.assertRaisesRegex(exception.NetworkError, 'No neutron ports or portgroups are ' 'associated with node', self.interface.configure_tenant_networks, ...
F ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.core.urlresolvers import reverse from django.template import defaultfilters as filters from django.utils.translation import pgettext_lazy from ...
ging.getLogger(__name__) class AddRuleLink(tables.LinkAction): name = "addrule" verbose_name = _("Add Rule") url = "horizon:project:firewalls:addrule" classes = ("ajax-modal",) icon = "plus" policy_rules = (("network", "cre
ate_firewall_rule"),) class AddPolicyLink(tables.LinkAction): name = "addpolicy" verbose_name = _("Add Policy") url = "horizon:project:firewalls:addpolicy" classes = ("ajax-modal", "btn-addpolicy",) icon = "plus" policy_rules = (("network", "create_firewall_policy"),) class AddFirewallLink(t...
import os import numpy as np from scipy.optimize import curve_fit def gauss(x, A, mu, sigma): return A * np.exp(-(x - mu)**2 / (2. * sigma**2)) scriptmode = True SDM_name = 'test' # The prefix to use for all output files # SDM_name = '13A-213.sb20685305.eb20706999.56398.113012800924' # Set up some useful var...
vos_link = '../vos_link/' # %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%%&% # Find the 21cm spw and check if the obs # is single pointing or mosaic # %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%%&% print "Fin
d HI spw..." # But first find the spw corresponding to it tb.open(vos_dir + msfile + '/SPECTRAL_WINDOW') freqs = tb.getcol('REF_FREQUENCY') nchans = tb.getcol('NUM_CHAN') tb.close() spws = range(0, len(freqs)) # Select the 21cm sel = np.where((freqs > 1.40 * 10**9) & (freqs < 1.43 * 10**9)) hispw = str(spws[sel[0]...
'False'}), 'forward_attributes_from_push_sources': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'map_attributes_from_push_sources': ('django.db.models.fields.BooleanField', [], {'default'...
False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}) }, 'saml.idpoptio
nssppolicy': { 'Meta': {'object_name': 'IdPOptionsSPPolicy'}, 'allow_create': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'binding_for_sso_response': ('django.db.models.fields.CharField', [], {'default': "'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'", ...
from
django.apps import AppConfig class DataimportConfig(AppConfig): name = "intranet.apps.dataimport"
#!/usr/bin/env python import numpy as np from horton import * # specify the even tempered basis set alpha_low = 5e-3 alpha_high = 5e2 nbasis = 30 lnratio = (np.log(alpha_high) - np.log(alpha_low))/(nbasis-1) # build a list of "contractions". These aren't real contractions as every # contraction only co
ntains one basis function. bcs = [] for ibasis in xrange(nbasis): alpha = alpha_low**lnratio # arguments of GOBasisContraction: # shell_type, li
st of exponents, list of contraction coefficients bcs.append(GOBasisContraction(0, np.array([alpha]), np.array([1.0]))) # Finish setting up the basis set: ba = GOBasisAtom(bcs) obasis = get_gobasis(np.array([[0.0, 0.0, 0.0]]), np.array([3]), default=ba)
"""SCons.Variables.PathVariable This file defines an option type for SCons implementing path settings. To be used whenever a a user-sp
ecified path override should be allowed. Arguments to PathVariable are: option-name = name of this option on the command line (e.g. "prefix") option-help = help string for option option-dflt = default value for this option validator = [optional] validator for option value. Predefined va...
hIsDirCreate -- path must be a dir; will create PathIsFile -- path must be a file PathExists -- path must exist (any type) [default] The validator is a function that is called and which should return True or False to indicate if the path ...
mote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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...
dispatcher = window.__xinput_window_event_dispatcher except AttributeError: dispatcher = window.__xinput_window_event_dispatcher = \ XInputWindowEventDispatcher() dispatcher.add_instance(self) device = device._open_device.contents if not device.num_...
s is inspired by test.c of xinput package by Frederic # Lepied available at x.org. # # In C, this stuff is normally handled by the macro DeviceKeyPress and # friends. Since we don't have access to those macros here, we do it # this way. for i in range(device.num_classes)...
# Author: Peter Prettenhofer <peter.prettenhofer@gmail.com> # Lars Buitinck <L.J.Buitinck@uva.nl> # License: Simplified BSD from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import metrics from sklearn.cluster import KMeans, MiniBatchKMean...
############################################ # Do the actual clustering if opts.minibatch: km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=1) else: km = KMeans(n_clusters=true_k, init='random', max_it...
print "done in %0.3fs" % (time() - t0) print print "Homogeneity: %0.3f" % metrics.homogeneity_score(labels, km.labels_) print "Completeness: %0.3f" % metrics.completeness_score(labels, km.labels_) print "V-measure: %0.3f" % metrics.v_measure_score(labels, km.labels_) print "Adjusted Rand-Index: %.3f" % \ metrics.a...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
: None, "d3format": None, } ), get_metric_mock( { "id": 843, "metric_name": "ratio", "verbose_name": "Ratio Boys/Girls", "description": "This represents
the ratio of boys/girls", "expression": "sum(num_boys) / sum(num_girls)", "warning_text": "no warning", "d3format": ".2%", } ), ], ) return mock
fr
om celery.task import Task import requests class Stra
cksFlushTask(Task): def run(self, url, data): requests.post(url + "/", data=data)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # spaceClustering.py # # Copyright 2014 Carlos "casep" Sepulveda <carlos.sepulveda@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Found...
it]+'\n') clusterFile.close xSize = args.xSize ySize = args.ySize # generate graphics of all ellipses for clusterId in range(clustersNumber): dataGrilla = np.zeros((1,7)) for unitId in range(dataCluster.shape[0]): i
f labels[unitId] == clusterId: datos=np.zeros((1,7)) datos[0]=dataCluster[unitId,:] dataGrilla = np.append(dataGrilla,datos, axis=0) ## remove the first row of zeroes dataGrilla = dataGrilla[1:,:] rfe.graficaGrilla(dataGrilla, outputFolder+'Grilla_'+str(clusterId)+'.png', 0, clustersColours[clusterId...
le. For other cases, see the M(copy) or M(template) modules. version_added: "0.7" options: path: description: - The file to modify. - Before 2.3 this option was only usable as I(dest), I(destfile) and I(name). aliases: [ dest, destfile, name ] required: true regexp: aliases: [ 'regex...
e.module_utils._text import to_bytes, to_native def write_changes(modu
le, b_lines, dest): tmpfd, tmpfile = tempfile.mkstemp() with open(tmpfile, 'wb') as f: f.writelines(b_lines) validate = module.params.get('validate', None) valid = not validate if validate: if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % ...
e): self.url = self.url.del_query_param(value) def handle_toggle_query(self, value): query_to_toggle = self.prepare_value(value) if isinstance(query_to_toggle, str): query_to_toggle = QueryString(query_to_toggle).dict current_query = self.url.query.dict for key, ...
# we have a key-match, so remove it from the string ext
= [x for x in ext if x != value] else: # no key match, so add it to the string ext.append(value) ext.sort() self.url = self.url.set_query_param(key, ",".join(ext)) elif ext and len(ext) == 1: # par...
from sympy import AccumBounds, Symbol, floor, nan, oo, E, symbols, ceiling, pi, \ Rational, Float, I, sin, exp, log, factorial, frac from sympy.utilities.pytest import XFAIL x = Symbol('x') i = Symbol('i', imaginary=True) y = Symbol('y', real=True) k, n = symbols('k,n', integer=True) def test_floor(): a...
(Float(17.0)) == 17 assert floor(-Float(17.0)) == -17 assert floor(Float(7.69)) == 7 assert floor(-Float(7.69)) == -8 assert floor(I) == I as
sert floor(-I) == -I e = floor(i) assert e.func is floor and e.args[0] == i assert floor(oo*I) == oo*I assert floor(-oo*I) == -oo*I assert floor(2*I) == 2*I assert floor(-2*I) == -2*I assert floor(I/2) == 0 assert floor(-I/2) == -I assert floor(E + 17) == 19 assert floor(pi +...
1) def logMsg(self, msg, lvl=1): self.className = self.__class__.__name__ utils.logMsg("%s %s" % (self.addonName, self.className), msg, lvl) def onScanStarted(self, library): self.logMsg("Kodi library scan %s running." % library, 2) if library == "video": utils.w...
ui.Dialog().yesno( heading="Confirm delete", line1="Delete file on Emby Server?") if not resp:
self.logMsg("User skipped deletion.", 1) embycursor.close() return url = "{server}/emby/Items/%s?format=json" % itemid self.logMsg("Deleting request: %s" % itemid) doUtils.downloadUrl(url, type=...
# # core.py # # Copyright (C) 2014 dredkin <dmitry.redkin@gmail.com> # # Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Damien Churchill <damoxc@gmail.com> # # Deluge is free software. # # Yo...
error = "Cannot List Contents of "+absolutepath absolutepath = os.path.expanduser("~") if windows(): isroot = self.is_root_folder(folder) and (subfolder == "..") else: isroot = self.is_root_folder(absolutepath) if windows() and isroo
t: subfolders = self.drives_list() absolutepath = "" else: subfolders = self.subfolders_list(absolutepath) return [absolutepath.decode(CURRENT_LOCALE).encode(UTF8), isroot, subfolders, error]
import random from common import generalUtils from common.log import logUtils as log from constants import clientPackets from constants import matchModModes from constants import matchTeamTypes from constants import matchTeams from constants import slotStatuses from objects import glob def handle(userToken, packetDa...
EST HDHR LOBBY OF ALL TIME", "This is gasoline and I set myself on fire", "Everyone is cheating apparently", "Kurwa mac", "TATOE", "This is not your drama landfill.", "I like cheese", "NYO IS NOT A CAT HE IS A DO(N)G", "Datingu startuato" ] # Set match name match.matchName = packetData["m...
ord"] != "": match.matchPassword = generalUtils.stringMd5(packetData["matchPassword"]) else: match.matchPassword = "" match.beatmapName = packetData["beatmapName"] match.beatmapID = packetData["beatmapID"] match.hostUserID = packetData["hostUserID"] match.gameMode = packetData["gameMode"] oldBeatmapM...
from ..rerequest import TemplateRequest init_req = TemplateRequest( re = r'(http://)?(www\.)?(?P<domain>ur(play)?)\.se/(?P<req_url>.+)', encode_vars = lambda v: { 'req_url': 'http://%(domain)s.se/%(req_url)s' % v } ) hls = { 'title': 'UR-play', 'url': 'http://urplay.se/', 'feed_url': 'http://urplay.se/rss',...
al_url>[^"]+)".*?"subtitles":\s?"(?P<subtitles>[^",]*)', encode_vars = lambda v: { 'final_url': ('http://130.242.59.75/%(final_url)s/playlist.m3u8' % v).replace('\\', ''), 'suffix-hint': 'mp4', 'subtitles': v.get('subtitles', '').replace('\\', '') % v } )] } rtmp = { 'items': [init_req, ...
5/ondemand playpath=%(ext)s:/%(final_url)s app=ondemand' % v).replace('\\', ''), 'suffix-hint': 'flv', 'rtmpdump-realtime': True, 'subtitles': v.get('subtitles', '').replace('\\', '') % v } )] } services = [hls, rtmp]
# Copyright (C) 2010 Linaro Limited # # Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org> # # This file is part of Launch Control. # # Launch Control is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License version 3 # as published by the Free Software F...
R A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Launch Control. If not, see <http://www.gnu.org/licenses/>. """ Tests for the Attachment model """ from django.contrib.contenttypes import generic f...
nts(models.Model): """ Test model that uses attachments """ attachments = generic.GenericRelation(Attachment) class Meta: # This requires a bit of explanation. Traditionally we could add new # models inside test modules and they would be picked up by django and # synchronize...
#!/usr/bin/env python3 import unittest from tests import testfunctions from dftintegrate.fourier import vaspdata class TestExtractingVASPDataToDatFiles(unittest.TestCase, testfunctions.TestFunctions): def setUp(self): print('Testing extracting VASP data to .dat fi...
ls') kpts_eigenvals_tocheck = self.
readfile(case, 'tocheck', 'kpts_eigenvals') self.assertEqual(kpts_eigenvals_ans, kpts_eigenvals_tocheck, msg='kpts_eigenvals case '+case) symops_trans_ans = self.readfile(case, 'answer', ...
"""Solve the Project Euler problems using functional Python. https://projecteuler.net/archives """ from importlib import import_module from os import listdir from os.path import abspath, dirname from re import match SOLVED = set(
int(m.group(1)) for f in listdir(abspath(dirname(__file__))) for m in (match(r"^p(\d{3})\.py$", f),) if m ) def compute(problem: int): """Compute the a
nswer to problem `problem`.""" assert problem in SOLVED, "Problem currently unsolved." module = import_module("euler.p{:03d}".format(problem)) return module.compute()
import random import pymel.core as pm from impress import models, register def randomTransform( translate=False, translateAmount=1.0, translateAxis=(False,False,False), rotate=False, rotateAmount=1.0, rotateAxis=(False,False,False), scale=False, scaleAmount=1.0, ...
= map(lambda axis: random.uniform( -translateAmount, translateAmount )*float(axis), translateAxis) object.setTranslation( offset, relative=True ) if rotate: offset = map(lambda axis: random.uniform( -rotateAmount, rotateAmount )*float(axis), rotateAxis) object.setRotation( o...
ffset = map(lambda axis: 1 + ( random.uniform( -scaleAmount, scaleAmount )*float(axis) ), scaleAxis) object.setScale( offset ) print '# Results: %i object randomized. #' % len(objects) class RandomTransformOptions( models.OptionModel ): translate = models.CheckBox( default=1, ann='about the chec...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
print_function import six from cryptography import utils def generate_parameters(key_size, backend): return backend.generate_dsa_parameters(key_size) def generate_private_key(key_size, backend): return
backend.generate_dsa_private_key_and_parameters(key_size) def _check_dsa_parameters(parameters): if utils.bit_length(parameters.p) not in [1024, 2048, 3072]: raise ValueError("p must be exactly 1024, 2048, or 3072 bits long") if utils.bit_length(parameters.q) not in [160, 256]: raise ValueErro...
############################################################################### # Copyright 2016 - Climate Research Division # Environment and Climate Change Canada # # This file is part of the "EC-CAS diags" package. # # "EC-CAS diags" is free software: you can redistribute it and/or modify # it under...
############################################# from .zonalmean import ZonalMean as Zonal from .vinterp import VInterp
from . import TimeVaryingDiagnostic class ZonalMean(Zonal,VInterp,TimeVaryingDiagnostic): """ Zonal mean (or standard deviation) of a field, animated in time. """ def __str__ (self): return 'zonal'+self.typestat+'_'+self.zaxis def do (self, inputs): from .movie import ZonalMovie prefix = '_'.jo...