prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# -*- coding: utf-8 -*-. import dxf2gmlcatastro # carpeta de trabajo path = '/carp
eta/archivos/' # define archivos dxf =
'parcelacad.dxf' gml = 'catastrogml.gml' #Define variables dxffile = path + dxf gmlfile = path + gml src = '25830' # Crea GML dxf2gmlcatastro.crea_gml(dxffile, gmlfile, src) #Añade capa GML a QGIS layer = iface.addVectorLayer(gmlfile, "gmlcatastro", "ogr")
from toee import * import char_class_utils ################################################### def GetConditionName(): return "Loremaster" def GetSpellCasterConditionName(): return "Loremaster Spellcasting" def GetCategory(): return "Core 3.5 Ed Prestige Classes" def GetClassDefinitionFlags(): return CDF_CoreC...
featEnum): return char_class_utils.IsClassFeat(class_feats, featEnum) def GetClassFeats(): return class_feats def I
sAlignmentCompatible( alignment): return 1 def LoremasterFeatPrereq(obj): numFeats = 0 loremasterFeats = (feat_empower_spell, feat_enlarge_spell, feat_extend_spell, feat_heighten_spell, feat_maximize_spell, feat_silent_spell, feat_quicken_spell , feat_still_spell, feat_widen_spell, feat_persistent_spell, feat_scri...
# # getlangnames.py # # Copyright (C) 2007 Red Hat, Inc. All rights reserved. # # 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, o
r # (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 warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy ...
. # import sys sys.path.append("..") import localeinfo import gettext localeInfo = localeinfo.get("en_US.UTF-8") names = {} for k in localeInfo.keys(): found = False for l in localeinfo.expandLangs(k): try: f = open("../po/%s.gmo" %(l,)) except (OSError, IOError): cont...
class ReversiLogic(object): def __init__(self): self.turn = 'b' self.board = Board() # Check if the current self.turn can play. If not, change to the other # player. If he can't play either, return None (game over). def get_whose_turn(self): if self.can_play(): ...
nd an empty square. Move on to the next direction else: break # If we check a square not on the board, just move on to the next. except KeyError: continu
e return attack_lines def flip(self, row, col, directions): # target is the color we'll be changing to. target = self.squares[get_key(row, col)] # squares is the list of squares that need to be graphically updated. squares = [] # Each direction is an attack line....
tionary'): create_filter_rules_list(['a'], self.resource_model) def test_filter_rule_missing_entry_fails(self): with self.assertRaisesRegex(BadFilterRule, 'missing'): create_filter_rules_list([{'key': 'key1'}], self.resource_model) def test_filter_rule_key_not_text_type_fails(s...
th_labels(self.LABELS_2, resource_id='res_2', site_name='other_site') dep3 = self.put_deployment_with_labels(self.LABELS_3, resource_id='res_3', ...
blueprint_id='res_4') self._test_labels_filters_applied(dep1.id, dep2.id, dep3.id, dep4.id) self.assert_filters_applied( [('a', ['b'], LabelsOperator.ANY_OF, 'label'), ('c', ['y', 'z'], LabelsOperator.NOT_ANY_OF, 'label')], {dep1.id}) self...
from . import views from django.urls import path urlpatterns = [ path("", views.PublicWidgets.as_view(), na
me="home"), path("create/widget", views.WidgetCreate.as_view(), name="widget-create"), path("subscription/<pk>/delete", views.SubscriptionDelete.as_view(), name="subscription-delete"), path("user/<username>/subscriptions", views.SubscriptionListView.as_view(), name="subscriptions"), path("user/<username...
s.UserWidgets.as_view(), name="widget-user"), # Widget Views path("widget", views.WidgetListView.as_view(), name="widget-list"), path("widget/<pk>", views.WidgetDetailView.as_view(), name="widget-detail"), path("widget/<pk>/delete", views.WidgetDelete.as_view(), name="widget-delete"), path("widget/<...
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
rt for stderr, perhaps Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>} """ # system imports import sys,
os, select, errno # Sibling Imports import abstract, fdesc, protocol from main import CONNECTION_LOST _stdio_in_use = 0 class StandardIOWriter(abstract.FileDescriptor): connected = 1 ic = 0 def __init__(self): abstract.FileDescriptor.__init__(self) self.fileno = sys.__stdout__.fileno ...
#!/bin/env python # -*- coding: utf-8 -*- """ Description: Compute Phase Tensors from ModEM Dat File and output to CSV files Usage Examples: python scripts/modem_data_to_phase_tensor.py examples/data/ModEM_files/Modular_MPI_NLCG_028.dat [OutDir] python scripts/modem_data_to_phase_tensor.py /e/MTPY2_Outputs...
nd for running the script """ import sys, os from mtpy.modeling.modem import Data from mtpy.mtpy_globals import NEW_TEMP_DIR if __name__ == "__main__": file_dat = sys.argv[1] if len(sys.argv)>2:
outdir = sys.argv[2] else: outdir=NEW_TEMP_DIR obj = Data() obj.compute_phase_tensor(file_dat, outdir)
.env.user.company_id.currency_id currency_rate_id = self.env['res.currency.rate'].search([ ('rate', '=', 1), '|', ('company_id', '=', self.env.user.company_id.id), ('company_id', '=', False)], limit=1) base_currency_id = currency_rate_id.currency_id ctx = context.copy() ...
', 'invoice_id', 'price_subtotal', 'product_id', 'quantity', 'uom_id', 'account_analytic_id', ],
'product.product': ['product_tmpl_id'], 'product.template': ['categ_id'], 'product.uom': ['category_id', 'factor', 'name', 'uom_type'], 'res.currency.rate': ['currency_id', 'name'], 'res.partner': ['country_id'], } def _select(self): select_str = """ SELEC...
mary_key=True)), ('name', models.CharField(help_text=b'This field is the actual domain name. This is the field that powerDNS matches to when it gets a request. The domain name should be in the format of: domainname.TLD.', unique=True, max_length=255, verbose_name='Name')), ('master', mod...
, choices=[(1, 'Public'), (3, 'Private')])), ('created', models.DateTimeField(auto_now_add=True, help_text=b'Added by Erigones.', null=True, verbose_name='Created')), ('changed', models.DateTimeField(auto_now=True, help_text=b'Added by Erigones.', null=True, verbose_name='Last changed'))...
models.IntegerField(default=None, help_text=b'Datacenter ID used for DC-bound DNS records. Added by Erigones.', null=True, verbose_name='Datacenter')), ], options={ 'db_table': 'domains', 'verbose_name': 'Domain', 'verbose_name_plural': 'Domains', ...
from d
jango import forms __all__ = ('RatingField',) class RatingField(forms.ChoiceField):
pass
# License: MIT License https://github.com/passalis/sef/blob/master/LICENSE.txt from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import sklearn from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sef_dr.classification import evaluate_svm from se...
import LinearSEF def supervised_reduction(method=None): # Load data and init seeds train_data, train_labels, test_data, test_labels = load_mnist(dataset_path='data') np.random.seed(1) sklearn.utils.check_random_state(1) n_train = 5000 n_classes = len(np.unique(train_labels)) if method == '...
train_labels[:n_train]) elif method == 's-lda': proj = LinearSEF(train_data.shape[1], output_dimensionality=(n_classes - 1)) proj.cuda() loss = proj.fit(data=train_data[:n_train, :], target_labels=train_labels[:n_train], epochs=50, target='supervised', batch_size=128...
__(self, main_window=None): self.main_window = main_window def get_current_config(self): current_config_dict = {} current_config_dict['h1'] = self.__get_current_table_config(table='h1') current_config_dict['h2'] = self.__get_current_table_config(table='h2') current_config_di...
h1_parent_index += 1 return None def resizing_h1_using_all_visible_h2(self, h1=None): '''automatically resize the h1 using all its h2 visible ''' h2_children = self.get_h2_children_from_h1(h1=h1) list_visible_h2 = self.get_all_h2_visible(lis
t_h2=h2_children) if list_visible_h2 is None: return full_size_h2 = 0 for _h2 in list_visible_h2: full_size_h2 += self.get_size_column(h2=_h2) self.main_window.processing_ui.h1_table.setColumnWidth( h1, full_size_h2) def get_h_columns_from_item...
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2015 Jérémy Bobbio <lunar@debian.org> # # diffoscope 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 Foundati...
tmpdir.mkdir('b') dot_changes_path = str(tmpdir.join('b/test_1.changes')) shutil.copy(TEST_DOT_CHANGES_FILE2_PATH, dot_changes_path) shutil.copy(TEST_DEB_FILE2_PATH, str(tmpdir.join('b/test_1_all.deb'))) return specialize(FilesystemFile(dot_changes_path)) def test_dot_changes_identification(dot_changes...
instance(dot_changes1, DotChangesFile) def test_dot_changes_invalid(tmpdir): tmpdir.mkdir('a') dot_changes_path = str(tmpdir.join('a/test_1.changes')) shutil.copy(TEST_DOT_CHANGES_FILE1_PATH, dot_changes_path) # we don't copy the referenced .deb identified = specialize(FilesystemFile(dot_changes_pa...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import mode
ls, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.
CreateModel( name='Stat', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateTimeField(auto_now_add=True)), ('up', models.BigIntegerField()), ('down', mode...
tApplicable') result = os.path.getctime(py_path) elif time_type == 'Change': if os.name != 'posix': return Expression('Missing', 'NotApplicable') result = os.path.getctime(py_path) elif time_type == 'Modification': result = os.path.getmtime...
mpfilename, {2000, 1, 1, 0, 0, 0.}, "Access"]; >> FileDate[tmpfilename, "Access"] = {2000, 1, 1, 0, 0, 0.} #> SetFileDate[tmpfilename, {2001, 1, 1, 0,
0, 0.}]; #> FileDate[tmpfilename, "Access"] = {2001, 1, 1, 0, 0, 0.} #> SetFileDate[tmpfilename] #> FileDate[tmpfilename, "Access"] = {...} #> DeleteFile[tmpfilename] #> SetFileDate["MathicsNonExample"] : File not found during SetFileDate[MathicsNonExample]. = $Failed """ ...
# -*- coding: utf-8 -*- """ This generate diagram in .png and .svg from neo.core Author: sgarcia """ from datetime import datetime import numpy as np import quantities as pq from matplotlib import pyplot from matplotlib.patches import Rectangle, ArrowStyle, FancyArrowPatch from matplotlib.font_manager import FontP...
properties', [])] for r in range(3): for ch_name in relationships[r]: x1, y1 = calc_coordinates(rect_pos[ch_name], all_h[ch_name])
x2, y2 = calc_coordinates(pos, all_h[name]) if r in [0, 2]: x2 += rect_width connectionstyle = "arc3,rad=-0.2" elif y2 >= y1: connectionstyle = "arc3,rad=0.7" else: connectionstyle ...
#!/usr/local/autopkg/python # encoding: utf-8 # # Copyright 2015 The Pennsylvania State University. # """ BESTemplater.py Created by Matt Hansen (mah60@psu.edu) on 2015-04-30. AutoPkg Processor for importing tasks using the BigFix RESTAPI Updated by Rusty Myers (rzm102@psu.edu) on 2020-02-21. Work in progress. Does...
n(_path.split(os.sep)[:-n]) try: from jinja2 import Environment, ChoiceLoader, FileSystemLoader except ImportError as err: raise ProcessorError("jinja2 module is not installed: %s" % err) # Assign variables template_name = self.env.get("template_name") ...
jinja_env = Environment(loader = ChoiceLoader([ FileSystemLoader(os.getcwd()), FileSystemLoader('templates'), FileSystemLoader(os.path.join(RECIPE_DIR, 'templates')), FileSystemLoader(os.path.join(uppath(RECIPE_DIR, 1), 'templates')), FileSystemLoad...
from base import Phase preparation = Phase('Preparation', 'Initializing connections, fetching data etc.') volume_creation = Phase('Volume creation', 'Creating the volume to bootstrap onto') volume_preparation = Phase('Volume preparation', 'Formatting the bootstrap volume') volume_mounting =
Phase('Volume mounting', 'Mounting bootstrap volume') os_installation = Phase('OS installation', 'Installing the operating system') package_installation = Phase('Package installation', 'Installing software') system_modification = Phase('System modification', 'Modifying configuration files, adding resources, etc.') syst...
s and other leftovers') volume_unmounting = Phase('Volume unmounting', 'Unmounting the bootstrap volume') image_registration = Phase('Image registration', 'Uploading/Registering with the provider') cleaning = Phase('Cleaning', 'Removing temporary files') order = [preparation, volume_creation, volume_...
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='TinyContent', f
ields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, prim
ary_key=True)), ('name', models.CharField(unique=True, max_length=100)), ('content', models.TextField()), ], options={ 'verbose_name': 'Content block', }, ), ]
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging from...
digest', 'digest_length'])): """Request for execution with args and snapshots to extract.""" @classmethod def create_from_snapshot(cls, argv, env, snapshot): return ExecuteProcessRequest( argv=argv, env=env, input_files_digest=snapshot.fingerprint, digest_length=snapshot.digest_length...
turn cls.create_from_snapshot(argv, env, EMPTY_SNAPSHOT) def __new__(cls, argv, env, input_files_digest, digest_length): """ :param args: Arguments to the process being run. :param env: A tuple of environment variables and values. """ if not isinstance(argv, tuple): raise ValueError('argv ...
# (C) British Crown Copyright 2014, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later ve...
e, np.nan) self.assertEqual(proxy.path, grib_fh.name) self.assertEqual(proxy.offset, _message_length * i) self.assertEqual(proxy.regularise, auto_regularise) def test_regular_mixed(self): tell_tale = np.arange(1, 5) * _message_length expected = tell_tale - _messa...
for offset in expected: gw = GribWrapper(grib_message, grib_fh, auto_regularise) self.assertIsInstance(gw._data, NumpyArrayAdapter) proxy = gw._data.concrete self.assertIsInstance(proxy, GribDataProxy) self.assertEqual(proxy.shape, (10, 20)) se...
# -*- coding: utf-8 -*- # # Cherokee-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2001-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free S...
AddCommon (self): if se
lf.show_document_root: table = CTK.PropsTable() table.Add (_('Document Root'), CTK.TextCfg('%s!document_root'%(self.key_rule), True), _(NOTE_DOCUMENT_ROOT)) submit = CTK.Submitter (URL_APPLY) submit += CTK.Indenter (table) self += submit # Publis...
import numpy as np from bmtools.filters import filtfilt_butter def derivatefilterQ(model, q, t, cutoff, fs, filter_order=4): ''' Differentiate data using backwards finite differences and butterworth low pass filter. Takes care of quaternions Inputs: ...
eeze() assert type(dq) == np.matrixlib.defmatrix.matrix assert type(t) == np.ndarray assert dq.shape[0] == len(t) assert dq.shape[1] == model.nv # Differentiate ddq = np.empty((len(t), model.nv)) for frame in xrange(0,len(t)-1): # Backward differences dt = np.float...
ilter ddq_prime = np.empty((len(t), model.nv)) for i in xrange(model.nv): filtered = filtfilt_butter(ddq[:,i], cutoff, fs, filter_order) ddq_prime[:,i] = filtered return np.matrix(ddq_prime)
import requests import json from JumpScale import j from mongoengine import * ENTRY_POINT ="" TOKEN="" class ModelGogsRepo(j.core.models.getBaseModel()): name = StringField(default='') description = StringField(default='') private = BoolField(default=False) readme = StringField(default='Default') ...
'born': 'Fri, 25 Sep 1970 10:00:00 GMT' }, ] r = perform_post('people', json.dumps(people)) print "'people' posted", r.status_code valids = [] if r.status_code == 201: response = r.json() if response['_status'] == 'OK': ...
return valids # def post_works(ids): # works = [] # for i in range(28): # works.append( # { # 'title': 'Book Title #%d' % i, # 'description': 'Description #%d' % i, # 'owner': random.choice(ids), ...
es. ==Operation== The default 'Activate Stretch' checkbox is off. When it is on, the functions described below will wo
rk, when it is off, the
functions will not be called. ==Settings== ===Loop Stretch Over Perimeter Width=== Default is 0.1. Defines the ratio of the maximum amount the loop aka inner shell threads will be stretched compared to the edge width, in general this value should be the same as the 'Perimeter Outside Stretch Over Perimeter Width' se...
hasattr(sys, 'exc_clear'): sys.exc_clear() _app_ctx_stack.push(self) appcontext_pushed.send(self.app) def pop(self, exc=None): """Pops the app context.""" self._refcnt -= 1 if self._refcnt <= 0: if exc is None: exc = sys.exc_info()[1]...
This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked. .. versionadded:: 0.10 """ return self.__c...
e overridden by a subclass to hook into the matching of the request. """ try: url_rule, self.request.view_args = \ self.url_adapter.match(return_rule=True) self.request.url_rule = url_rule except HTTPException as e: self.request.routing...
# -*- coding: utf-8 -*- # # 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 ...
rflowSensorTimeout, \ AirflowSkipException from airflow.models import BaseOperator from airflow.utils import timezone from a
irflow.utils.decorators import apply_defaults class BaseSensorOperator(BaseOperator): """ Sensor operators are derived from this class an inherit these attributes. Sensor operators keep executing at a time interval and succeed when a criteria is met and fail if and when they time out. :param...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. <<<<<<< HEAD # Dist
ributed under the terms of the MIT License. ======= # Distributed under the terms of the MIT Li
cense. >>>>>>> a41cc069c865a5d0f35d0731f92c547467395b1b
''' Copyright 2021 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Fou...
------- ''' Copy Scenario Authors: JamesVaughan Latest revision by: JamesVaughan This tool will allow XTMF to be able to execute a vdf batch file into an EMME Databank. ''' #---VERSION HISTORY ''' 0.0.1 Created on 2021-01-20 by JamesVaughan ''' import inro.modeller as ...
ort traceback as _traceback _MODELLER = _m.Modeller() #Instantiate Modeller once. process = _m.Modeller().tool('inro.emme.data.function.function_transaction') class CopyScenario(_m.Tool()): version = '0.0.1' batch_file = _m.Attribute(str) scenario_number = _m.Attribute(int) def page(self): ...
_section in self.data.config[base].sections.now: sect_data = self.data.config[base].sections.now[ns_section] if sect_data.metadata["full_ns"] == namespace: return [ns_section] if ns_section in self.data.config[base].sections.latent: sect_data = self.data.confi...
th('file:')): format_keys.append(section) format_keys.sort(rose.config.sort_settings) return format_keys def get_icon_path_for_config(self, config_name): """Return the path to the config identifier icon or Non
e.""" icon_path = None for filename in self.data.config[config_name].meta_files: if filename.endswith('/images/icon.png'): icon_path = filename break return icon_path def get_macro_module_prefix(self, config_name): # Return a valid module-...
can be made to be very slow or very, very fast unlike `turtle` - Artist metaphor matches 'canvas' metaphor used in all graphics coding. - Artist draws lines individually instead of updating a single line with new coordinates so that the artists drawn `lines` can be checked to see if the line was drawn forward or...
urn self.good_job() else: return self.try_again()
def _close_enough(self): for y in range(400): for x in range(400): if self.solution[x][y] and not self.grid.ping(x,y): return False if self.grid[x][y] and not self.solution.ping(x,y): return False return True def ...
ort Errors from email import Charset SEMISPACE = '; ' # Regular expression used to split header parameters. BAW: this may be too # simple. It isn't strictly RFC 2045 (section 5.1) compliant, but it catches # most headers found in the wild. We may eventually need a full fledged # parser eventually. paramre = re.com...
y. if quote or tspecials.search(value): return '%s="%s"' % (param, Utils.quote(value)) else: return '%s=%s' % (param, value) else: return param def _parseparam(s): plist = [] while s[:1] == ';': s = s[1:] end = s.find(';') while end > ...
nd) % 2: end = s.find(';', end + 1) if end < 0: end = len(s) f = s[:end] if '=' in f: i = f.index('=') f = f[:i].strip().lower() + '=' + f[i+1:].strip() plist.append(f.strip()) s = s[end:] return plist def _unquotevalue(value)...
ample: ```python x = tf.placeholder(tf.float32, shape=(1024, 1024)) y = tf.matmul(x, x) with tf.Session() as sess: print(sess.run(y)) # ERROR: will fail because x was not fed. rand_array = np.random.rand(1024, 1024) print(sess.run(y, feed_dict={x: rand_array})) # Will succeed. ``` Args: ...
.convert_to_tensor(shape, name=n
ame) def sparse_placeholder(dtype, shape=None, name=None): """Inserts a placeholder for a sparse tensor that will be always fed. **Important**: This sparse tensor will produce an error if evaluated. Its value must be fed using the `feed_dict` optional argument to `Session.run()`, `Tensor.eval()`, or `Operati...
# -*- coding: utf-8 -*- import csv import os import gzip class File: def read(self, path, **kwargs): path = os.path.join(kwargs.get('root_path', ''), path) content_type = kwargs.get('content_type', 'txt') if content_type == 'txt': with file(path, 'r') as f: co...
single': writer.writerow(c['data']) elif c['type'] == 'multi': writer.writerows(c['data']) else: raise Except
ion('Row type must be specified') else: raise Exception('Bad file type') def exists(self, path): return os.path.exists(path)
until the confirmation key expires. @rtype: dict @return: A dictionary with the following keys: 'confirmation_key': <str> The code that is used to confirm the invitation 'match_user': <str> A username, if a user exists with that email-address 'match_user_...
@return: The name of the group that was disabled, nice for feedback. """ assert hasattr(group, 'entity_id') # Yan
k all the spreads for row in group.get_spread(): group.delete_spread(row["spread"]) # Remove all members for membership in group.search_members(group_id=group.entity_id, member_filter_expired=False): group.remove_member(memb...
# -*- coding: utf-8 -*- #above helps to declare what encoding we want to use in the module #note this is copied from the first json lab #above is used to set the encoding for this module, (unfortunately didn't help that much) #used for seeing our data in nicest string format possible import pprint #again idiom for ...
ounter.most_common()[:40]) #below is work we did to figure out the proper procedure to #count words using a dictionary #pprint.pprint(word_freq_dc) #for k, v in word_freq_dc.iteritems(): # tupled_word_freq.ap
pend((k, v)) #tupled_word_freq = zip(word_freq_dc.itervalues(), word_freq_dc.iterkeys()) #print(tupled_word_freq) #print sorted(tupled_word_freq) #help(word_freq_dc.get)
# shipHeavyMissileExpDmgPirateCruiser # # Used by: # Ship: Gnosis t
ype = "passive" def handler(fit, ship, context): fit.modules.filteredChargeBoost(lambda mod: mod.charge.requiresSkill("Heavy Missiles"), "explosiveDamage", sh
ip.getModifiedItemAttr("shipBonusRole7"))
import urllib.request import json from modules import userDatabase def get_what_pulse_url(param: str): return "http://api.whatpulse.org/user.php?user=" + str(param) + "&formatted=yes&format=json" # noinspection PyUnusedLocal def on_channel_pm(irc, user_mask, user, channel, message): command = message.split(...
private_message(channel, "\u000310WhatPulse:\u0003 {0}(ID:{1}) \u000310Country:\u0003 {2} " "\u000310Date Joined:\u0003 {3} \u000310LastPulse
d:\u0003 {4} " "\u000310Pulses:\u0003 {5} \u000310Keys:\u0003 {6} \u000310Clicks:\u0003 {7} " "\u000310AvKeysPerPulse:\u0003 {8} \u000310AvClicksPerPulse:\u0003 {9} " "\u000310AvKeyPerSecond:\u0003 {10} \u000310AvClicksPe...
from .dispatch import dispatch from .compatibility import basestring from blaze.expr.literal import BoundSymbol, data as bz_data @dispatch(object, (basestr
ing, list, tuple)) def create_index(t, column_name_or_names, name=None): """Create an index on a column. Parameters ---------- o : table-like index_name : str Th
e name of the index to create column_name_or_names : string, list, tuple A column name to index on, or a list or tuple for a composite index Examples -------- >>> # Using SQLite >>> from blaze import SQL >>> # create a table called 'tb', in memory >>> sql = SQL('sqlite:///:memory:',...
normal argument may be a quoted variable # e.g. strip now, not later if not value: return None else: value = value.strip("'\"") variables = ApacheParser.arg_var_interpreter.findall(value) for var in variables: # Strip off ${ and } ...
that are not loaded into the configuration.""" filters = [("ifmodule", self.modules), ("ifdefine", self.variables)] valid_matches = [] for match in matches: for filter_ in filters: if not self._pass_filter(match, filter_): break
else: valid_matches.append(match) return valid_matches def _pass_filter(self, match, filter_): """Determine if directive passes a filter. :param str match: Augeas path :param list filter: list of tuples of form [("lowercase if directive", set of relevan...
"""docker""" import http.client import json import socket __all__ = ['HTTPConnection', 'HTTPError', 'get'] class HTTPConnection(http.client.HTTPConnection): def __init__(self): http.client.HTTPConnection.__init__(self, 'localhost') def connect(self): sock = socket.socket(socket.AF_UNIX, so...
if resp.status != 200: raise HTTPError(resp.status, resp.reason) except Exception: conn.close() raise try: if async: return resp elif resp.headers.get('Content-Type') == 'application/json': return json.loa
ds(resp.read().decode('utf-8')) else: return resp.read() finally: if not async: conn.close()
import csv import os import sys import traceback import sqlite3 import fnmatch import decimal import datetime def valid_dt(dt): try: datetime.datetime.strptime(dt, "%m/%d/%Y") return True except: return False def adapt_decimal(d): return str(d) def convert_decimal(s): return decimal.Decimal(s) def db_cur(...
_marks def create_tbl(cur, tbl_name, header, arr = [], index_arr = []): cur.execute("""select count(*) FROM sqlite_master WHERE type='ta
ble' AND name = '%s' """ % (tbl_name)) tbl_exists = cur.fetchone() if tbl_exists[0] == 0: print "CREATE TABLE " + tbl_name + " (" + header.replace("id,", "id PRIMARY KEY,") + " );" cur.execute("CREATE TABLE " + tbl_name + " (" + header.replace("id,", "id PRIMARY KEY,") + " );") for index in index_arr: cur...
import datetime from django.db import models from django.utils.translation import ugettext, ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib import admin from schedule.models import Occurrence from django_attendance.conf import settings as attendance
_settings class EventAttendance(models.Model): ''' The attendance status of a user for a specific Occurrence of an event. ''' occurrence = models.OneToOneField(Occurrence) attendees = models.ManyToManyField(User) class Meta: verbose_name
= _('attendance') verbose_name_plural = _('attendances') def __unicode__(self): return "Attendance for %s-%s" % (self.occurrence.title, self.occurrence.start) def duration(self): """ Get the duration of this event in hours, taking the HO...
s_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 } counter = {} for k,v in EXTENSIONS.iteritems(): counter[k] = 0 dir_list = os.listdir(abs_path) files = [] for file in dir_list: # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY O...
form.errors['dir_name'] = forms.util.ErrorList([_('Error creating folder.')]) else: form = MakeDirForm(abs_path) return render_to_response('filebrowser/makedir.html', { 'form': form, 'query': query, 'title': _(u'New Folder'), 'settings_var': get_se...
bs(query, path), 'breadcrumbs_title': _(u'New Folder') }, context_instance=Context(request)) mkdir = staff_member_required(never_cache(mkdir)) def upload(request): """ Multipe File Upload. """ from django.http import parse_cookie # QUERY / PATH CHECK query = request.GET ...
""" Provides a more structured call to the nodejs bing """ import os import sys import argparse import subprocess def main(): parser = argparse.ArgumentParser(description="Use Bing's API services") parser.add_argument("query", nargs="*", help="Query string") parser.add_argument("-s", "--service", default...
%s %s\n" % (args.service, que
ry)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2015 Jérémy Bobbio <lunar@debian.org> # Copyright © 2015 Clemens Lang <cal@macports.org> # # diffoscope is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public L...
assert difference is None @pytest.fixture def obj_differences(obj1, obj2): return obj1.compare(obj2).details @skip_unless_tools_exist('otool', 'lipo') def t
est_obj_compare_non_existing(monkeypatch, obj1): monkeypatch.setattr(Config(), 'new_file', True) difference = obj1.compare(MissingFile('/nonexisting', obj1)) assert difference.source2 == '/nonexisting' assert len(difference.details) > 0 @skip_unless_tools_exist('otool', 'lipo') def test_diff(obj_differ...
dling of }{ -- each brace should be a separate token # A regular expression that matches postscript each different kind of postscript token pattern = '/?[a-zA-Z][a-zA-Z0-9_]*|[-]?[0-9]+|[}{]|%.*|[^\t\n ]' ######## Debug Functions def Debug(*s): print(s) sys.exit(1) return ######## Common Functions #### Is...
sh(x1 == x2) def _LT(): x1,x2 = PopTwoNumbers("_LT") return OperandPush(x1 < x2) def _GT(): x1,x2 = PopTwoNumbers("_GT") return OperandPush(x1 > x2) #### Boolean Operators def _AND(): x1,x2 = PopTwoBooleans("_AND") return OperandPush(x1 and x2) def _OR(): x1,x2 = PopTwoBooleans("_OR") ...
#### Sequencing Operators def _IF(): t == "" while t != "{": CommandLogic(OperandPush(ExecutionPop())) if OperandPop() == True: OperandPush(ExecutionPop()) ExecutionPop() return True def _IFELSE(): t == "" while t != "{": CommandLogic(OperandPush(ExecutionPop())...
# testStr = "Hello {name}, How long hav
e you bean?. I'm {my
Name}" # # testStr = testStr.format(name="Leo", myName="Serim") # # print(testStr) limit = None hello = str(limit, "") print(hello) # print( "4" in "3.5")
''' Reads scrambled Vigenere Cipher text from stdin and attempts to decrypt it. Written for Python 2.7. Copyright (C) 2014 leechy9 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 ...
encies = [ ('A', 0.08167), ('B', 0.01492), ('C', 0.02782), ('D', 0.04253), ('E', 0.12702), ('F', 0.02228), ('G',
0.02015), ('H', 0.06094), ('I', 0.06966), ('J', 0.00153), ('K', 0.00772), ('L', 0.04025), ('M', 0.02406), ('N', 0.06749), ('O', 0.07507), ('P', 0.01929), ('Q', 0.00095), ('R', 0.05987), ('S', 0.06327), ('T', 0.09056), ('U', 0.02758), ('V', 0.00978), ('W', 0.02360), ('X', 0.00150), ('...
""" Run example scripts. @author J. Chiang <jchiang@slac.stanford.edu> @author Paul F. Kunz <Paul_Kunz@slac.stanford.edu> """ #$Id: run_examples.py,v 1.13 2006/10/03 20:02:20 pfkeb Exp $ import sys from load_hippo import app, canvas prompt = 1 scripts = [] scripts.append('static_vs_dynamic') scripts.append('loglo...
else: sys.stderr.write("
Hit return to continue: ") x = sys.stdin.readline() return x print "Hit return to run named script" for name in scripts : prompt("Run %s: " % name) canvas.clear() command = 'import ' + name exec(command) print "All done. Enjoy!"
# -*- coding: ISO-8859-1 -*- """ Form Widget classes specific to the geoSite admin site. """ # A class that corresponds to an HTML form widget, # e.g. <input type="text"> or <textarea>. # This handles rendering of the widget as HTML. import json from django.template.loader import render_to_string from .conf import ...
'html': rendered_widgets[1], 'label': _("longitude"), }, 'config': { 'map_widget_height': settings.GEOPOSITIONMAP_MAP_WIDGET_HEIGHT, 'map_options': json.dumps(settings.GEOPOSITIONMAP_MAP_OPTIONS), 'marker_options': json...
s.GEOPOSITIONMAP_GOOGLE_VIEW), 'osm_view': json.dumps(settings.GEOPOSITIONMAP_OSM_VIEW), } }) class Media: #extend = False css = { 'all': ( 'geopositionmap/geopositionmap.css', '//cdn.leafletjs.com/leafl...
import elastic import nlp def lookup(description, synonyms=None): ''' Look up words by their definitions using the indexed terms and their synonyms.
''' description = nlp.correct(description) query = {'bool':{'must':get_definition_query(description)}} synonym_query = get_synonym_query(description, synonyms) if synonym_query: query['bool']['should'] = synonym_query quer
y['bool']['minimum_should_match'] = 0 query['bool']['boost'] = 1.2 return search(query) def search(query): print 'searching', query results = elastic.client.search(index=elastic.SEARCH_INDEX, body={'query':query}) return list(parse_results(results)) def get_definition_query(description, synony...
# Copyright (c) 2008 Mikeal Rogers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complian
ce 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 License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under th...
= {int(x[:5]): x for x in allfiles if x[-12:] == '_parsed.zlib'} toifiles = {int(x[:5]): x for x in allfiles if x[-19:] == '_shifts_parsed.zlib'} for team in teams: teamgames = {int(g) for g in basic_gamelog.query('Season == {0:d} & (Home == "{1:s}" | Away == "{1:s}")'.format( season, team)...
import js
on jsonpage = json.loads(page) completed_games = set() for gameday in jsonpage['dates']: for game in gameday['games']: if game['status']['abstractGameState'] == 'Final': completed_games.add(int(str(game['gamePk'])[-5:])) return completed_games def reparse_season(sea...
import bpy from ... base_types.node import AnimationNode class CombineVectorNode(bpy.types.Node, AnimationNode): bl_idname = "an_CombineVectorNode" bl_label = "Combine Vector" dynamicLabelType = "HIDDEN_ONLY" def create(self): self.newInput("Float", "X", "x") self.newInput("Float", "Y"...
label = "<X,
Y, Z>" for axis in "XYZ": if self.inputs[axis].isUnlinked: label = label.replace(axis, str(round(self.inputs[axis].value, 4))) return label def getExecutionCode(self): return "vector = Vector((x, y, z))"
def extractRumorsBlock(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if "Rumor's Block" in item['tags'] and 'chapter' in item['title'].l
ower(): return buildReleaseMessageWithType(item, "Rumor's Block", vol, chp, frag=frag, postfix=postfix, tl_type='oel')
return False
a helper class that provides housekeeping for LSTM cells. This may be useful for alternative LSTM and similar type of cells. The subclasses must implement `_call_cell` method and `num_units` property. """ @abc.abstractproperty def num_units(self): """Number of units in this cell (output dimension).""" ...
dims(initial_cell_state, [0]), cel
l_states]) mod_outputs = array_ops.concat( 0, [array_ops.expand_dims(initial_output, [0]), outputs]) final_cell_state = self._gather_states(mod_cell_states, sequence_length, batch_size) final_output = self._gather_states(mod_outputs, seq...
# -*- coding: utf-8 -
*- __doc__ = """\ Copyright Puzzlebox Productions, LLC (2010) This code is released under the GNU Pulic License (GPL) version 2 For more information please refer to http://www.gnu
.org/copyleft/gpl.html """
h(self._permission_owner_execute, 3, 4, 0, 1) # group checkboxes self._permission_group_read = gtk.CheckButton(_('Read')) self._permission_group_read.connect('toggled', self._update_octal, (1 << 2) * 10) table.attach(self._permission_group_read, 1, 2, 1, 2) self._permission_group_write = gtk.CheckButton(_('...
def _entry_activate(self, widget, data=None): """Handle octal mode change""" self._mode = int(widget.get_text(), 8) se
lf.update_mode() def _update_octal(self, widget, data=None): """Update octal entry box""" if self._permission_updating: return data = int(str(data), 8) self._mode += (-1, 1)[widget.get_active()] * data self.update_mode() def _update_checkboxes(self, widget=None, data=None): """Update checkboxes accord...
""" Contains tests for the collector base class. """ import pytest from tests.base import TestBase from statsite.metrics import Counter, KeyValue, Timer from statsite.collector import Collector class TestCollector(TestBase): def test_stores_aggregator(self): """ Tests that collectors will store ag...
assert 0 == len(results) def test_parse_metrics_keeps_good_metrics(self, aggregator): """ Tests that parse_metrics will keep the good metrics in the face of an error. """ message = "\n".join(["k::1|c", "j:2|nope", ...
ts = Collector(aggregator)._parse_metrics(message) assert [Timer("k", 2)] == results def test_parse_metrics_ignores_blank_lines(self, aggregator): """ Tests that parse_metrics will properly ignore blank lines. """ message = "\n".join(["", "k:2|ms"]) assert [Timer("k...
from django.contrib.auth import get_user_model User = get_user_model() from rest_framework import serializers from nodeshot.core.base.serializers import ModelValidationSerializer from nodeshot.community.profiles.serializers import ProfileRelationSerializer from .models import Comment, Vote, Rating, NodeRatingCount ...
delSerializer): class Meta: model = NodeRatingCount
fields = ('likes', 'dislikes', 'rating_count', 'rating_avg', 'comment_count')
__author__ = 'jbowman' # https://pythonspot.com/inner-classes/ class Human: def __init__(self, name):
self.name = name self.head = self.Head() def addhead(self): self.head2 = self.Head() class Head: def __init__(self): self.brain = self.Brain() def talk(self): return 'talking...' class Brain: def think(self): ...
execute only if run as a script directly joey = Human('Joey') print(joey.name) print(joey.head.talk()) print(joey.head.brain.think())
#!
/usr/bin/env python3.5 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.ar
gv)
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Custom filters for use in openshift_aws ''' from ansible import errors class FilterModule(object): ''' Custom ansible filters for use by openshift_aws role''' @staticmethod def scale_groups_serial(scale_group_info, upgrade=False): ''' This function w...
group_info = scale_group_info[0] if not isinstance(scale_group_info, dict):
raise errors.AnsibleFilterError("|filter plugin failed: Expected scale_group_info to be a dict") serial = None for tag in scale_group_info['tags']: if tag['key'] == 'deployment_serial': serial = int(tag['value']) if upgrade: serial += 1 ...
def get_attendance_records(file_path): attendance_file = open(file_path,'r') lines = attendance_file.readlines() attendance_file.close() header = lines[0] attendance_records = lines[1:] return attendance_records def convert_attendance_record_to_bools(sessions): sessions_bool = [] for...
_of_sessions_attended] += 1 # add record to session attendance dictionary for i in range(number_of_sessions): key = u'Session_'+ str(i) session_attendance[key] += sessions[i] return { u"by_attendee" : attendee_consistency, u"by_session" : session_attendance ...
temgetter IGNORE = { 'a', 'also', 'an', 'and', 'are', 'as', 'be', 'by', 'can', 'do', 'for', 'from', 'have', 'in', 'is', 'it', 'just', 'more', 'not', 'of', 'on', 'or', 'our', 'over', 'than', 'that', 'the', 'their', 'these', 'they', 'this', 'those', 'to', 'up', 'we', 'with' } def build_word_counter(file...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redis...
pose only (nice name) def get_name(self): return self.checkmodulation_name # Will look at if our check_period is ok, and give our check_command if we got it def get_ch
eck_command(self, t_to_go): if not self.check_period or self.check_period.is_time_valid(t_to_go): return self.check_command return None # Should have all properties, or a void check_period def is_correct(self): state = True cls = self.__class__ # Raised all...
# Copyright (C) 2012-2015, Alphan Ulusoy (alphan@bu.edu) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published b
y # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOU
T ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 F...
############################################################################## # Copyright (c) 2013-2018,
Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/s
pack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distrib...
# Copyright (C) 2013 Claudio "nex" Guarnieri (@botherder) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pro...
If not, see <http://www.gnu.org/licenses/>. from lib.cuckoo.common.abstracts import Signature class NetworkIRC(Signature): name = "net
work_irc" description = "Connects to an IRC server, possibly part of a botnet" severity = 3 categories = ["irc"] authors = ["nex"] minimum = "0.6" def run(self): if "irc" in self.results["network"]: if len(self.results["network"]["irc"]) > 0: return True ...
from . import utils import bpy from bpy.types import NodeTree, Node, NodeSocket # Implementation of custom nodes from Python # Derived from the NodeTree base type, similar to Menu, O
perator, Panel, etc. class GameGraph(NodeTree): # Description string '''A custom node tree type that will show up in the node editor header''' # Optional identifier string. If not explicitly defined, the python class name is used. bl_idname = 'GameGraphType'
# Label for nice name display bl_label = 'Game Graph' # Icon identifier bl_icon = 'NODETREE' # Custom socket types class ReadySocket(NodeSocket): def __new__(self): self.link_limit = 500 print("set link limit!") # Description string '''Custom node socket type''' ...
# __init__.py - collection of Luxembourgian numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Lic...
Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA # 02110-1301 USA """Collection of Luxembourgian numbers.""" # provide vat as an alias from stdnum.lu import tva as vat # noqa: F401
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
: self.path = path self._snapcraft_version = snapcraft_version if read_only: storage_class = _YAMLStorageReadOnly else: storage_clas
s = _YAMLStorage self.db = tinydb.TinyDB(str(path), storage=storage_class) logger.debug(f"Datastore init: {self.path} read_only={read_only}") # Force the datastore to be read by making a query, otherwise it is # only read on the first access. _ = self.db.tables() # No...
from django.db import models, DEFAULT_DB_ALIAS, connection from django.contrib.auth.models import User from django.conf import settings class Animal(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatF...
lass Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta:
ordering = ('id',) # Models to regression test #11428 class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward ...
from django.apps im
port AppConfig class AuditorConfig(AppConfig): name = 'audit
or'
def extractFeelinthedarkWordpressCom(item): ''' Parser for 'feelinthedark.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ...
ildReleaseMessageWithType(item,
name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
pons.warlock import BloodFury from SDWLE.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE from SDWLE.game_objects import Minion from SDWLE.tags.action import Summon, Kill, Damage, Discard, DestroyManaCrystal, Give, Equip, \ Remove, Heal, ReplaceHeroWithMinion from SDWLE.tags.base import Effect, Aura, Deat...
battlecry=Battlecry(Discard(), PlayerSelector())) def create_minion(self, p
layer): return Minion(4, 3) class SummoningPortal(MinionCard): def __init__(self): super().__init__("Summoning Portal", 4, CHARACTER_CLASS.WARLOCK, CARD_RARITY.COMMON) def create_minion(self, player): return Minion(0, 4, auras=[Aura(ManaChange(-2, 1, minimum=1), CardSelector(condition...
et_driver): failed_amphora = data_models.Amphora( id=uuidutils.generate_uuid(), role=constants.ROLE_MASTER, load_balancer_id=uuidutils.generate_uuid()) amp_flow = self.AmpFlow.get_failover_amphora_flow( failed_amphora, 2) self.assertIsInstance(amp_flow, flow...
test_get_post_map_lb_subflow(self, mock_get_net_driver): self.AmpFlow = amphora_flows.AmphoraFlows() amp_flow = self.AmpFlow._get_post_map_lb_subflow( 'SOMEPREFIX', constants.ROLE_MASTER) self.assertIsInstance(amp_flow, flow.Flow) self.assertIn(constants.FLAVOR, amp_flow...
amp_flow.requires) self.assertIn(constants.AMPHORA, amp_flow.provides) self.assertEqual(1, len(amp_flow.provides)) self.assertEqual(2, len(amp_flow.requires)) amp_flow = self.AmpFlow._get_post_map_lb_subflow( 'SOMEPREFIX', constants.ROLE_BACKUP) self.assertIsInstan...
* stride ) filt = filt.reshape( fh*fw ) newIm = numpy.zeros ( (height * stride), numpy.int ) code = """ int sum=0, pos; int ys=0, fys=0; for (int y=0; y < (height-(fh/2)); y++) { for (int x=0; x < (stride-(fw/2)); x++) { fys=sum=0; pos=ys+x; int th = ((height-y) < fh ) ? height-y :...
not self.checkLineCharacteristics(line): found = False #print "False" #print "True" if found: return endpoint return False def getValidPair ( self, l, r ): """Returns the first pair that is a barcode and is locat
ed at the top edges of a barcode. """ if not l or not r: return False l.sort( key=lambda x: x[1] ) r.sort( key=lambda x: x[1] ) if l[0][1] > r[0][1]: r.sort( key=lambda x: x[0], reverse=True ) res = self.getValidPoint( l[0], r ) if not res: return self.getValidP...
version = requests.__version__ major, minor, patch = [int(i) for i in version.split('.')] except Exception: # Probably some new-fangled version, so it should support verify pass else: if (major, minor, patch) < (0, 8, 8): sys.stderr.write( 'Warning...
mplementation doesn't verify server " "certificates. For improved security, we suggest installing " "requests.") return impl(*args, **kwargs) class HT
TPClient(object): def __init__(self, verify_ssl_certs=True): self._verify_ssl_certs = verify_ssl_certs def request(self, method, url, headers, post_data=None): raise NotImplementedError( 'HTTPClient subclasses must implement `request`') class RequestsClient(HTTPClient): name ...
from game.models import (Card, HEART, SPADE, CLUB, DIAMOND) def test_card_creation_without_name(): c = Card('heart', 5) assert c.name == 'heart' assert c.suit == 'heart' assert c.value == 5 def test_ca...
5 de
f test_card_spade_is_monster(): c = Card(SPADE, 5) assert c.is_monster() == True def test_card_club_is_monster(): c = Card(CLUB, 5) assert c.is_monster() == True def test_card_heart_is_not_monster(): c = Card(HEART, 5) assert c.is_monster() == False def test_card_diamond_is_not_monster(): ...
import numpy as np import os __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__)) ) + "/" class Dataset(): """ I want to create a similar object to that one existing in R: Dataframe """ def __init__(self, tra...
ls] def dummy() """ ToDo: It generates dummy data (an small subset to practice) """ pass class Examples(object): """ """ def __init__(self): """ """ pass def spam(self): """ Spam dataset """ training_ds =...
ata/spam_test.csv" return Dataset(training_ds, test_ds) def gene_expression(self): """ Gene expression dataset """ training_ds = __location__ + "data/gene_expression_training.csv" test_ds = __location__ + "data/gene_expression_test.csv" return Dataset(tra...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, getopt from datetime import datetime import math from gann import * def print_usage(): print """ classic Gann square: gann.py -o <output file name> -s <square size> Gann square based on date: gann.py -o <output file name> -a <base date...
elif opt in ("-b", "--b_date"): date_b = datetime.strptime(arg, date_format) elif opt in ("-m", "--mfile"): marks_file_name = arg elif opt in ("-r", "--rect"): rect = arg.split(';') try: left, bot, right, up = int(rect[0]), int(rect[1]), ...
print 'Failed to parse range!' if output_file_name == '': print_usage() sys.exit(2) if square_size != -1: # classic Gann square # Info print "Cells: %i" % (square_size * square_size) print "Square size: %i" % square_size print "Cell size: %i" % cell_...
from m1 import <error descr="Cannot find reference 'foo' in 'm1.pyi'">foo</error> from m1 import <error descr="Cannot find reference 'bar' in 'm1.pyi'">bar</error> from m1 im
port bar_imported from m1 import <error descr="Cannot find reference 'm2' in 'm1.pyi'">m2</error> from m1 import m2_imported print(foo, b
ar, bar_imported, m2, m2_imported)
#!/usr/bin/python2 # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # 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...
://www.gnu.org/licenses/>. # """FreeIPA platform FreeIPA is a server for identity, policy, and audit. """ from os.path import abspath, dirname import sys if __name__ == '__main__': # include ../ for ipasetup.py sys.path.append(dirname(dirname(abspath(__file__)))) from ipasetup import ipasetup # noqa: E4...
"ipaplatform.fedora", "ipaplatform.redhat", "ipaplatform.rhel" ], )
"""
This is helper module to profile the whole package in Python 3.7 profiling modules from command line will be supported and this module will no longer be needed """ import cProfile from .__main__ import main if __name__ == "__main__": cProfile.run("ma
in()", filename=".nemchmarker.cprofile")
_call(command): if command == "tor --version": return TOR_VERSION_OUTPUT.splitlines() else: raise ValueError("stem.util.system.call received an unexpected command: %s" % command) mocking.mock(stem.util.system.call, _mock_call) version = stem.version.get_system_tor_version() self...
ersion("0.2.2.36") >= requirements) self.assertTrue(Version("0.2.2.35") >= requirements) self.assertTrue(Version("0.2.1.38") >= requirements) self.assertFalse(Version("0.2.2.37") >= requirements) self.assertFalse(Version("0.2.3.36") >= requirements) requirements = stem.version._VersionRequirements(...
requirements.less_than(Version("0.2.2.36"), False) self.assertFalse(Version("0.2.2.37") >= requirements) self.assertFalse(Version("0.2.2.36") >= requirements) self.assertTrue(Version("0.2.2.35") >= requirements) def test_requirements_in_range(self): """ Checks a VersionRequirements with a sing...
#!/usr/bin/python3 import os # import logging import logger as logger_ WS_SERVER = 'ws://127.0.0.1:4055/ws' WS_TIMEOUT = 10 APP_DIR = os.path.dirname(__file__) # SQL_DIR = os.path.join(APP_
DIR, 'sql') logger = logger_.rotating_log(os.path.join( APP_DIR, 'kts_snmp.log'), 'kts_snmp_log') SNMP_IP = '192.168.222.179' SNMP_PORT
= 11162 ROUTER_URL = 'http://127.0.0.1/snmp'
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2013-2015 Pervasive Displays, Inc. # Copyright 2015, Syed Faisal Akber # # 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...
t.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) # Raspberry Pi hardware SPI config: DC = 23 RST = 24 SPI_PORT = 0 SPI_DEVICE = 0 WHITE = 1 BLACK = 0 # fonts are in different places on Rasp...
hare/fonts/truetype/freefont/FreeMono.ttf', # R.Pi '/usr/share/fonts/truetype/LiberationMono-Bold.ttf', # B.B '/usr/share/fonts/truetype/DejaVuSansMono-Bold.ttf' # B.B '/usr/share/fonts/TTF/FreeMonoBold.ttf', # Arch '/usr/share/fonts/TTF...
from django.shortcuts import render from django.conf import settings from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.views.decorators.csrf import csrf_exemp
t from fetcher import api import req
uests import json def index(request): return render(request, 'fetcher/index.html', {'result': api.status()}) def status(request): if request.method == 'GET' and request.META.get('CONTENT_TYPE') == 'application/json': return HttpResponse(json.dumps(api.status()), content_type='applica...
from django import temp
late register = template.Library() @register.filter() def is_assistant_or_coordinator(user, course): return course.is_assistant_
or_coordinator(user)
:{1}@{2}/command-api\ '.format(self._username, self._password, self._host)) except: print('There was an error trying to connect') # run CMD def _runCMD(self, cli): if self._connected: return self._switch.runCmds(1, cli) ...
ateDataDict('total_memory', self._version_info['memTotal']) def getSystemMac(self): self.getVersionInfo()
return self.createDataDict('system_mac', self._version_info['systemMacAddress']) def getDetails(self): # moved getVersionInfo() so this information gets refreshed as well # and to remove the redundancy of __init__ self.getVersionInfo() items = ( ...
""" Test objconfig.writer.Json """ from objconfig.writer import Json as JsonWriter from objconfig.reader import Json as JsonReader from objconfig.writer import AbstractWriter from objconfig.writer import WriterInterface import os def test_emptyinstantiation_json(): writer = JsonWriter() assert isinstance(wri...
r() conf = { "webhost" : "www.example.com", "database" : { "adapter" : "pdo_mysql", "params" : { "host" : "db.example.com", "username" : "dbuser", "password" : "secret", "
dbname" : "dbproduction" } } } writer.toFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "test.json"), conf) reader = JsonReader() compconf = reader.fromFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "test.json")) os.remove(os.path.join(os.path.dirname(o...
e def assert_quad(value_and_err, tabled_value, errTol=1.5e-8): value, err = value_and_err assert_allclose(value, tabled_value, atol=err, rtol=0) if errTol is not None: assert_array_less(err, errTol) class TestCtypesQuad(TestCase): @dec.skipif(_ctypes_missing, msg="Ctypes library could not be...
te(self): # 5) Sine weighted integral (infinite limits) def myfunc(x, a): return exp(-x * a) a = 4.0 ome = 3.0 assert_quad(quad(myfunc, 0, Inf, args=a, weight='sin', wvar=ome), ome / (a ** 2 + ome ** 2)) def test_cosine_weighted_infinite(
self): # 6) Cosine weighted integral (negative infinite limits) def myfunc(x, a): return exp(x * a) a = 2.5 ome = 2.3 assert_quad(quad(myfunc, -Inf, 0, args=a, weight='cos', wvar=ome), a / (a ** 2 + ome ** 2)) def test_algebraic_log_weight(se...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Base package for building Invenio application factories.""" import os from setup...
assifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Softwar...
ge :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Development Status :: 5 - Production/Stable', ], )
for x in undefined(): # ty<car
et>pe: int pass
""" MooseGesture Test application Al Sweigart al@coffeeghost.net http://coffeeghost.net/2011/05/09/moo
segesture-python-mouse-gestures-module Run the app and then draw by dragging the mouse. When you release the mouse button, the gesture you drew will be identified. This scri
pt requires the MooseGesture library, which you can download from here: http://coffeeghost.net/moosegesture.py And also requires Pygame: http://pygame.org Copyright 2011, BSD-license. """ import pygame, sys, os from pygame.locals import * sys.path.append(os.path.abspath('..')) import moosegesture # setup constants ...
""" Support for Neato Connected Vaccums switches. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.neato/ """ import logging import requests from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.helpers.entity import ToggleEntity fr...
, dev) add_devices(dev) class NeatoConnectedSwitch(ToggleEntity): """Neato Connected Switches.""" def __init__(self, hass, robot, switch_type): """Initialize the Neato Connected switches.""" self.type = switch_type self.robot = robot self.neato = hass.data[NEATO_LOGIN] ...
ate = self.robot.state except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as ex: _LOGGER.warning("Neato connection error: %s", ex) self._state = None self._schedule_state = None self._clean_state = None def update(self): ...
ntation build configuration file # # All configuration values have a default; values that are commented out # serve to show the default. # import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # document...
, a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%Y-%m-%d %H:%M' # If true, SmartyPants will be used to convert quotes and dashes to # typographically corre
ct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('kirppu', '0006_item_lost_property'), ] operations = [ migrations.AlterField( model...
name='text', field=models.CharField(help_text='Text item in UI', max_length=163
84), preserve_default=True, ), ]