prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
m import Client as RbprmClient from hpp.corbaserver import Client as BasicClient import hpp.gepetto.blender.exportmotion as em ## Corba clients to the various servers # class CorbaClient: """ Container for corba clients to various interfaces. """ def __init__ (self): self.basic = BasicClient ()...
ntPosition (jointName) ## Set static position of joint in its parent frame def setJointPosition (self, jointName, position): return self.client.basic.robot.setJointPosition (jointName, position) ## Get joint number degrees of freedom.
def getJointNumberDof (self, jointName): return self.client.basic.robot.getJointNumberDof (jointName) ## Get joint number config size. def getJointConfigSize (self, jointName): return self.client.basic.robot.getJointConfigSize (jointName) ## set bounds for the joint def setJointBounds ...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file e
xcept in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS
E-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 the Licen...
import unittest, random, sys, time sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_glm def write_syn_libsvm_dataset(csvPathname, rowCount, colCount, SEED): r1 = random.Random(SEED) dsf = open(csvPathname, "w+") for i in range(rowCount): rowDa...
print "glm end on ", csvPathname, 'took', time.time() - start, 'seconds' h2o_glm.si
mpleCheckGLM(self, glm, None, **kwargs) if __name__ == '__main__': h2o.unit_main()
an change_organizations mail status'), ('delete_mailstatus', 'Can delete mail status'), ('delete_mine_mailstatus', 'Can delete_mine mail status'), ('delete_organizations_mailstatus', 'Can delete_organizations mail status'), ('view_mailstatus', 'Can view mail status'), ('view_mine...
ects.filter( codename=permission_codename, content_type=content_type).exists(): Permission.objects.create( name=permission_name, codename=permission_codename, content_type=content_type) # Group permi...
group, _ = Group.objects.get_or_create(name=group_name) for model_name, permissions in models.items(): c
"""Testing chapter C creation""" self.chapter_c.update(self.plist) assert(type(self.chapter_c.content)==str), self.fail("Wrong type returned") #length calc header == 1 + 2 * length length_wait = 1 + 2 * len(self.plist) assert(len(self.chapter_c.content)==length_wait), se...
off)==127), \ self.fail("Wrong nb of note off recorded") def test_parse(self): """ Test parse chapter N with several notes""" #creating chapter self.chapter_n.update(self.plist_off) size, notes_parsed = self.chapter_n.parse(self.chapter_n.content) assert(len(no...
1000]] self.chapter_n.update(off_mont) size, notes_parsed = self.chapter_n.parse(self.chapter_n.content) def test_trim(self): self.chapter_n.update(self.plist_off) self.chapter_n.trim(6) #Test highest a
#!/usr/bin/env python from nose.tools import * from utilities import execution_path, run_all from utilities import side_by_side_image import os, mapnik import re def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.'))...
mage_filters,'sharpen') if 'shape' in mapnik.DatasourceCache.plugin_names(): def test_style_level_image_filter(): m = mapnik.Map(256, 256) mapnik.load_map(m, '../data/good_maps/style_level_image_filter.xml') m.zoom_all() successes = [] fails = [] for name in ("", "ag...
"edge-detect", "emboss", "gray", "invert", "sharpen", "sobel", "x-gradient", "y-gradient"): if name == "": filename = "none" else: filename = re.sub(r"[^-_a-z.0-9]", "", name) # find_style returns a copy of the style obj...
_ops.equal(a_rank, 1), [a_rank]) new_shape = [1] * n new_shape[i] = -1 dtype = a.dtype if dtype == dtypes.bool: output.append(array_ops.reshape(nonzero(a)[0], new_shape)) elif dtype.is_integer: output.append(array_ops.reshape(a, new_shape)) else: raise ValueError( 'O...
is < 0 else axis # Broadca
st shapes to match, ensure that the axis of interest is not # broadcast. arr_shape_original = array_ops.shape(arr) indices_shape_original = array_ops.shape(indices) arr_shape = array_ops.tensor_scatter_update(arr_shape_original, [[axis]], [1]) indices_shape = array_ops.tensor_scatter_update(indices_shape_orig...
CALONG' self.part2mod[self.modBpartIDs[i]]['channel']='LONG' self.part2mod[self.modBpartIDs[i]]['detector'] = 'NRCBLONG' elif i < 4: self.part2mo
d[self.modApartIDs[i]]['channel']='SHORT' self.part2mod[self.modApartIDs[i]]['detector']='NRCA'+str(i+1) self.part2mod[self.modBpartIDs[i]]['channel']='SHORT' self.part2mod[self.modBpartIDs[i]]['detector']='NRCB'+str(i+1) elif i > 4 and i < 9: ...
self.part2mod[self.modApartIDs[i]]['detector']='NRCA'+str(i+1-5) self.part2mod[self.modBpartIDs[i]]['channel']='SHORT' self.part2mod[self.modBpartIDs[i]]['detector']='NRCB'+str(i+1-5) elif i > 9 and i < 14: self.part2mod[self.modApartIDs[i]]['channel...
#!/usr/bin/python import glob,re,sys,math,pyfits import numpy as np import utils if len( sys.argv ) < 2: print '\nconvert basti SSP models to ez_gal fits format' print 'Run in directory with SED models for one metallicity' print 'Usage: convert_basti.py ez_gal.ascii\n' sys.exit(2) fileout = sys.argv[1] # try to...
s.append( int( m.group(1) )*1e6 ) # read in this file fp = open( file, 'r' ) for line in fp: parts = line.strip().split() ls.append( float( parts[0].strip() ) ) this.append( float( parts[1].strip() ) ) if i == 0: # if this is the first file, gen
erate the data table nls = len( ls ) seds = np.empty( (nls,nages) ) # convert to ergs/s/angstrom seds[:,i] = np.array( this )/4.3607e-33/1e10 # convert to numpy ages = np.array( ages ) ls = np.array( ls )*10.0 # make sure we are sorted in age sinds = ages.argsort() ages = ages[sinds] seds = seds[:,sinds] # sp...
from __future__ import print_function, absolute_import import numpy as np from numba import cuda, int32, float32 from numba.cuda.testing import unittest from numba.config import ENABLE_CUDASIM def useless_sync(ary): i = cuda.grid(1) cuda.syncthreads() ary[i] = i def simple_smem(ary): N = 100 sm ...
np.int32))) def test_coop_smem2d(self): compiled = cuda.jit("void(float32[:,::1])")(coop_smem2d) shape = 10, 20 ary = np.empty(shape, dtype=np.float32) compiled[1, shape](ary)
exp = np.empty_like(ary) for i in range(ary.shape[0]): for j in range(ary.shape[1]): exp[i, j] = (i + 1) / (j + 1) self.assertTrue(np.allclose(ary, exp)) def test_dyn_shared_memory(self): compiled = cuda.jit("void(float32[::1])")(dyn_shared_memory) ...
where(graph[connected_components_matrix] != 0) connected_components_matrix[node_to_add] = True if last_num_component >= connected_components_matrix.sum(): break return connected_components_matrix def _graph_is_connected(graph): """ Return whether the graph is connected (True) or No...
r instance the heat kernel of a euclidean distance matrix or a k-NN matrix). However care must taken
to always make the affinity matrix symmetric so that the eigen vector decomposition works as expected. Parameters ---------- adjacency : array-like or sparse matrix, shape: (n_samples, n_samples) The adjacency matrix of the graph to embed. n_components : integer, optional The dimen...
ePreferences ) if not oozebanePreferences.activateOozebane.value: return gcodeText skein = OozebaneSkein() skein.parseGcode( gcodeText, oozebanePreferences ) return skein.output.getvalue() def writeOutput( fileName = '' ): "Oozebane a gcode linear move file. Chain oozebane the gcode if it is not already oozeba...
the execute button, title of the dialog & preferences fileName. self.executeTitle = 'Oozebane' self.saveTitle = 'Save Preferences' preferences.setHelpPreferencesFileNameTitleWindowPosition(
self, 'skeinforge_tools.oozebane.html' ) def execute( self ): "Oozebane button has been clicked." fileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFilenames(), self.fileNameInput.wasCancelled ) for fileName in fileNames: writeOutput( fileName ) ...
__source__ = 'https://leetcode.com/problems/binary-tree-tilt/' # Time: O(n) # Space: O(n) # # Description: 563. Binary Tree Tilt # # Given a binary tree, return the tilt of the whole tree. # # The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values # and the sum of...
Hide Company Tags Indeed # Hide Tags Tree # Explanation # If we had each node's subtree sum, # our answer would look like this psuedocode: # for each node: ans += abs(node.left.subtreesum - node.right.subtreesum). # Let _sum(node) be the node's subtree sum. # We can find it by adding the subtree sum of the left child, ...
well do the ans += abs(left_sum - right_sum) part. import unittest # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 48ms 97.16% class Solution(object): def findTilt(self, root): """ ...
f._expr_() self.ast['rvalue'] = self.last_node self._cut() self._statement_() self.ast['body'] = self.last_node self.ast._define( ['rvalue', 'body'], [] ) @graken() def _casestatement_(self): with self._group(): with s...
e) self._closure(block1) self._token(';') @graken() def _autovar_(self):
self._name_() self.ast['name'] = self.last_node with self._optional(): self._token('[') self._constantexpr_() self.ast['maxidx'] = self.last_node self._token(']') self.ast._define( ['name', 'maxidx'], [] ) @...
# coding=utf-8 # -----------------------------
--------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost ...
rated. # -------------------------------------------------------------------------- from msrest.serialization import Model class VaultSecretGroup(Model): """Describes a set of certificates which are all in the same Key Vault. :param source_vault: The relative URL of the Key Vault containing all of the ...
""" WSGI config for mjuna project. It exposes the WSGI ca
llable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_M
ODULE", "mjuna.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
ntic, status, message = self.authenticator.is_authentic(request) self.assertFalse(authentic) self.assertEqual(401, status) self.assertEqual("", message) @patch.object(RemoteAuthenticator, "signature_valid") @patch.object(RemoteAuthenticator, "authentication_present") @patch.object(R...
or.authenticate(request) self.assertFalse(authentic) def test_authentication_type(self): """We self-describe""" self.assertEqual('REMOTE', self.authenticator.authenticator_type) class TestLocalAuthenticator(_TestAuthenticator, TestCase): def setUp(self): self.logger = mock.Moc...
logger=self.logger, mauth_api_version='v2', mauth_base_url='https://mauth-sandbox.imedidata.net') self.mws_time = "1479392498" self.app_uuid = 'b0603e5c-c344-488e...
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
oupMembersTable(UsersTable): class Meta: name = "group_members" verbose_name = _("Group Members") table_actions = (UserFilterAction, AddMembersLink, RemoveMembers) class AddMembers(tables.BatchAction): @staticmethod def action_present(count): return unge
ttext_lazy( u"Add User", u"Add Users", count ) @staticmethod def action_past(count): return ungettext_lazy( u"Added User", u"Added Users", count ) name = "addMember" icon = "plus" requires_input = True ...
from hypothesis import given, strategies as st import numpy as np from pysaliency.numba_utils import auc_for_one_positive from pysaliency.roc import general_roc def test_auc_for_one_positive(): asser
t auc_for_one_positive(1, [0, 2]) == 0.5 assert auc_for_one_positive(1, [1]) == 0.5 assert auc_for_one_positive(3, [0]) == 1.0 assert auc_for_one_positive(0, [3]) == 0.0 @given(st.lists(st.floats(allow_nan=False, allow_infinity=False), min_size=1), st.floats(allow_nan=False, allow_infinity=F
alse)) def test_simple_auc_hypothesis(negatives, positive): old_auc, _, _ = general_roc(np.array([positive]), np.array(negatives)) new_auc = auc_for_one_positive(positive, np.array(negatives)) np.testing.assert_allclose(old_auc, new_auc)
"License": "BSD", "License File": "/LICENSE", }, os.path.join('third_party', 'ots'): { "Name": "OTS (OpenType Sanitizer)", "URL": "http://code.google.com/p/ots/", "License": "BSD", }, os.path.join('third_party', 'pdfsqueeze'): { "Name": "pdfsqueeze", ...
k(os.path.join(root, path)): if files:
return True for vcs_metadata in VCS_METADATA_DIRS: if vcs_metadata in dirs: dirs.remove(vcs_metadata) return False def FilterDirsWithFiles(dirs_list, root): # If a directory contains no files, assume it's a DEPS directory for a # project not used by our curren...
ete on 31 Dec 2030. # Note that midnight GMT must be specified. # Be sure to quote your date strings - s3_lifecycle: name: mybucket transition_date: "2020-12-30T00:00:00.000Z" expiration_date: "2030-12-30T00:00:00.000Z" prefix: /logs/ status: enabled state: present # Disable the rule created ab...
on(msg=e.message) module.exit_json(changed=changed) def compare_rule(rule_a, rule_b): # Copy objects rule1 = copy.deepcopy(rule_a) rule2 = copy.deepcopy(rule_b) # Delete Rule from Rule try: del rule1.Rule except AttributeError: pass try: del rule2.Rule e...
1.transition rule2_expiration = rule2.expiration rule2_transition = rule2.transition # Delete the Expiration and Transition objects from the Rule objects del rule1.expiration del rule1.transition del rule2.expiration del rule2.transition # Compare if rule1_transition is None: ...
from setuptools
import setup setup( name="pystor", version="0.9.1", author="Ethronsoft", author_email='dev@ethronsoft.com', zip_safe=False, packages=["ethronsoft", "ethronsoft.pystor"], license=open("LICENSE.txt").read(), include_package_data=True, keywords="nosql document store serverless embedd...
verless document store", install_requires=[ 'enum34' ], setup_requires=[ 'pytest-runner' ], tests_require=[ 'pytest' ], entry_points={ 'console_scripts':[ "pystor = ethronsoft.pystor.__main__:main" ] } )
from . import views def register_in(router): router.register(r'openstack', views.OpenStackServiceViewSet, base_name='openstack') router.register(r'openstack-images', views.ImageViewSet, base_name='openstack-image') router.register(r'openstack-flavors', views.FlavorViewSet, base_name='openstack-flavor') ...
nts', views.TenantViewSet, base_name='openstack-tenant') router.register(r'openstack-service-project-link', views.OpenStackServiceProjectLinkViewSet, base_name='openstack-spl') router.register(r'openstack-security-groups', views.SecurityGroupViewSet, base_name='openstack-sgp') router.register(r'openstack-fl...
ase_name='openstack-fip') router.register(r'openstack-networks', views.NetworkViewSet, base_name='openstack-network') router.register(r'openstack-subnets', views.SubNetViewSet, base_name='openstack-subnet')
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-07 23:02 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', ...
rs', to=settings.AUTH_USER_MODEL)), ('gr
oups', models.ManyToManyField(blank=True, to='auth.Group')), ('users', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Advanced Filters', 'verbose_name': 'Advanced Filter', }, ...
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 the License. """Handlers that are not directly relat...
.app_context.get_slug(), location) return location def redirect(self, location): super(ApplicationHandler, self).redirect( self.canonicalize_url(location)) class BaseHandler(ApplicationHandler): """Base handler.""" def __init__(self, *args, **kwargs): super(BaseHandle...
) self.course = None def get_course(self): if not self.course: self.course = Course(self) return self.course def find_unit_by_id(self, unit_id): """Gets a unit with a specific id or fails with an exception.""" return self.get_course().find_unit_by_id(unit_id...
s = document.getElementById('no-transitions'), head = document.head || document.getElementsByTagName('head')[0]; head.removeChild(styles) """) def select_option_by_text(select_browser_query, option_text): """ Chooses an option within a select by text (helper method for Select's select...
e a callable that allows you to filter the event stream and select particular events of interest. A dictionary `event_filter` is also supported, which simply indicates that the event should match that provided expectation. `number_of_matches` lets us know when enough events have been found and ...
ion will not return until this many events have passed the filter. If not enough events are found before a timeout expires, then this will raise a `BrokenPromise` error. Note that this simply states that *at least* this many events have been emitted, so `number_of_matches` is simply a lower boun...
from rand
om import random from banti.linegraph import LineGraph class Weight(): def __init__(self, val): self.val = val def combine(self, other): return random() < .3, Weight(int(100*random())+(self.v
al+other.val)//2) def strength(self): return self.val def __repr__(self): return "{}".format(self.val) weights = [Weight(val) for val in range(10, 80, 10)] print(list(enumerate(weights))) lgraph = LineGraph(weights) print(lgraph.lchildren) print(lgraph) lgraph.process_tree() print(lgraph)...
__all__ = ['chatcommand', 'execute_chat_command', 'save_matchsettings', '_register_chat_command'] import functools import inspect from .events import eventhandler, send_event from .log import logger from .asyncio_loop import loop _registered_chat_commands = {} # dict of all registered chat commands async def exe...
d] = function else: logger.error('chatcommand ' + "'" + chat_command + "'" + ' already registered to ' + str(function)) return False def _unregister_chat_command(chat_command): if chat_command not in _registered_chat_commands: raise 'chat command not registered' else: del ...
if _register_chat_command(cmd, func) is False: return module = inspect.getmodule(func) logger.debug('chatcommand ' + "'" + cmd + "' connected to " + str(func) + ' in module ' + str(module)) @functools.wraps(func) def func_wrapper(*args, **kwargs): retur...
n instance from the base64 data. :param screenshot: The screenshot image. :param driver: The webdriver for the session. """ return EyesWebDriverScreenshot(driver, screenshot=screenshot) def __init__(self, driver, screenshot=None, screenshot64=None, is_viewport_scre...
this variable must NOT be non
e. :param screenshot64: The base64 representation of a png image. If screenshot is None, this variable must NOT be none. :param is_viewport_screenshot: Whether the screenshot object represents a viewport screenshot or a...
from functools import wraps from flask import Flask, make_response from werkzeug.contrib.atom import AtomFeed from datetime import datetime as dt from HTMLParser import HTMLParser from bs4 import BeautifulSoup import praw app = Flask(__name__) def get_api(): USER_AGENT = "reddit_wrapper for personalized rss see: ...
.add(article.title, func(article), content_type='html', author=article.author.name, url=article.url, updated=dt.fromtimestamp(int(article.created)), published=dt.fromtime...
int(article.created))) r = make_response(feed.get_response()) r.headers['Content-Type'] = "application/xml" return r return wrap_reddit return _reddit @app.route('/r/python.atom') @reddit("Python Subreddit", "python") def python(article): try: return HTMLPa...
_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: sf_account_manager short_description: Manage SolidFire accounts extends_documentation_fragment: - netapp.solidfi...
attributes=self.attributes) except Exception as e: s
elf.module.fail_json(msg='Error creating account %s: %s)' % (self.name, to_native(e)), exception=traceback.format_exc()) def delete_account(self): try: self.sfe.remove_account(account_id=self.account_id) except Exception as e: self.module.f...
import sys, os import tweepy # File with colon-separaten consumer/access token and secret consumer_file='twitter.consumer' access_file='twitter.access' def __load_auth(file): if os.path.exists(file): with open(file) as f: tokens = f.readline().replace('\n',''
).replace('\r','').split(':') if len(tokens) == 2: return tokens[0],tokens[1] else: raise ValueError("Expecting two colon-separated tokens") else: raise IOError("File not found: %s" % file) def twit(message, secret_dir='/secret'): # # Load the twitter consume...
s.path.join(secret_dir, consumer_file)) access_token, access_secret = __load_auth(os.path.join(secret_dir, access_file)) # # Perform OAuth authentication auth = tweepy.OAuthHandler(consumer_token, consumer_secret) auth.set_access_token(access_token, access_secret) # # Create the API and post...
# -*- coding: utf-8 -*- from __future__ import with_statement, print_function, absolute_import import os from requests_oauthlib import OAuth1Session def create_oauth_token(expiration=None, scope=None, key=None, secret=None, name=None, output=True): """ Script to obtain an OAuth token from Trello. Must ha...
s" % resource_owner_key) print(" - oauth_token_secret = %s" % resource_owner_secret) print("") # Step 2: Redirect to the provider. Since this is a CLI script we do not # redirect. In a web application you would redirect the user to the URL # below. print("Go to the following link in...
.format( authorize_url=authorize_url, oauth_token=resource_owner_key, expiration=expiration, scope=scope, name=name )) # After the user has granted access to you, the consumer, the provider will # redirect you to whatever URL you have told them to redirect to. You ca...
impo
rt renderer
from model.contact import Contact #создаем скрипт для генерации групп с последующим сохранением в файл import random import string import os.path import jsonpickle import getopt import sys try: #почитай про трай opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts","file"]) #опция n задает кол-во...
/contacts.json" for o, a in opts: #данная структура (в общем) позволяет управлять скриптом получения параметров групп с использованием раздела Edit Configuration #мы можем задать число групп и адрес положения файла результата if o == "-n": n = int(a) elif o == "-f
": f = a def random_string(prefix, maxlen): #генерация случайных данных для теста symbols = string.ascii_letters+string.digits + string.punctuation + " "*10 #данные которые применяем в случайной строке return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) #случайны...
#Made by Zachary C. on 9/21/16 last edited on 9/21/16 #CONSTANTS HOURS_DAY = 24 MINUTES_HOUR = 60 SECONDS_MINUTE = 60 #1. Greet the user and explain the program #2. Ask the
user to input the number of days #3. save the number of days days = float(input('This program converts days into hours, minutes, and seconds.\nPlease enter the number of days: ')) #4. Calculate the number of hours (days * hours in day) #5. Save the number of hours hours = days * HOURS_DAY #6. Calculate the number o...
nds in minute) #9. Save the number of seconds seconds = minutes * SECONDS_MINUTE #10. Display mumber of hours #11. Display number of minutes #12. Display number of seconds #13. Signoff print('In ' , days , ' days there are ' , int(format(hours , '.0f')) , ' hours or ' , int(format(minutes , '.0f')) , ' minutes or ' , ...
[parentNum]-4), int(data[parentNum])) getElem(data, searchNum(data, numpy.where(data==data[parentNum-3]), parentNum-3), hier,length,typeRC, int(data[parentNum]-3), int(data[parentNum])) elif data[parentNum-3] < length and data[parentNum-4] > length: #print (parentNum-4 , data[p...
ent) + ", " global dotcolLeafData dotcolLeafData.append(hier) #print(content) #print (leafData[rowLeafNum]) #print (colLeafData[colLeafNum])
removeNum = len(str(int(data[parentNum-3]))) + 1 hier = hier[:-removeNum] getElem(data, searchNum(data, numpy.where(data==data[parentNum-4]), parentNum-4), hier, length,typeRC, int(data[parentNum]-4), int(data[parentNum])) elif data[parentNum-3] > length and data[parentNum-4] < ...
r""" Description: Generates 2-D data maps from OpenFoam data saved by paraview as a CSV file. The data has to be saved as point data and the following fields are expected p, points:0->2, u:0->2. An aperture map is the second main input and is used to generate the interpolation coordinates as well as convert the flow ve...
| """ import argparse from argparse import RawDescriptionHelpFormatter as RawDesc import os import scip
y as sp from scipy.interpolate import griddata from apmapflow import _get_logger, set_main_logger_level, DataField # setting up logger set_main_logger_level('info') logger = _get_logger('apmapflow.scripts') # setting a few convenience globals avg_fact = None voxel_size = None base_name = None # creating arg parser ...
, 'verified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'vote': ('helios.datatypes.djangofield.LDObjectField', [], {}), 'vote_hash': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'vote_tinyhash': ('django.db.models.fields.Char...
['helios.Election']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'num_voters'
: ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'processing_finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'processing_started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'uploaded_at': ('django.db.models.fie...
#!/usr/bin/env python3 import sys from collections import defaultdict, deque from dataclasses import dataclass @dataclass class Nobe: children: object metadata: object argh = 0 def parse(data): global argh children = data.popleft() metadata = data.popleft() print(children, metadata) nobe...
obe.children.append(parse(data)) for x in range(metadata): argh += data.popleft() def main(args): data = [s.strip() for s in sys.stdin][0] d
ata = deque([int(x) for x in data.split(' ')]) print(data) print(len(data)) parse(data) print(argh) if __name__ == '__main__': sys.exit(main(sys.argv))
from chatterbot.adapters import Adapter from chatterbot.adapters.exceptions import AdapterNotImplementedError class IOAdapter(Adapter): """ This is an abstract class that
represents the interface that all input-output adapters should implement. """ def process_input(self): """ Re
turns data retrieved from the input source. """ raise AdapterNotImplementedError() def process_response(self, input_value): """ Takes an input value. Returns an output value. """ raise AdapterNotImplementedError()
: iv = fscale * sp.verts0[vi] newv[vi] = iv #vv = v / numpy.sqrt ( numpy.sum (v*v) ) #sv = vv * min ( rad, rad0 ) #newv[vi] = sphf * sv + (1.0-sphf) * iv sp.geometry = (newv,tris) for vi, v in enumerate ( smod.icosVe...
k %s, %d -> %d" % (dmap.name,start_rad,end_rad) ) self.MakeTNorms ( smod ) import time start = time.time() mm = dmap.full_matrix () #m1 = numpy.zeros_like ( mm ) # transform to index reference frame of ref_map f1 = dmap.data.ijk_to_xyz_tr
ansform from _contour import affine_transform_vertices as transform_vertices #f2 = xform_matrix ( mask_map.openState.xform ) #f3 = xform_matrix ( ref_map.openState.xform.inverse() ) #f4 = ref_map.data.xyz_to_ijk_transform #tf = multiply_matrices( f2, f1 ) #tf = multiply_...
len(updated_keys), len(removing_keys)), Style.RESET_ALL) # check verification failed items target_verified_items = None if len(reversed_matc...
u, c, t, e, m = synchronize(added_file, lc) # error i
f e: error_files[added_file] = e # normal elif u and write_file(added_file, c): added_cnt += 1 translated_files_lines[added_file] = t # verify failed for k in (m or {}): resul...
from collections import defaultdict from django.core.files.storage import DefaultStorage from django.core.management.base import BaseCommand, CommandError from candidates.csv_helpers import list_to_csv, memberships_dicts_for_csv from elections.models import Election def safely_write(output_filename, memberships_lis...
on.D
oesNotExist: message = "Couldn't find an election with slug {election_slug}" raise CommandError( message.format(election_slug=options["election"]) ) else: election_slug = None self.options = options self.output_pref...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
port_range': {'key': 'destinationPortRange', 'type': 'str'}, 'source_port_ranges': {'key': 'sourcePortRanges', 'type': '[str]'}, 'destination_port_ranges': {'key': 'destinationPortRanges', 'type': '[str]'}, 'source_addre
ss_prefix': {'key': 'sourceAddressPrefix', 'type': 'str'}, 'destination_address_prefix': {'key': 'destinationAddressPrefix', 'type': 'str'}, 'source_address_prefixes': {'key': 'sourceAddressPrefixes', 'type': '[str]'}, 'destination_address_prefixes': {'key': 'destinationAddressPrefixes', 'type':...
from flask import render_template, jsonify, url_for, abort, request, redirect, current_app from flask_wtf import Form from flask_user import current_user from silverflask import db from silverflask.models import User from silverflask.fields import GridField from silverflask.core import Controller from silverflask.cont...
url_prefix = CMSController.url_prefix + '/security' urls = { '/edit/<int:record_id>': 'edit_user', '/gridfield': 'get_users', '/': 'form' } allowed_actions = { 'edit_user' } @staticmethod def edit_user(record_id):
user_obj = db.session.query(User).get(record_id) if not user_obj: abort("Not found", 404) form_class = User.get_cms_form() form = form_class(request.form, obj=user_obj) if form.validate_on_submit(): form.populate_obj(user_obj) if form['new_passwo...
# Copyright (C) 2013, Walter Bender - Raul Gutierrez Segales # # 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 ...
ttach(service_grid, x, y, 1, 1) service_grid.show()
x += 1 if x == nx: x = 0 y += 1 alignment = Gtk.Alignment.new(0.5, 0, 0, 0) alignment.add(grid) grid.show() vbox = Gtk.VBox() vbox.pack_start(alignment, False, False, 0) alignment.show() scrolled = Gtk.ScrolledWindow...
confirm.") def must_exist(p): if not p.exists(): raise Exception("No such file: %s" % p.absolute()) def run_cmd(ctx, chdir, args): cmd = ' '.join(map(str, args)) print("Invoke {}".format(cmd)) with cd(chdir): ctx.run(cmd, pty=True) class DocTree(object): """ Base class for ...
dest args += ['--times'] # preserve timestamps # the problem with --times is that it fails when sev
eral # users can publish to the same server alternatively. # Only the owner of a file can change the mtime, other # users can't, even if they have write permission through # the group. args += ['--exclude', '.doctrees'] args += ['./'] # source ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2....
n import log as logging from cinder import wsgi #default request size is 112k max_request_body_size_opt = cfg.IntOpt('osapi_max_request_body_size', default=114688, help='Max size for body of a request') FLAGS = flags.FLAGS FLAGS.register_o...
stBodySizeLimiter(wsgi.Middleware): """Add a 'cinder.context' to WSGI environ.""" def __init__(self, *args, **kwargs): super(RequestBodySizeLimiter, self).__init__(*args, **kwargs) @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if (req.content_length > FLAGS.osap...
ort unittest class TestChanges(unittest.TestCase): PROJECT = "project" ZONE_NAME = "example.com" CHANGES_NAME = "changeset_id" @staticmethod def _get_target_class(): from google.cloud.dns.changes import Changes return Changes def _make_one(self, *args, **kw): return ...
ges.add_record_set( ResourceRecordSet( "test.example.com", "CNAME", 3600, ["www.example.com"], zone ) ) changes.delete_record_set( ResourceRecordSet( "test.example.com", "CNAME", 86400, ["other.example.com"], zone ) ...
e(client=client2) self.assertEqual(len(conn1._requested), 0) self.assertEqual(len(conn2._requested), 1) req = conn2._requested[0] self.assertEqual(req["method"], "POST") self.assertEqual(req["path"], "/%s" % PATH) SENT = {"additions": RESOURCE["additions"], "deletions": ...
from lumberjack.client.file_descriptor import FileDescriptorEndpoint from lumberjack.client.message_receiver import MessageReceiverFactory from lumberjack.client.message_forwarder import RetryingMessageForwarder from lumberjack.client.protocol import LumberjackProtocolFactory from lumberjack.util.object_pipe import Obj...
: factory = LumberjackProtocolFactory(forwarder) host, port = self.parse_server(server) options = self.create_ssl_context(host, ssl_certificate) connector = reactor.connectSSL(host, port, factory, options) return connector def parse_server(self, server_string): try: host, port = server_...
Context(ssl.PROTOCOL_TLSv1) #ssl_context.load_verify_locations(cafile = ssl_certificate) #ssl_context.verify_mode = ssl.CERT_REQUIRED certData = FilePath(ssl_certificate).getContent() authority = ssl.Certificate.loadPEM(certData) options = ssl.optionsForClientTLS(host, authority) return opt...
# Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
ryptographicAlgorithm): An enumeration specifying the algorithm for which the created key will be compliant. length(int): The length of the key to be created. This value must be compliant with the constraints of the provided algorithm. Returns: dict: A di...
the bytes format """ @abstractmethod def create_asymmetric_key_pair(self, algorithm, length): """ Create an asymmetric key pair. Args: algorithm(CryptographicAlgorithm): An enumeration specifying the algorithm for which the created keys will be comp...
rt ( get_installable_version, get_package_key_suffix, is_release, ) # A systemctl sub-command to start or restart a service. We use restart here # so that if it is already running it gets restart (possibly necessary to # respect updated configuration) and because restart will also start it if it # is not running....
nd # and HTTPS URLs are supported. # FLOC-1880 will ensure these are necessary and sufficient. sudo_from_args(["apt-get", "update"]), sudo_from_args([ "apt-get", "-y
", "install", "apt-transp
i = 0 while i <3: w
hile i <2: i
+= 1 i += 1
from math import pi, sin, cos, tan, sqrt from recordclass import recordclass import numpy as np import scipy.signal as signal import matplotlib.pyplot as plt from functools import reduce def db2a(db): return np.power(10, (db / 20.0)) def a2db(a): return 20 * np.log10(a) def series_coeffs(c): return redu...
c.append(series_coeffs(c)) # c.append(impedance_filter(c[-1])) wh = [signal.freqz(b, a) for b, a in c] plt.subplot(111) plt.title("Frequency response - reflection filte
r") for w, h in wh: plt.semilogx(w, 20 * np.log10(np.abs(h))) plt.ylabel('Amplitude Response (dB)') plt.xlabel('Frequency (rad/sample)') plt.grid() plt.show() if __name__ == "__main__": main()
################################################################################ # Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. # # Leap Motion proprietary and confidential. Not for distribution. # # Use subject to the terms of the Leap Motion SDK Agreement available at ...
swipe = SwipeGesture(gesture) print " Swipe id: %d, state: %s, position: %s, direction: %s, speed: %f" % ( gesture.id, self.state_names[gesture.state], swipe.position, swipe.direction, swipe.speed)
if gesture.type == Leap.Gesture.TYPE_KEY_TAP: keytap = KeyTapGesture(gesture) print " Key Tap id: %d, %s, position: %s, direction: %s" % ( gesture.id, self.state_names[gesture.state], keytap.position, keytap.direction ) ...
rs from packstack.installer import basedefs from packstack.installer import utils from packstack.modules.ospluginutils import getManifestTemplate, appendManifestFile from packstack.installer import exceptions from packstack.installer import output_messages # Controller object will # be initialized from main flow con...
: ("Ente
r a single or comma separated list of gluster volume " "shares to use with Cinder"), "OPTION_LIST" : ["^'([\d]{1,3}\.){3}[\d]{1,3}:/.*'"], "VALIDATORS" : [validators.validate_multi_regexp], "PROCESSORS" : [pro...
"""Testing the StringEnum class.""" import ezenum as ez
e def test_basic(): """Just check it out.""" rgb = eze.StringEnum(['Red', 'Green', 'Blue']) assert rgb.Red == 'Red' assert rgb.Green == 'Green' assert rgb.Blue == 'Blue' asser
t rgb[0] == 'Red' assert rgb[1] == 'Green' assert rgb[2] == 'Blue' assert len(rgb) == 3 assert repr(rgb) == "['Red', 'Green', 'Blue']"
SSL/TLS support and the pyOpenSSL module. A HIGH severity warning will be reported whenever known broken protocol versions are detected. It is worth noting that native support for TLS 1.2 is only available in more recent Python versions, specifically 2.7.9 and up, and 3.x A note on 'SSLv23': ...
bad_ssl_versions = get_bad_proto_versions(config) if context.call_function_name_qual == 'ssl.wrap_socket': if context.check_call_arg_value('ssl_version', bad_ssl_versions): return bandit.Issue( severity=bandit.HIGH, confidence=bandit.HIGH, text="s...
version'), ) elif context.call_function_name_qual == 'pyOpenSSL.SSL.Context': if context.check_call_arg_value('method', bad_ssl_versions): return bandit.Issue( severity=bandit.HIGH, confidence=bandit.HIGH, text="SSL.Context call with in...
nt_id), # ClientId size client_id) # ClientId @classmethod def _encode_message_set(cls, messages): """ Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed Format ====== Message...
: written to disk by the leader 0: immediate response -1: waits for all replicas to be in sync timeout: Maximum time (in ms) the server will wait for replica acks. This is _not_ a socket timeout Returns: ProduceRequest """
if acks not in (1, 0, -1): raise ValueError('ProduceRequest acks (%s) must be 1, 0, -1' % acks) return kafka.protocol.produce.ProduceRequest( required_acks=acks, timeout=timeout, topics=[( topic, [( partiti...
# # Copyright 2008 Google Inc. All Rights Reserved. """ The user module contains the objects and methods used to manage users in Autotest. The valid action is: list: lists user(s) The common options are: --ulist / -U: file containing a list of USERs See topic_common.py for a High Level Design and Algorithm. """ ...
else: keys = ['login']
super(user_list, self).output(results, keys)
# This file is part of the FragDev Website. # # the FragDev Website 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, o
r # (at your option) any later version. # # the FragDev Website is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MER
CHANTABILITY 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 the FragDev Website. If not, see <http://www.gnu.org/licenses/>. # Placeholder urlpatterns list, in case views are added app_na...
from Graph import Graph def mkTestGraph4(): return Graph( ['a','b','c','d'], [ ('a','b'), ('b','c'), ('c','a'), ('a','d') ] ) def mkTestGraph4b(): ## isomorphic with 4 return Graph( ['a','c','b','d'], ...
('a','d'), ('a','c'), ('c','e') ] ) def mkPetersenGraph(): return Graph(
10, [ (0,1),(1,2),(2,3),(3,4),(4,0), # outer polygon (5,6),(6,7),(7,8),(8,9),(9,5), # inner polygon (0,5),(1,8),(2,6),(3,9),(4,7) ] # btwn polygons ) class PossibleEdges: ## this keeps a list of edges (x,y) such that the ith ## edge has x at 2*i position and y at 2*i+1 p...
if self.hist_arr[i] is not None: U.histogram(img, amin=self.hist_min[i], amax=self.hist_max[i], histArr=self.hist_arr[i]) self.hist[i].setHist(self.hist_arr[i], self.hist_min[i], self.hist_max[i]) else: resolution = 10000 a_h = U.histogram(img, reso...
v.setVisibility(i, visible) for v in self.viewers] #self.doc._wIdx = [w for w, bl in enumerate(self.hist_show) if bl]
def OnZSliderBox(self, event=None): z = int(self.zSliderBox.GetValue()) if z >= self.doc.nz: z = self.doc.nz - 1 elif z < 0: z = 0 #while z < 0: #z = self.doc.nz + z self.set_zSlice(z) self.zSlider.SetValue(z) def ...
init__( module, action_args=action_args, desired_state=desired_state, zone=zone, permanent=permanent, immediate=immediate ) def get_enabled_immediate(self, rule, timeout): # Convert the rule string to standard format # before checking whether it is present rule = str(Ric...
nversion'] service = module.params['service'] rich_rule = module.params['rich_rule'] source = module.params['source'] zone = module.params['zone'] if module.params['port'] is not None: if '/' in module.params['port']: port, protocol = module.params['port'].strip().split('/') ...
il_json(msg='improper port format (missing protocol?)') else: port = None modification_count = 0 if icmp_block is not None: modification_count += 1 if icmp_block_inversion is not None: modification_count += 1 if service is not None: modification_count += 1 if por...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Flag.testing' db.add_column('waffle_flag', 'testing', self.gf('django.db.models.fields.Boo...
odels.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'defaul...
'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), ...
from datetime import datetime class ModelManager(object): def __init__(self, db, collection_name, has_stats=False, **kwargs): self.property_helper = None self.log_helper = None self.collection_name = collection_name self.db = db if 'logger' in kwargs: self.log_...
self.collection.__getattribute__(attr) if callable(orig_attr): def hooked(*args, **kwargs): result = orig_attr(*args, **kwargs) # prevent wrapped_class from becoming unwrapped if result == self.collection: return self ...
atetime'): if self.property_helper is None: return datetime.now() return self.property_helper.get_local_time(date_format) def log(self, msg, level='msg'): if self.log_helper is not None: self.log_helper.log(msg, level) def drop(self): self.collection.dro...
************************************* from latticeCommon import * import latticeBaseFeature import latticeExecuter import latticeCompoundExplorer as LCE from latticeBoundBox import getPrecisionBoundBox #needed for alignment import FreeCAD as App import Part from Draft import _ShapeString __title__="BoundingBox mod...
.Strings[i] self.foolObj.Shape = None self.draft_shape_string.execute(self.foolObj) shape = self.foolObj.Shape #calculate alignment point if obj.XAlign == 'None' and obj.YAlign == 'None': pass #need not ...
x else: if obj.AlignPrecisionBoundBox: bb = getPrecisionBoundBox(shape) else: bb = shape.BoundBox alignPnt = App.Vector() if obj.XAlign == 'Left': ...
# # Copyright 2009 Eigenlabs Ltd. http://www.eigenlabs.com # # This file is part of EigenD. # # EigenD 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. # # EigenD is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # ...
#! /usr/bin/python # -*- coding: utf-8 -*- import os import sys import logging import time import logging.config dir_cur = os.path.normpath(os.path.dirname(os.path.abspath(__file__)).split('bin')[0]) if dir_cur not in sys.path: sys.path.insert(0, dir_cur) log_dir = os.path.normpath(dir_cur + os.path.sep + 'logs' ...
print msg t.stop() elif 'p' == options.mode: if 0 != len(options.list.split(',')) % 2: msg = "In pare s
torm mode, number of alarms should be an EVEN number, otherwise there will be mismatch." logging.critical(msg) else: try: t = SnmpTrapUtils.SendTrapDurationMode(options, traps_map, list_engine[0], list_engine[1], ...
from cl.api import views from cl.audio import api_views as audio_views from cl.people_db import api_views as judge_views from cl.search import api_views as search_views from django.conf.urls import url, include from rest_framework.routers import DefaultRouter router = DefaultRouter() # Search & Audio router.register(...
r(r'retention-events', judge_views.RetentionEventViewSet) router.register(r'educations
', judge_views.EducationViewSet) router.register(r'schools', judge_views.SchoolViewSet) router.register(r'political-affiliations', judge_views.PoliticalAffiliationViewSet) router.register(r'sources', judge_views.SourceViewSet) router.register(r'aba-ratings', judge_views.ABARatingViewSet) urlpatterns =...
l, r = [int(x) for x in input().split()] if max(l,r) == 0:
print("Not a moose") elif l == r: print("Even {}".format(l+r)) else: print("Odd {
}".format(max(l,r)*2))
""" Created on April 14, 2017 @author Miguel Contreras M
orales """ import QueryTool import datetime import cherrypy as QueryServer
import os if __name__ == "__main__": """ This initializes CherryPy services + self - no input required """ print "Intializing!" portnum = 9100 # start the QeueryServer QueryServer.config.update({'server.socket_host' : '127.0.0.1', 'server....
fr
om bokeh.util.deprecate import deprecated_module deprecated_module('bokeh.properties', '0.11', 'use bokeh.co
re.properties instead') del deprecated_module from .core.properties import * # NOQA
# -*- coding: utf-8 -*- # Copyright 2017 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Indonesia - Bukti Potong P
Ph 4 Ayat 2 (F.1.1.33.09)", "version": "8.0.1.1.0", "category": "localization", "website": "https://opensynergy-indonesia.com/", "author": "OpenSynergy Indonesia", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "l10n_id_taxform_bukti_potong_pph_commo...
.xml", "views/bukti_potong_pph_f113309_out_views.xml", ], }
import gzip import os import numpy as np import cPickle as pickle import six from six.moves.urllib import request import scipy from scipy import io # from sklearn import decomposition ''' BVH ''' def load_bvh_data(file_path): frames = 0 frame_time = 0.0 with open(file_path, "rb") as f: lines...
gzip.open(labels, 'rb') as f_labels: f_images.read(16) f_labels.read(8) for i in six.moves.range(num): target[i] = ord(f_labels.read(1)) for j in six.moves.range(dim): data[i, j] = ord(f_images.read(1)) return data, target def download_mn...
ubyte.gz' train_labels = 'train-labels-idx1-ubyte.gz' test_images = 't10k-images-idx3-ubyte.gz' test_labels = 't10k-labels-idx1-ubyte.gz' num_train = 60000 num_test = 10000 print('Downloading {:s}...'.format(train_images)) request.urlretrieve('{:s}/{:s}'.format(parent, train_images), train_...
#!/usr/bin/env python
from livereload import Server, shell server = Server() style = ("style.scss", "style.css") script = ("typing-test.js", "typing-test-compiled.js") server.watch(style[0], shell(["sass", style[0]], output=style[1])) server.watch(script[0], shell(["babel", script[0]], output=script[1])) server.watch("index.html") ser...
host", open_url=True)
from collections import Counter def TFIDF(TF, complaints, term): if TF >= 1: n = len(complaints) x = sum([1 for complaint in complaints if term in complaint['bo
dy']]) return log(TF + 1) * log(n / x)
else: return 0 def DF(vocab, complaints): term_DF = dict() for term in vocab: term_DF[term] = sum([1 for complaint in complaints if term in complaint['body']]) threshold = 3 features = [term for term in term_DF.keys() if term_DF[term] > threshold] return features def chi_square(...
# Copyright 2016-17 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class StockChangeStandardPrice(models.TransientModel): _inherit = "stock.change.standard.price" @api.model ...
res = super(StockChangeStandardPrice, self).default_get(fields) product_or_template = self.env[self._context['active_model']].browse( self._context['active_id']) if 'counterpart_account_id' in fields: # We can only use one account here, so we use the decrease # acco...
we'll use the # increase/decrease accounts defined in the product category. res['counterpart_account_id'] = product_or_template.categ_id. \ property_inventory_revaluation_decrease_account_categ.id return res
import unittest from pyml.nearest_neighbours import KNNClassifier, KNNRegressor from pyml.datasets import gaussian, regression from pyml.preprocessing import train_test_split class TestKNNClassifier(unittest.TestCase): @classmethod def setUpClass(cls): cls.datapoints, cls.labels = gaussian(n=100, d=2...
cls.regressor = KNNRegressor(n=5) cls.regressor.train(X=cls.X_train, y=cls.y_train) def test_train(self): self.assertEqual(self.regressor.X, self.X_train)
def test_predict(self): predictions = self.regressor.predict(X=self.X_test) self.assertEqual(predictions[:5], [3.1161666191379163, 4.933573052500679, 6.611283497257544, 9.185848057766739, 3.110023909806445]) def test_score_mse(self): mse = se...
""" Default urlconf for noisefilter """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib
import admin from django.contrib.sitemaps.views import index, sitemap from django.views.generic.base import TemplateView from django.views.defaults import (permission_denied, page_not_found, server_error) sitemaps = { # Fill me with sitemaps }...
# Admin url(r'^admin/', include(admin.site.urls)), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Sitemap url(r'^sitemap\.xml$', index, {'sitemaps': sitemaps}), url(r'^sitemap-(?P<section>.+)\.xml$', sitemap, {'sitemaps': sitemaps}), # robots.txt url(r'^robots\.txt$'...
#!/usr/bin/env python """ rpgtoolkit.py Generate a random webpage from a config file. Lots of gaming resources are simple variations on a theme. Here's a big list, choose a random thing from the list, and interpolate a bit using data from some other lists. Here's how this program works: given a config file, figure o...
elf.start = sel
f.config['meta']['start'] self.norepeats = True self.saved_tags = {} def load_config(self, config_file): """load the config file into the static config variable, but only once""" if not os.path.isfile(config_file): sys.exit("config file: %s is not a file" % config_file) if not self.config...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import si...
meters = parameters @property def controller(self): """Gets the controller of this V1IngressClassSpec. # noqa: E501 Controller refe
rs to the name of the controller that should handle this class. This allows for different \"flavors\" that are controlled by the same controller. For example, you may have different Parameters for the same implementing controller. This should be specified as a domain-prefixed path no more than 250 characters in length,...
# -*- coding: utf-8 -*- import datetime as dt from tradenews.database import ( Column, db, Model, SurrogatePK, ) class NewsCluster(SurrogatePK, Model): __ta
blename__ = 'newscluster' # id = Column(db.Integer(), nullable=False, primary_key=True) date = Column(db.Text(), nullable=False, defa
ult=dt.datetime.utcnow) title = Column(db.Text(), nullable=True) text = Column(db.Text(), nullable=True) cluster = Column(db.Integer(), nullable=True) def __init__(self): db.Model.__init__(self)
# Copyright (c) 2007, Enthought, Inc. # License: BSD Style. #--(Interfaces)----------------------------------------------------------------- """ Interfaces ========== In Traits 3.0, the ability to define, implement and use *interfaces* has been added to the package. Defining Interfaces ------------------- Interfa...
-----------------------------------------
# Define a class using an object that implements the 'IName' interface: class Apartment ( HasTraits ): renter = Instance( IName ) #--[Example*]-------------------------------------------------------------------- # Create an object implementing the 'IName' interface: william = Person( first_name = 'William', la...
e(0, 8, 2): elem_on_1_has_value, elem_on_1_value = sess.run( [elem_on_1_has_value_t, elem_on_1_t]) self.assertTrue(elem_on_1_has_value) self.assertEqual(i, elem_on_1_value) elem_on_2_has_value, elem_on_2_value = sess.run( [elem_on_2_has_value_t, elem_on_2_t]) ...
gumentError): self.evaluate(elem_on_1_t) with self.assertRaises(errors.InvalidArgumentError): self.evaluate(elem_
on_2_t) @combinations.generate(skip_v2_test_combinations()) def testUneven(self): dataset = dataset_ops.Dataset.range(10) multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator( dataset, ["/cpu:1", "/cpu:2"], max_buffer_size=4) config = config_pb2.ConfigProto(device_count={"CPU"...
# SPDX-License-Ident
ifier: MIT # Copyright (C) 2019-2020 Tobias Gruetzmacher # Copyright (C) 2019-2020 Daniel Ring from .common import _ParserScraper class ProjectFuture(_ParserScraper): imageSearch = '//td[@class="tamid"]/img' prevSearch = '//a[./img[@alt="Previous"]]' def __init__(self, name, comic, first, last=None): ...
__(name) else: super(ProjectFuture, self).__init__('ProjectFuture/' + name) self.url = 'http://www.projectfuturecomic.com/' + comic + '.php' self.stripUrl = self.url + '?strip=%s' self.firstStripUrl = self.stripUrl % first if last: self.url = self.stripU...
""" Management command to load language fixtures as tags """ from __future__ import unicode_literals import csv import os import re from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from orb.models import Category, Tag def has_data(input): """Identify...
( "--iso6392", action="store_true", dest="iso6
392", default=False, help="Flag for including all ISO 639.2 (only ISO 639.1 included by default)", ) def handle(self, *args, **options): try: user = User.objects.get(pk=options["user"]) except User.DoesNotExist: raise CommandError("No match u...
class Sol
ution: # @param {integer[]} nums # @param {integer} target # @return {integer[]} def searchRange(self, nums, target): res = [] l, r = 0, len(nums) - 1 while l <= r: m = (l + r) /2 if nums[m] < target: l = m + 1 else: ...
r = 0, len(nums) - 1 while l <= r: m = (l + r) /2 if nums[m] <= target: l = m + 1 else: r = m - 1 res.append(r) res = [-1, -1] if res[0] > res[1] else res return res
# Copyright 2019 kubeflow.org. # # 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,...
.KFSERVING_V1BETA1, kind=constants.KFSERVING_KIND, metadata=client.V1ObjectMeta( name=service_name, namespace=KFSERVING_TEST_NAMESPACE ), spec=V1beta1InferenceServiceSpec(predictor=predictor), ) KFServing.create(isvc) KFServi
ng.wait_isvc_ready(service_name, namespace=KFSERVING_TEST_NAMESPACE) res = predict(service_name, "./data/torchserve_input.json") assert(res.get("predictions")[0] == 2) KFServing.delete(service_name, KFSERVING_TEST_NAMESPACE)
#!/usr/bin/python # -*- coding: utf-8 -*- import os import time from creds import get_nova_obj from scit_config import * from scit_db import * #get authed nova obj nova = get_nova_obj() def create_nova_vm(logger, server_name, usr_dst): conf = getScitConfig() retry = int(conf["scit"]["scit_clean_retry"]) ...
#retry 10 t
imes print "clear vm failed, timeout.." if logger: logger.error("clear vm retry timeout.") return False instances = nova.servers.list() if instances: retry = retry + 1 time.sleep(10) else: print "all vm clea...
# coding: utf8 # jmdict.py # 2/14/2014 jich
i if __name__ == '__main__': import sys sys.path.append('..') def get(dic): """ @param dic str such as ipadic or unidic @return bool """ import rc return rc.runscript('getcabocha.py', (dic,)
) if __name__ == "__main__": get('unidic') # EOF
from django.db import models from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.utils.translation import ugettext_l
azy as _ from django.conf import settings from django.
utils import timezone from qbase.time import timesince from qbase import fields from qbase.models import get_contenttype from qevent.registry import check import functools from collections import defaultdict def stream(f): """ 把返回过滤条件的函数,变成queryset 并扩充了 offset, limit 条件 """ @functools.wraps(f) ...
#!/usr/bin/python3 """ Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... Example 1: Input: nums = [1, 5, 1, 1, 6, 4] Output: One possible answer
is [1, 4, 1, 5, 1, 6]. Example 2: Input: nums = [1, 3, 2, 2, 3, 1] Output: One possible answer is [2, 3, 1, 3, 1, 2]. Note: You may assume all input has valid answer. Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? """ from typing import List class Solution: def wiggleSort(self, num...
> None: """ Do not return anything, modify nums in-place instead. Median + 3-way partitioning """ n = len(nums) # mid = self.find_kth(nums, 0, n, (n - 1) // 2) # median = nums[mid] median = list(sorted(nums))[n//2] # three way pivot odd =...
self._verify_xblock_info_state(xblock_info, 'visibility_state', expected_state, path, should_equal) def _verify_explicit_staff_lock_state(self, xblock_info, expected_state, path=None, should_equal=True): """ Verify the explicit staff lock state of an item in the xblock_info. """ se...
ock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.ready) self._verify_visibility_state(xblock_info, VisibilityState.ready, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.ready, path=self.FIRS...
D_UNIT_PATH) def test_released_unit(self): """ Tests the visibility state of a published unit with release date in the past. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") ...
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
ame) # ----------------------------------------------------------------- @property def statistics(self): """ This function ... :return: """ return Table.read(self.statistics_path) # ----------------------------------------------------------------
-
#!/usr/bin/env python3 # ScatterBackup - A chaotic backup solution # Copyright (C) 2015 Ingo Ruhnke <grumbel@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 Foundation, either version 3 of the...
.assertEqual(11, fileinfo.size) self.assertEqual("6df4d50a41a5d20bc4faad8a6f09aa8f", fileinfo.blob.md5) self.assertEqual("bc9faaae1e35d52f3dea9651da12cd36627b8403", fileinfo.blob.sha1) # def test_json(self): # fileinfo = FileInfo
.from_file("tests/test.txt") # jstxt = fileinfo.json() # fileinfo2 = FileInfo.from_json(jstxt) # self.assertEqual(fileinfo, fileinfo2) if __name__ == '__main__': unittest.main() # EOF #
# -*- coding: utf-8 -*- from __future__ import unicode_literals import base from misc import GetPageInfo from models import PageIdentifier from category import GetSubcategoryInfos from revisions import GetCurrentContent, GetPageRevisionInfos from meta import GetSourceInfo def test_unicode_title(): get_beyonce ...
equestOperation(url) res = get_photo() text = res[0] assert len(text) == 16408 def test_get_html(): get_africa_html = base.GetPageHTM
L('Africa') res = get_africa_html() text = res[0] assert len(text) > 350000 def test_missing_revisions(): get_revs = GetPageRevisionInfos('Coffee_lololololol') rev_list = get_revs() ''' Should return 'missing' and negative pageid ''' assert len(rev_list) == 0 def test_get_meta():...
#!/usr/bin/env python ''' OWASP ZSC | ZCR Shellcoder ZeroDay Cyber Research Z3r0D4y.Com Ali Razmjoo shellcode template used : http://shell-storm.org/shellcode/files/shellcode-57.php ''' from core i
mport stack from core import template def run(dirname): command = 'mkdir %s' %(str(dirname)) return template.sys(stack.generate(com
mand.replace('[space]',' '),'%ecx','string'))
ath.expanduser(fsdbRoot) # replace ~ fsdbRoot = os.path.expandvars(fsdbRoot) # replace vars fsdbRoot = os.path.normpath(fsdbRoot) # replace /../ and so on fsdbRoot = os.path.realpath(fsdbRoot) # resolve links # check if path it's absolute if not os.path.isabs(fsd...
to the file with the given digest Args: digest -- digest of the file Returns: String rapresenting the absolute path of the file """ relPath = Fsdb.generateDirTreePath(digest, self._conf['deep']) return os.path.join(self.fsdbRoot, relPath) def _ma...
: path -- path to the leaf folder """ try: oldmask = os.umask(0) os.makedirs(path, self._conf['mode']) os.umask(oldmask) except OSError, e: if(e.errno == errno.EACCES): raise Exception("not sufficent permissions to write...