prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distribu
ted with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
ed 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. import mxnet as mx import numpy as np import json def check_metric(metric, *args...
rnalQueue from lightbus.utilities.casting import cast_to_signature from lightbus.utilities.deforming import deform_to_bus from lightbus.utilities.singledispatch import singledispatchmethod logger = logging.getLogger(__name__) class EventClient(BaseSubClient): def __init__(self, **kwargs): super().__init_...
" listener_name='example', on_error=lightbus.OnError.ACKNOWLEDGE_AND_LOG)" ), ) elif on_error == on_error.ACKNOWLEDGE_AND_LOG: try: await listener(event_message, **parameters) except asyncio.CancelledError: raise e...
cknowledge the successfully processed message await self.producer.send( AcknowledgeEve
def extractShibbsdenCom(item): ''' Parser for 'shibbsden.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('GOOD CHILD', 'Reborn as a Good Child', 'translated'), (...
'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp
, frag=frag, postfix=postfix, tl_type=tl_type) return False
from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("pro
jects", "doctype", "project") frappe.db.sql(""" update `tabProject` p set total_sales_amount = ifnull((select sum(base_grand_total) f
rom `tabSales Order` where project=p.name and docstatus=1), 0) """)
import logging from django.utils.html import format_html import django_tables2 as tables from django_tables2.rows import BoundPinnedRow, BoundRow logger = logging.getLogger(__name__) # A cheat to force BoundPinnedRows to use the same rendering as BoundRows # otherwise links don't work # BoundPinnedRow._get_and_ren...
attrs = {"class": "table table-bordered table-striped table-hover " "table-condensed"} # @classmethod # def set_header_color(cls, color): # """ # Sets all colum
n headers to have this background colour. # """ # for column in cls.base_columns.values(): # try: # column.attrs['th'].update( # {'style': f'background-color:{color};'}) # except KeyError: # column.attrs['th'] = {'style': f'back...
*********************************************************** QAD Quantum Aided Design plugin ok classe per gestire il map tool in ambito del comando array ------------------- begin : 2016-05-31 copyright : iiiii email ...
: bbbbb aaaaa ggggg ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribut...
, or * * (at your option) any later version. * * * ***************************************************************************/ """ from .. import qad_utils from ..qad_variables import QadVariabl...
from django.conf import settings from django.utils import timezone from rest_framework import authentication from rest_framework import exceptions import datetime import jwt from .models import User def generate_jwt(user): payload = { 'user': user.pk, 'exp': timezone.now() + datetime.timedelta...
en): return jwt.decode(token, settings.SECRET_KEY) class JWTAuthentication(authentication.BaseAuthentication): def authenticate(self, request): token = self._get_jwt_from_header(request) try: payload = decode_jwt(token) except jwt.ExpiredSignature: ...
ons.AuthenticationFailed(detail=detail) except jwt.DecodeError: detail = 'Error decoding token.' raise exceptions.AuthenticationFailed(detail=detail) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self._ge...
rson obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the S...
stserver and waits for reply. Returns: Reply to GET. On error return '' """ http_data = '' try: http_params = urllib.urlencode({"User" : self.username, "Message" : 'GET', "Parameter" : 'Empty'}) http_data = self.__requestreply(http_params) ...
= lines.pop() if message == "CLOSE": self.isConnected = False return 'ERROR' if message == 'ERR': # TODO: don't send ack. http_data = self.__requestreply(http_params) ...
# encoding: utf-8 # module samba.dcerpc.drsuapi # from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so # by generator 1.135 """ drsuapi DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class D
sReplicaObjMetaData2Ctr(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; re
stored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass array = property(lambda self: object(), lambda self, v: None, lambda self: None) # default count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default enumeratio...
'd' def x(): print j j = 0 def y():
for x in []: print
x
# Copyright 2019 The Sonnet Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
tLike ) -> Tuple[tf.Tensor, types.GradFn]: """Scales gradients for the backwards pass. Args: t: A Tensor. scale: The scale factor for the gradient on
the backwards pass. Returns: A Tensor same as input, with scaled backward gradient. """ def grad(dy: tf.Tensor) -> Tuple[tf.Tensor, None]: """Scaled gradient.""" return scale * dy, None return t, grad
## ## This copyrighted software is distributed under the GPL v2.0 license. ## See the LICENSE file for more details. ## ## Yeast workspace configuration file import numpy as np import WorkspaceModules.YeastApplicatorPlate import WorkspaceModules.YeastArena import WorkspaceModules.YeastArena3x3 YeastWorkspace = { 'b...
rkspaceModules.YeastApplicatorPlate.YeastApplicatorPlate(422.0, 247),
'yeastArena': WorkspaceModules.YeastArena.YeastArena(285, 139), 'yeastArena3x3': WorkspaceModules.YeastArena3x3.YeastArena3x3(124, 36) }
d running?") log.critical("Login failed - Could not create session. Is memcached running?") log.exception(exc) raise redirect_url = None # The AJAX method calling should know the default destination upon success if third_party_auth_successful: redirect_u...
est.user, username) else: context['message'] = _("Unexpected account status") return JsonResponse(context, status=400) user_account.changed_by = request.user user_account.standing_last_changed_at = datetime.datetime.now(UTC) user_account.save() return JsonRes...
all to change a profile setting: Right now, location""" # TODO (vshnayder): location is no longer used u_prof = UserProfile.objects.get(user=request.user) # request.user.profile_cache if 'location' in request.POST: u_prof.location = request.POST['location'] u_prof.save() return JsonRespons...
# Copyright Microsoft Corporation # # 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 writ...
ASIS, # 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. # # Requires Python 2.6+ and Openssl 1.0+ # import xml from tests
.tools import * from azurelinuxagent.common.protocol.wire import * from azurelinuxagent.common.osutil import get_osutil class TestRemoteAccess(AgentTestCase): def test_parse_remote_access(self): data_str = load_data('wire/remote_access_single_account.xml') remote_access = RemoteAccess(data_str) ...
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django import forms from lib.l10n_utils.dotlang import _, _lazy from bedrock.mozorg.forms import...
id email address'), }, widget=forms.TextInput(
attrs={ 'size': 20, 'class': 'fill-width' } ) ) superpriority = forms.BooleanField(widget=HoneyPotWidget, required=False) def clean_input_attachment(self): cleaned_data = super(FraudReportForm, self).clean() attachment = clean...
rProvider == 'tvtorrents': sickbeard.TVTORRENTS = curEnabled elif curProvider == 'torrentleech': sickbeard.TORRENTLEECH = curEnabled elif curProvider == 'btn': sickbeard.BTN = curEnabled elif curProvider == 'binnewz': si...
date_onlyfirst = 0 if use_xbmc == "on": use_xbmc = 1 else: use_xbmc = 0
if plex_update_library == "on": plex_update_library = 1 else: plex_update_library = 0 if plex_notify_onsnatch == "on": plex_n
# coding: utf-8 # Copyright (c) 2015 Fabian Barkhau <fabian.barkhau@gmail.com> # License: MIT (see LICENSE file) from kivy.uix.label import Label from gravur.utils import l
oad_widget @load_widget class LabelBox(Label): pas
s
# Copyright (c) 2015 Tanium Inc # # Generated from console.wsdl version 0.0.1 # # from .base import BaseType class SavedActionApproval(BaseType): _soap_tag = 'saved_action_approval' def __init__(self): BaseType.__i
nit__( self, simple_properties={'id': int, 'name': str, 'approved_flag': int}, complex_properties={'metadata': MetadataList}, list_properties={}, ) self.id = None self.name = None self.approve...
self.metadata = None from metadata_list import MetadataList
urn mapping else: return identifiers_ns.upper() def get_ns_id_from_identifiers(identifiers_ns, identifiers_id): """Return a namespace/ID pair compatible with INDRA from identifiers. Parameters ---------- identifiers_ns : str An identifiers.org standard namespace. identifiers_i...
) db_ns = get_ns_from_identifiers(identifiers_ns) if db_ns is None: return None, None db_id = identifiers_id if reg_entry['namespace_embedded']: if not identifiers_id.startswith(identifiers_ns.upper()): db_id = '%s:%s' % (identifiers_ns.upper(), identifiers_id) return db_...
iers.org namespace when possible. Example: this can be used to map 'UP' to 'uniprot'. Parameters ---------- db_name : str An INDRA namespace to map to identifiers.org Returns ------- str or None An identifiers.org namespace or None if not available. """ mapped_db_n...
if x
() and y(
) and z(): a() else: b()
def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args): try: entity = IN.entitier.load_single(entity_type, int(entity_id)) if not entity: return output = Object() db = IN.db connection = db.connection container_id = IN.commenter.get_container_id(entity)...
], }).execute() if cursor.rowcount >= 0: total = int(cursor.fetchone()[0]) more_id = '_'.join(('more-commens', entity_type, str(entity_id), str(parent_id))) if total > 0: cursor = db.select({ 'table' : 'entity.comment', 'columns' : ['id'], 'where' : [ ['container_id', c
ontainer_id], ['id', '<', int(last_id)], ['parent_id', parent_id], # add main level comments only ['status', 1], ], 'order' : {'created' : 'DESC'}, 'limit' : limit, }).execute() ids = [] last_id = 0 if cursor.rowcount >= 0: for row in cursor: ids.append(row['id']) ...
et_session from couchpotato.api import addApiView from couchpotato.core.event import addEvent from couchpotato.core.helpers.encoding import toUnicode from couchpotato.core.helpers.request import jsonified, getParams from couchpotato.core.helpers.variable import mergeDicts, md5, getExt from couchpotato.core.logger impor...
= [] for quality in qualities: q = mergeDicts(self.getQuality(quality.identifier), quality.to_dict()) temp.append(q) return temp def single(self, identifier = ''): db = get_session() quality_dict = {} quality = db.query(Quality).filter(or_(Quality....
*quality.to_dict()) return quality_dict def getQuality(self, identifier): for q in self.qualities: if identifier == q.get('identifier'): return q def saveSize(self): params = getParams() db = get_session() quality = db.query(Quality).filt...
#coding:utf-8 import numpy as np from chainer import Variable, FunctionSet import chainer.functions as F class LSTM(FunctionSet): def __init__(self,f_n_units, n_units): super(LSTM, self).__init__( l1_x = F.Linear(f_n_units, 4*n_units), l1_h = F.Linear(n_units, 4*n_units), ...
) # パラメータの値を-0.08~0.08の範囲で初期化 for param in self.
parameters: param[:] = np.random.uniform(-0.08, 0.08, param.shape) def forward_one_step(self, x_data, y_data, state, train=True,dropout_ratio=0.0): x ,t = Variable(x_data,volatile=not train),Variable(y_data,volatile=not train) h1_in = self.l1_x(F.dropout(x, ratio=dropout_ratio, tr...
e: description: - The selector when filtering on node labels required: false default: None aliases: [] images: description: - The image to base this registry on - ${component} will be replaced with --type required: 'openshift3/ose-${component}:${version}' default: None aliases:...
pod. The default is set for 5000. required: False default: [5000] aliases: [] replicas: description:
- The replication factor of the registry; commonly 2 when high availability is desired. required: False default: 1 aliases: [] selector: description: - Selector used to filter nodes on deployment. Used to run registries on a specific set of nodes. required: False default: None aliases:...
s'. """ self.scheduler.add_task(self._command_iter(command, files, refresh)) def _command_on_selected(self, command, refresh=1): files = self._get_selected_files() if len(files): self._command(command, files, refresh) def on_button_update_clicked(self, obj): ...
r.new_from_text_and_icon( gtk.STOCK_DIALOG_ERROR, primary, secondary) msgarea.add_button(_("Hi_de"), gtk.RESPONSE_CLOSE) msgarea.connect("response", lambda *args: s
elf.msgarea_mgr.clear()) msgarea.show_all() return False tmpdir = tempfile.mkdtemp("-meld") _temp_dirs.append(tmpdir) diffs = [] for fname in self.vc.get_patch_files(patch): destfile = os.path.join(tmpdir,fname) destdir = os.path.dirname(...
composition = "".join(decomposition) bidi_mirroring = line[9] == "Y" if general_category == "Ll": upcode = line[12] if upcode: upper_case = int(upcode, 16) _lower_to_upper_case[code] = upper_case if char_name.endswith("First>"): ...
ived_core_properties_txt(): """Load derived core properties from Blocks.txt.""" with open_unicode_data_file("DerivedCoreProperties.txt") as dcp_txt: dcp_ranges = _parse_code_ranges(dcp_txt.read()) for f
irst, last, property_name in dcp_ranges: for character_code in range(first, last + 1): try: _core_properties_data[property_name].add(character_code) except KeyError: _core_properties_data[property_name] = {character_code} def _load_property_value_aliases...
[-1., 1., 0.], [1., 1., 0.], [1., -1., 0.], [0., 0., 1.], [0., 0., -1.]]) self.mesh_elements = np.array([[0, 1, 4], [0...
10, 10), dtype='int16') self.image[:, :, :5] = 1 self.image_origin = np.array([-1., -1., -1.]) self.image_voxel_size = np.array([0.2, 0.2, 0.2]) # Create a data array self.data_array = np.array([math.tan(x) for x in np.linspace(-math.pi/4, mat...
bytes # --> use only bytes in dtypes self.dtype1 = np.dtype([('density', np.float32), ('melting_Pt', np.float32), ('Chemical_comp', 'S', 30)]) self.struct_array1 = np.array([(6.0, 1232, 'Cu2O'), ...
import json import logging import httplib import urllib2 from django.core.exceptions import ValidationError from django.conf import settings siaUrl=settings.SIA_URL import re import string def sanitize_search_term(term): # Replace all puncuation with spaces. allowed_punctuation = set(['&', '|', '"', "'"]) ...
ion) punctuation = "".join(all_punctuation - allowed_punctuation) term = re.sub(r"[{}]+".format(re.escape(punctuation)), " ", \ term) # Substitute all double quotes to single quotes. term = term.replace('"
', "'") term = re.sub(r"[']+", "'", term) # Create regex to find strings within quotes. quoted_strings_re = re.compile(r"('[^']*')") space_between_words_re = re.compile(r'([^ &|])[ ]+([^ &|])') spaces_surrounding_letter_re = re.compile(r'[ ]+([^ &|])[ ]+') multiple_operator_re = re.compile(r"[ ...
self.storage = ix.storage self.indexname = ix.indexname info = ix._read_toc() self.generation = info.generation + 1 self.schema = info.schema self.segments = info.segments self.docnum = self.docbase = docbase self._setup_doc_offsets() # Internals ...
docmap[docnum] = newdoc newdoc += 1 else: docmap = None newdoc += reader.doc_count_all() # Return the map and the new lowest unused document number return docmap, newdoc def _merge_per_doc(self, reader, docmap): schema = self.schema ...
# Skip deleted documents if docmap and docnum not in docmap: continue # Renumber around deletions if docmap: newdoc = docmap[docnum] # Get the stored fields d = reader.stored_fields(docnum) # Start a new document in...
import sublime import unittest import os import sys class TestImport(unittest.TestCase): mpath = None @classmethod def setUpClass(cls): basedir = os.path.dirname(__file__) mpath = os.path.normpath(os.path.join( basedir, "..", "st3_{}_{}".format(sublime.platform(), sublime.arc...
cess self.assertTrue("winpty" in sys.modules) proc = PtyProcess.spawn('cmd.exe') self.assertTrue(proc.isalive()) proc.terminate(True) @classmethod def tearDownClass(cls): if not cls.mpath: return mpath = cls.mpath if mpath in sys.path:
sys.path.remove(mpath) if "winpty" in sys.modules: del sys.modules["winpty"]
#!/usr/bin/env python # # Copyright 2011 Splunk, Inc. # # 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 ...
fic language governing permissions and limitations # under the License. """Example of a ur
llib2 based HTTP request handler.""" from pprint import pprint from StringIO import StringIO import sys import urllib2 import splunk.client as client import utils def request(url, message, **kwargs): method = message['method'].lower() data = message.get('body', "") if method == 'post' else None headers ...
#Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details """Tests for reportlab.lib.utils """ __version__=''' $Id$ ''' from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation setOutDir(__name__) import os, time, sys import reportlab import unittest from reportlab.lib impo...
ase): "Test import utilities" count = 0 def setUp(self): from reportlab.lib.utils import get_rl_tempdir
s = repr(int(time.time())) + repr(self.count) self.__class__.count += 1 self._tempdir = get_rl_tempdir('reportlab_test','tmp_%s' % s) if not os.path.isdir(self._tempdir): os.makedirs(self._tempdir,0o700) _testmodulename = os.path.join(self._tempdir,'test_module_%s.py' % s)...
# ############################################################################ # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business i...
on from selenium.webdriver.common.by import By from features.pages.common import CommonPageMixin from features.fields.fields import InputField, SelectField, ButtonField class SearchEntityPage(CommonPageMixin, pypom.Page): URL_TEMPLATE = '/entities/'
acronym = InputField(By.ID, 'id_acronym') title = InputField(By.ID, 'id_title') entity_type = SelectField(By.ID, "id_entity_type") search = ButtonField(By.ID, "bt_submit_entity_search") def find_acronym_in_table(self, row: int = 1): return self.find_element(By.ID, 'td_entity_%d' % row).text ...
# -*- coding: utf-8 -*- # # tm1640-rpi documentation build configuration file, created by # sphinx-quickstart on Fri Apr 12 19:52:17 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # ...
html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each them
e, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation...
# encoding: utf-8 import json import time from kubectl_data import * from kubectl_ports import * from kubectl_wrapper import * TMP_FILEPATH = '/tmp/' def create_tmp_json(data, service_path): with open(service_path, 'w') as out: json.dump(data, out, indent=2) def sub_start(service_name, data, kube_type): fil...
bel(service_name) pods_list = filter(lambda x: x != '', pods.split('\n')) if not pods_list: print 'No pods found' return elif len(pods_list) > 1: format_list = '\n'.join(pods_list) + '\n\nName: ' answer = raw_input('Multiple pods under this service, please choose one by selecting the name: \n' + f...
return logs(pod_name, f) def kubectl_describe(service_name): found_pods_and_exec_func(service_name, describe) def kubectl_connect(service_name): found_pods_and_exec_func(service_name, connect)
""" Configuration for bookmarks Django app """ from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from edx_django_utils.plugins import PluginSettings
, PluginURLs from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType class BookmarksConfig(AppConfig): """ Configuration class for bookmarks Django app """ name = 'openedx.core.djangoapps.bookmarks' verbose_name = _("Bookmarks") plugin_app
= { PluginURLs.CONFIG: { ProjectType.LMS: { PluginURLs.NAMESPACE: '', PluginURLs.REGEX: '^api/bookmarks/', PluginURLs.RELATIVE_PATH: 'urls', } }, PluginSettings.CONFIG: { ProjectType.LMS: { Settin...
import logging from pylons import config, request, response, session, tmpl_context as c from pylons.controllers.util import abort from fmod.lib.base import BaseController, render from fmod import model from sqlalchemy import desc log = logging.getLogger(__name__) from hashlib import md5 import time, datetime #usef...
in photos.getchildren(): image = photo.get('id') dt = int(photo.get('dateadded')) if ImageHistory.get(image=image, dt=dt): log.debug('found high water mark, quitting') break if ImageHistory.get_all(image=image): log.debug('found a re-add') p = Ping() p.image = image p.owner = photo.g...
() ih = ImageHistory() ih.image = image ih.dt = dt ih.save() ImageHistory.commit() return "successful"
from api imp
ort ServerError,NoAccessError,Simp
leTax
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'CVtek dev' __credits__ = [] __version__ = "1.0" __maintainer__ = "CVTek dev" __status__ = "Development" __model_name__ = 'sr_crianca.SRCrianca' import auth, base_models from orm import * from form import * class SRCrianca(Model, View): def...
self.data_registo = date_field(view_order = 9, name = 'Data Registo', size=40, args = 'required') self.nome_pai = string_field(view_order = 10, name = 'Nome do Pai', size = 60, onlist=False) self.n
ome_mae = string_field(view_order = 11, name = 'Nome do Mãe', size = 60) self.endereco_familia = text_field(view_order=12, name='Endereço Familia', size=70, args="rows=30", onlist=False, search=False) self.telefone = string_field(view_order = 13, name = 'Telefone', size = 40, onlist = True) s...
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University # Berlin, 14195 Berlin, Germany. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source ...
or stride in strides: for lag in lags: chunks = [] for _, _, Y in reader.iterator(stride, lag): chunks.append(Y) chunks = np.vstack(chunks) np.testing.assert_equal(chunks, self.d[lag::stride]) def test_lagged_stridden_a...
trides = [2, 3, 5, 7, 15] lags = [1, 3, 7, 10, 30] for stride in strides: for lag in lags: chunks = {i: [] for i in xrange(reader.number_of_trajectories())} for itraj, _, Y in reader.iterator(stride, lag): chunks[itraj].append(Y) ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-03 08:56 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): dependencies = [ migrations.swappable_depende...
ango.db.models.deletion.CASCADE, to='snapventure.Profile'), ), migrations.AddField( model_name='journey', name='inscriptio
ns', field=models.ManyToManyField(through='snapventure.Inscription', to='snapventure.Profile'), ), ]
# # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge...
import SCons.Scanner def only_dirs(nodes): is_Dir = lambda n: isinstance(n.disambiguate(), SCons.Node.FS.Dir) return list(filter(is_Dir, nodes)) def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry k...
ype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) skip_entry = {} skip_entry_list = [ '.', '..', '.sconsign', # Used by the na...
ED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWA...
if layer not in renpy.config.layers and layer not in renpy.config.top_layers: report("Uses layer '%s', which is not in config.layers.", layer) image_exists(name, expression, tag) for i in at_list: try_eval("the at list of a scene or show statment", i, "Perhaps you forgot to declare...
ehind = imspec(node.imspec) tag = tag or name[0] if layer not in renpy.config.layers and layer not in renpy.config.top_layers: report("Uses layer '%s', which is not in config.layers.", layer) if tag not in image_prefixes: report("The image tag '%s' is not the prefix of a declared ...
he License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed ...
e the License for the specific language governing permissions and # limitations under the License. """Create
/ interact with a batch of updates / deletes. Batches provide the ability to execute multiple operations in a single request to the Cloud Datastore API. See https://cloud.google.com/datastore/docs/concepts/entities#batch_operations """ from google.cloud.datastore import helpers from google.cloud.datastore_v1.proto i...
# NEVER DO THIS IN SQL! from Repository.Loader import Loader, LoaderException from Domain import Grade, Student, Discipline import sqlite3 class SQLLoader(Loader): def __init__(self, repo): self.repo = repo self.conn = sqlite3.connect(self.repo.getStoragePath() + ".sqlite") self.cursor = s...
zable['grades']) self.conn.commit() def load(self): try: self.repo._createNewRepo() for row in self.cursor.execute('SELECT * FROM students'):
self.repo.addStudent(Student.Student(row[0], row[1]), False) for row in self.cursor.execute('SELECT * FROM disciplines'): self.repo.addDiscipline(Discipline.Discipline(row[0], row[1]), False) for row in self.cursor.execute('SELECT * FROM grades'): self.repo.addGr...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015- Serge Noiraud # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public Lic
ense as published by # 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 WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See ...
e 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 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # https://en.wikipedia.org/wiki/Miscellaneous_Symbols # http://www.w3schools.com/chars...
import sys sys.path.insert(0, "../") import unittest from dip.typesystem import DNull, DBool, DInteger, DString, DList from dip.compiler import BytecodeCompiler from dip.interpreter import VirtualMachine from dip.namespace import Namespace class TestInterpreter(unittest.TestCase): def _execute_simple(...
Integer.new_int(5), # data1 DBool(), # data2 DInteger.new_int(999), # data3 ]) self.assertEqual(result.int_py(), 999) def test_lists(self): result = self._execute_simple(""" LIST_NEW 0 LIST_ADD 0 1 ...
append(data2) LEN 0 3 # 3 data3 = len(data0) EQ 3 5 6 # 4 data6 = (data3 == data5) LIST_REM 0 4 # 5 data0.remove(data4 (represents an index)) LEN 0 3 # 6 data3 = ...
rom being stored for new events.'), required=False ) # JavaScript options scrape_javascript = forms.BooleanField( label=_('Enable JavaScript source fetching'), help_text=_('Allow Sentry to scrape missing JavaScript source context when possible.'), required=False, ) ...
nd chosen team') def clean_slug(self): slug = self.
cleaned_data.get('slug') if not slug: return other = Project.objects.filter( slug=slug, organization=self.organization ).exclude(id=self.instance.id).first() if other is not None: raise forms.ValidationError( 'Another project (%s) is al...
# -*- coding: utf-8 -*- # Copyright 2022 Google 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.0 # # Unless required by applicable law or...
rative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-aiplatform # [START aiplatform_v1_generated_TensorboardService_ReadTensorboardBlobData_sync] from google.cloud import ...
(s) request = aiplatform_v1.ReadTensorboardBlobDataRequest( time_series="time_series_value", ) # Make the request stream = client.read_tensorboard_blob_data(request=request) # Handle the response for response in stream: print(response) # [END aiplatform_v1_generated_Tensorboar...
ude=None, define=None, flags=None, headers=None, compiler=None, warnings_are_errors=False, scan=True, msvc_lib=False, debug=True, linkflags=None ): if compiler is None: compiler, toolchain = _get_default_compiler() else: toolchain = _get_toolchain(compiler) if toolchain is None: ...
command.append('-D
NDEBUG') for identifier, value in define.items(): command.append('-D{}={}'.format(identifier, value)) if scan: depfile = core.temporary(core.random('.d')) command.extend(['-MD', '-MF', depfile]) else: depfile = None if _gnu_supports_colo...
from scrapy.contrib.exporter import CsvItemExporter from scrapy.conf import settings class SlybotCSVItemExporter(CsvItemEx
porter): def __init__(self, *args, **kwargs): kwargs['fields_to_export'] = settings.getlist('CSV_E
XPORT_FIELDS') or None super(SlybotCSVItemExporter, self).__init__(*args, **kwargs)
#!/usr/bin/en
v python2.7 import sys for line in open(sys.argv[1]): cut=line.split('\t') if len
(cut)<11: continue print ">"+cut[0] print cut[9] print "+" print cut[10]
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Stardust Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test spending coinbase transactions. # The coinbase transaction in block N can appear in block # N+1...
mework from test_framework.util import * # Create one-input, one-output, no-fee transaction: class MempoolSpendCoinbaseTest(StardustTestFramework): def __init__(self): super().__init__() self.num_nodes = 1 self.setup_clean_chain = False def setup_network(self): # Just need one...
self.is_network_split = False def run_test(self): chain_height = self.nodes[0].getblockcount() assert_equal(chain_height, 200) node0_address = self.nodes[0].getnewaddress() # Coinbase at height chain_height-100+1 ok in mempool, should # get mined. Coinbase at height ...
import unittest from unittest.mock import patch from app.main.service import GitHubUserService @patch("app.main.service.github") class TestGitHubUserService(unittest.TestCase): def setUp(self): self.test_user = "test" self.retrieved_repos_return = [ { "fork": False, ...
_repos.return_value = self.retrieved_repos_return github_client.retrieve_repo.side_effect = self.mock_retrieve_repo g
ithub_client.retrieve_pulls.side_effect = local_mock_retrieve_pulls actual_repos = GitHubUserService.retrieve_repos(self.test_user) for repo in actual_repos: if repo.is_fork: self.assertIsNone(repo.pull_requests, "The parent pulls are not in...
import _plot
ly_utils.basevalidators class BgcolorsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="bgcolorsrc", parent_name="histogram.marker.pattern", **kwargs ): super(BgcolorsrcValidator, self).__init__( plotly_name=plotly_name, parent_nam...
: utf-8 -*- # # sympa documentation build configuration file, created by # sphinx-quickstart on Mon Aug 25 18:11:49 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any ext...
custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = ...
from distutils.core import setup setup( # Application name: name="streaker", # Version number (initial): ver
sion="0.0.1", # Application author details: author="Aldi Alimucaj", author_email="aldi.alimucaj@gmail.com", # Packages packages=["streaker"], scripts=['bin/streaker'], # Include additional files into the package include_package_data=True, # Details url="http://pypi.python.or...
ption="GitHub streak manipulator", # long_description=open("README.txt").read(), # Dependent packages (distributions) install_requires=[ # "", ], )
# -*- coding: utf-8 -*- ############################################################################## # # document_csv module for OpenERP, Import structure in CSV # Copyright (C) 2011 SYLEAM (<http://www.syleam.fr/>) #
Christophe CHAUVET <christophe.chauvet@syleam.fr> # Copyright (C) 2011 Camptocamp (http://www.camptocamp.com) # Guewen Baconnier # # This file is a part of document_csv # # document_csv is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General P...
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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public Lice...
from sklearn.cluster import MiniBatchKMeans import numpy as np import json import os from texta.settings import MODELS_DIR class WordCluster(object): """ WordCluster object to cluster Word2Vec vectors using MiniBatchKMeans. : param embedding : Word2Vec object : param n_clusters, int, number of cluster...
ter_{}'.format(unique_id)) try: with open(file_path) as fh: data = json.loads(fh.read()) self.cluster_dict = data["cluster_dict"] self.word_to_cluster_dict = data["word_to_cluster_dict"] except:
return False
# -*- coding: utf-8 -*- from __future__ import with_statement import os import sys import zipfile from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError from pyload.utils import fs_encode class UnZip(Extractor): __name = "UnZip" __type = "extractor" __version = "1.12...
) as z: z.setpassword(password) return z.namelist() def check(self, password): pass def verify(self): with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z: badfile = z.testzip() if badfile: raise CRCError(b...
File(fs_encode(self.filename), 'r', allowZip64=True) as z: z.setpassword(password) badfile = z.testzip() if badfile: raise CRCError(badfile) else: z.extractall(self.out) except (zipfile.BadZipfile, zipfile...
# https://leetcode.com/problems/linked-lis
t-cycle-ii/ from ListNode import ListNode class Solution(object): def detectCycle(self, head): slow,fast = head,head while True: if fast == None or fast.next == None : return None slow = slow.next fast = fast.next.next if slow == fast : ...
ad.next fast = fast.next return head
from pycse.lisp im
port * def test_symbol(): assert Symbol('setf').lisp == 'setf' def test_quote(): assert Quote('setf').lisp == "'setf" def test_sharpquote(): assert SharpQuote('setf').lisp == "#'setf" def test_cons(): assert Cons('a', 3).lisp == '("a" . 3)' def test_Alist(): assert Alist(["a", 1, "b", 2]).lisp ...
def test_splice(): assert Splice([1, 3]).lisp == ',@(1 3)' def test_backquote(): assert Backquote([Symbol("a"), 1]).lisp == '`(a 1)' def test_comment(): assert Comment(Symbol("test")).lisp == '; test'
from django.conf.urls.defaults import * from tastypie.api import Api #from tastytools.api import Api from base.api import BaseResource from bcmon.api import PlayoutResource as BcmonPlayoutResource from bcmon.api import ChannelResource as BcmonChannelResource from alibrary.api import MediaResource, ReleaseResource, ...
ediaResource()) api.register(ReleaseResource()) api.register(ArtistResource()) api.register(LabelResource()) api.register(SimplePlaylistResource()) api.register(PlaylistResource()) api.register(PlaylistItemPlaylistResource()) # importer api.register(ImportResource()) api.
register(ImportFileResource()) # exporter api.register(ExportResource()) api.register(ExportItemResource()) # abcast api.register(AbcastBaseResource()) api.register(StationResource()) api.register(ChannelResource()) api.register(JingleResource()) api.register(JingleSetResource()) ### scheduler api.register(EmissionR...
import socket import sys import threading try: from Queue import Queue, Empty except: from queue import Queue, Empty from collections import OrderedDict from . import parseintset DEFAULT_THREAD_LIMIT = 200 CLOSED_STATUS = 'closed' OPEN_STATUS = 'open' if sys.version_info.major >= 3: unicode = str class...
t.socket(socket.AF_INET, socket.SOCK_STREAM) sock_instance.settimeout(self.timeout) try: # Connect to the host via TCP sock_instance.connect((host, port)) except socket.error: # Note that it is in the closed state self....
e that it is in the open state self.output_queue.put((host, port, OPEN_STATUS)) sock_instance.close() self.input_queue.task_done() self.output_queue.task_done() def stop_running(self): self.keep_running = False def port_scan(host, ports, thread_coun...
""" #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# This file is part of the Smart Developer Hub Project: http://www.smartdeveloperhub.org Center for Open Middleware http://www.centeropenmiddleware.com/ #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=...
" import StringIO import urlparse from rdflib import Graph, RDF from rdflib.namespace import OWL from rdflib.plugins.parsers.notation3 import BadSyntax import agora.fountain.vocab.schema as sch __author__ = 'Fernando Serena' class VocabularyException(Exception): pass class DuplicateVocabulary(VocabularyExcep...
yNotFound(VocabularyException): pass class UnknownVocabulary(VocabularyException): pass def __load_owl(owl): """ :param owl: :return: """ owl_g = Graph() for f in ['turtle', 'xml']: try: owl_g.parse(source=StringIO.StringIO(owl), format=f) break ...
medelta from openerp.osv import fields, orm from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.translate import _ from openerp.addons.connector.session import ConnectorSession from openerp.addons.connector.connector import ConnectorUnit from openerp.addons.connector.unit.mapper import (mapping,...
magento.website'].search( cr, uid, [('backend_id', '=', backend_id)], context=context) if not website_ids: self.synchronize_metadata(cr, uid, backend_id, context=context) return True def synchronize_metadata(self, cr, uid, ids, context=None): if not hasat...
bsite', 'magento.store', 'magento.storeview'): # import directly, do not delay because this # is a fast operation, a direct return is fine # and it is simpler to import them sequentially import_batch(sess...
""" OnionShare | https://onionshare.org/ Copyright (C) 2014 Micah Lee <micah@micahflee.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 License, or (at your option) any l...
tributed 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 of the GNU General Public License along with this program. If not, see
<http://www.gnu.org/licenses/>. """ from onionshare import web from nose import with_setup def test_generate_slug_length(): """generates a 26-character slug""" assert len(web.slug) == 26 def test_generate_slug_characters(): """generates a base32-encoded slug""" def is_b32(string): b32_alpha...
import sys from os.path import join, abspath, dirname # PATH vars here = lambda *x: join(abspath(dirname(__file__)), *x) PROJECT_ROOT = here("..") root = lambda *x: join(abspath(PROJECT_ROOT), *x) sys.path.insert(0, root('apps')) ADMINS = ( ('Maxime Lapointe', 'maxx@themaxx.ca'), ) MANAGERS = ADMINS SHELL_PLUS...
ition INSTALLED_APPS = ( 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'djang
o.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'www', ) PROJECT_APPS = () INSTALLED_APPS += PROJECT_APPS MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.com...
command to open :type cmd: str or list of str :param all: pipe all, not only selected message :type all: bool :param separately: call command once per message :type separately: bool :param background: do not suspend the interface :type background: bool :pa...
(['--all'], {'action': 'store_true', 'help': 'print all messages'}), (['--raw'], {'action': 'store_true', 'help': 'pass raw mail string'}), (['--separately'], {'action':
'store_true', 'help': 'call print command once for each message'}), (['--add_tags'], {'action': 'store_true', 'help': 'add \'Tags\' header to the message'}), ], ) class PrintCommand(PipeCommand): """print message(s)""" repeatable = True def __init__(self, ...
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
ons of the
Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIA...
# Copyright The IETF Trust 2008, All Rights Reserved from django.conf.urls.defaults import patterns, include from ietf.wginfo import views, edit, milestones from django.views.generic.simple import redirect_to urlpatterns = patterns('', (r'^$', views.wg_dir), (r'^summary.txt', redirect_to, { 'url':'/wg/1wg-...
(?P<acronym>[a-zA-Z0-9-]+)/history/$', views.history), (r'^(?P<acronym>[a-zA-Z0-9-]+)/edit/$', edit.edit, {'action': "edit"}, "wg_edit"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/conclude/$', edit.conclude, None, "wg_conclude"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/$', milestones.edit_milestones, {'milestone_...
estones.edit_milestones, {'milestone_set': "charter"}, "wg_edit_charter_milestones"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/charter/reset/$', milestones.reset_charter_milestones, None, "wg_reset_charter_milestones"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/ajax/searchdocs/$', milestones.ajax_search_docs, None, "wg...
"""Admin API urls.""" from rest_framework import routers from . import viewsets router = routers.SimpleRoute
r() router.register(r"domains", viewsets.DomainViewSet, basename="domain") router.register( r"domainaliases", viewsets.DomainAliasViewSet, basename="domain_alias") router.register(r"accounts", viewsets.AccountViewSet, basename="account") router.register(r"aliases", viewsets.AliasViewSet, basename="alias") router.re...
urls
= True self.pat = re.compile('dbg disconnected') self.req_handlers = { 'new_client': self.req_new_client, 'new_dbg': self.req_new_dbg, 'dbg_quit': self.req_dbg_quit, 'idb_n': self.req_idb_n, 'idb_list': self.req_idb_list, 'module':...
if not self.idb_clients: for s in self.srv_socks: s.close() sys.exit() # a new debugger client connects to the dispatcher def req_new_dbg(self, s, hash): msg = hash['msg'] if self.current_dbg: self.dbg_quit() # promote...
.current_dbg.client_sock = s self.idb_clients.remove(self.current_dbg) self.broadcast("new debugger client: %s" % msg) # store dbb's dialect if 'dialect' in hash: self.current_dialect = hash['dialect'] self.dbg_dialect() # inform client about debugger's dialect...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Partially based on AboutMethods in the Ruby Koans # from runner.koan import * def my_global_function(a, b): return a + b class AboutMethods(Koan): def test_calling_a_global_function(self): self.assertEqual(5, my_global_function(2, 3)) # NOTE: ...
exception[0]) try: my_global_function(1, 2, 3) except Exception as e: # Note,
watch out for parenthesis. They need slashes in front! self.assertMatch(r'my_global_function\(\) takes exactly 2 arguments \(3 given\)', e[0]) # ------------------------------------------------------------------ def pointless_method(self, a, b): sum = a + b def test_which_does_not_ret...
d a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_permissions short_descriptio...
file', 'vnic_profile', 'system', ] ), authz_name=dict(required=True, aliases=['domain']), object_id=dict(default=None), object_name=dict(default=None), user_name=dict(rdefault=None),
group_name=dict(default=None), namespace=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) if (
#!/usr/bin/env python # coding=utf-8 # code by kbdancer@92ez.com from threading import Thread from telnetlib import Telnet import requests import sqlite3 import queue import time import sys import os def ip2num(ip): ip = [int(x) for x in ip.split('.')] return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] ...
mac=?""" query_result = my_sqlite_db.query(query_info, [wifi_ssid, wifi_key, router_mac]) if len(query_result
) < 1: position_data = get_position_by_ip(host) country = position_data[0] province = position_data[1] city = position_data[2] isp = position_data[3] insert_info = """INSERT INTO scanlog (`host`,`ma...
# "<port-id>" case if isinstance(ports, int) or ports.isdigit():
id1 = getPortID(ports) if id1 >= 0: return (id1,) return id1 splits = ports.split("-") # "<port-id>-<port-id>" case if len(splits) == 2 and splits[0].isdigit() and splits[1].isdigit(): id1 = getPortID(splits[0]) id2 = getPortID(splits[1]) if id1 >= ...
(id2, id1) else: # ids are the same return (id1,) # everything else "<port-str>[-<port-str>]" matched = [ ] for i in range(len(splits), 0, -1): id1 = getPortID("-".join(splits[:i])) port2 = "-".join(splits[i:]) if len(port2) > 0: id2 = getPor...
import math def OUT_CIRC(t, b, c, d): t = float(t) b = float(b) c = float(c) d = float(d) t = t / d - 1 return c * math.sqrt(1 - t * t) + b def OUT_QUART(t, b, c, d): t = float(t) b = float(b) c = float(c) d = float(d) t = t / d - 1 return -c * (t * t * t * t - 1)...
+ .75) + b elif t < (2.5 / 2.75): t -= (2.25 / 2.75) return c * (7.5625 * t * t + .9375) + b else: t -= (2.625 / 2.75) return
c * (7.5625 * t * t + .984375) + b def INOUT_EXP(t, b, c, d): t = float(t) b = float(b) c = float(c) d = float(d) t1 = t / (d / 2) if t == 0: return b elif t == d: return b + c elif t1 < 1: return c / 2 * math.pow(2, 10 * (t1 - 1)) + b - c * 0.0005 else: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Microsoft Internet Explorer WebCache database.""" import unittest from plaso.lib import definitions from plaso.parsers.esedb_plugins import msie_webcache from tests.parsers.esedb_plugins import test_lib class MsieWebCacheESEDBPluginTest(test_lib.ESEDB...
ent_values) def testProcessOnDatabaseWithPartitionsExTable(self): """Tests the Process function on database with a PartitionsEx table.""" plugi
n = msie_webcache.MsieWebCacheESEDBPlugin() storage_writer = self._ParseESEDBFileWithPlugin( ['PartitionsEx-WebCacheV01.dat'], plugin) self.assertEqual(storage_writer.number_of_events, 4014) self.assertEqual(storage_writer.number_of_extraction_warnings, 3) self.assertEqual(storage_writer.number...
rifies that the restore is successful. Args: ds_fn: See `run_core_tests`. num_outputs: See `run_core_tests`. break_point: Break point. Optional. Defaults to num_outputs/2. sparse_tensors: See `run_core_tests`. verify_exhausted: See `gen_outputs`. Raises: AssertionError if a...
Saver checkpoint. Args: ds_fn:
0-argument function that returns the dataset. break_points: A list of integers. For each `break_point` in `break_points`, we produce outputs till `break_point` number of items have been produced and then checkpoint the state. The current graph and session are destroyed and a new graph and...
f
rom flappy.display3d.vertexbuffer3d import VertexBuffer3D, VertexBuffer3DFormat from flappy.display3d.indexbuffer3d import IndexBuffer3D from flappy.display3d.program3d import Program3D from flappy.display3d.texture import Texture from flappy.display3d.scene3d import Scene3D
import asyncio import logging import concurrent.futures class EchoServer(object): """Echo server class""" def __init__(self, host, port, loop=None): self._loop = loop or asyncio.get_event_loop() self._server = asyncio.start_server(self.handle_connection, host=host, port=port) def start(s...
, writer): peername = writer.get_extra_info('peername') logging.info('Accepted connection from {}'.format(peername)) while not reader.at_eof(): try: data = yield from asyncio.wait_for(reader.readline(), timeout=10.0) writer.write(data) exce...
': logging.basicConfig(level=logging.DEBUG) server = EchoServer('127.0.0.1', 8899) try: server.start() except KeyboardInterrupt: pass # Press Ctrl+C to stop finally: server.stop()
import numpy as np import numpy.testing as npt import AFQ.utils.parallel as para def power_it(num, n=2): # We define a function of the right form for parallelization return num ** n def test_parfor(): my_array = np.arange(100).reshape(10, 10) i, j = np.random.randint(0, 9, 2) my_list = list(my_...
npt.assert_equal(para.parfor(power_it, my_list, engine=engine, backend=backend, out_shape=my_array.shape)[i, j], pow...
the first item should be the item 0, 0: npt.assert_equal(para.parfor(power_it, my_list, engine=engine, backend=backend)[0], power_it(my_array[0, 0]))
#!/usr/bin/env python3.4 # dotslash for local from flask import Flask, render_template, request, redirect from werkzeug.contrib.fixers import ProxyFix from urllib.request import urlopen, Request from urllib.parse import urlparse from omxplayer import OMXPlayer from youtube_dl import YoutubeDL from youtube_dl.utils imp...
sed for best quality stream_url_types = ['rtmp', 'url'] # things that livestreamer can have :D for stream_type in stream_url_types: if hasattr(stream, stream_type): log('
url is livestream!') title = "%s (livestream)" % url play_omxplayer(getattr(stream, stream_type)) return '', 204 except (PluginError, RuntimeError) as e: # therefore url is not (supported) livestream pass # continue an...
from axiom.test.historic.stubloader import StubbedTest from xquotient.mail import MailTransferAgent from axiom.userbase import LoginSystem class MTAUpgraderTest(StubbedTest): def testMTA2to3(self): """ Make sure MailTransferAgent upgraded OK and that its "userbase" attribute refers to the s...
ginSystem))
at not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os sys.path.append(os.path.abspath('_themes')) sys.path.append(os.path.abspath('.')) # If extensions (or modules to doc...
ter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_cop...
t, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhe...
# force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../") import BellZhurkov.Python.TestExamples.TestUtil.Bell_Test_Data as ...
lZurkovFit(Forces,Folding,**opt) infUnfold = BellModel.BellZurkovFit(Forces,Unfolding,**opt) # get predictions along a (slightly l
arger) x range xMin=11e-12 xMax=15e-12 # how much should we interpolate? numPredict = (len(Forces)+1)*50 xRangePredict = np.linspace(xMin,xMax,numPredict) predictFold = infFold.Predict(xRangePredict) predictUnfold = infUnfold.Predict(xRangePredict) markerDict = dict(marker='o', ...
ort Course Surveys feature """ import logging from lxml import etree from collections import OrderedDict from django.db import models from student.models import User from django.core.exceptions import ValidationError from model_utils.models import TimeStampedModel from survey.exceptions import SurveyFormNameAlreadyE...
s an optional field): results = { '1': { 'field1': 'value1', 'field2': 'value2', }, '2': { 'field1': 'value3', 'field2': 'value4', 'field3': 'value5', } : : ...
in-memory dictionary. """ if user: answers = SurveyAnswer.objects.filter(form=form, user=user) else: answers = SurveyAnswer.objects.filter(form=form) results = OrderedDict() num_users = 0 for answer in answers: user_id = answer.user....
import sys try: import setuptools f
rom setuptools import setup except ImportError: setuptools = None from distutils.core import setup version = '0.0.1' kwargs = {} if setuptools is not None: kwargs['install_requires'] = ['tornado>=4.3'] if sys.version_info < (3, 4): kwargs['install_requires'].append('enum34') setup( name...
o_http2.test'], package_data={ 'tornado_http2': [ 'hpack_static_table.txt', 'hpack_huffman_data.txt', ], 'tornado_http2.test': [ 'test.crt', 'test.key', ], }, **kwargs)
import io import os import unittest from stango import Stango from stango.files import Files from . import StangoTestCase, make_suite, view_value, view_template dummy_view = view_value('') class GenerateTestCase(StangoTestCase): def setup(self): self.tmp = self.tempdir() self.manager = Stango() ...
lf.tmp), ['index.html']) with open(os.path.join(self.tmp, 'index.html'), 'rb') as fobj: self.eq(fobj.read(), b'\xde\xad\xbe\xef') def test_view_returns_a_bytearray_object(self): self.manager.files = Files( ('', view_value(bytearray(b'\xba\xdc\x0f\xfe'))), ) s...
th open(os.path.join(self.tmp, 'index.html'), 'rb') as fobj: self.eq(fobj.read(), b'\xba\xdc\x0f\xfe') def test_view_returns_a_filelike_object_with_str_contents(self): self.manager.files = Files( ('', view_value(io.StringIO('foobar'))), ) self.manager.generate(self.t...
""" This module contains transfor
mation functio
ns (clip->clip) One file for one fx. The file's name is the fx's name """
#! /usr/bin/env python import os import sys import glob version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) def substitute_file(name): subst = '' f = open(name) for l in f: if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'): l = '#define LIBTORRENT_VERSION_MAJO...
NY' in l and name.endswith('.hpp'): l = '#define LIBTORRENT_VERSION_TINY %d\n' % version[2] elif '#define LIBTORRENT_VERSION ' in l and name.endswith('.hpp'): l = '#define LIBTORRENT_VERSION "%d.%d.%d.%d"\n' %
(version[0], version[1], version[2], version[3]) elif 'AC_INIT([libtorrent-rasterbar]' in l and name.endswith('.ac'): l = 'AC_INIT([libtorrent-rasterbar],[%d.%d.%d],[arvid@libtorrent.org],\n' % (version[0], version[1], version[2]) elif 'set (VERSION ' in l and name.endswith('.txt'): l = 'set (VERSION "%d.%d.%...
print "Loading USBDriver : Logitech Cordless RumblePad 2" class USBDriver : def __init__(self): self.componentNextThrottleFrame = "Hat Switch" # Component for throttle frames browsing self.valueNextThrottleFrame = 0.5 self.componentPreviousThrottleFrame = "Hat Switch" self.v...
ction
s self.componentF1 = "Button 1" # Function button self.valueF1 = 1 self.valueF1Off = 0 self.componentF2 = "Button 2" # Function button self.valueF2 = 1 self.valueF2Off = 0 self.componentF3 = "Button 3" # Function button self.valueF3 = 1 ...
the command-line options for the shell command options = get_cmd_options(db_name) # Constructing the 'createlang' command. createlang_cmd = 'createlang %splpgsql' % options if verbosity >= 1: print createlang_cmd # Must have database super-user privileges to execute createlang -- it must # al...
se. The 'test' keyword may be set to retur
n the test spatial database name. """ if test: if settings.TEST_DATABASE_NAME: test_db_name = settings.TEST_DATABASE_NAME else: test_db_name = TEST_DATABASE_PREFIX + settings.DATABASE_NAME return test_db_name else: if not settings.DATABASE_NAME: ...
import logging import unittest from functools import reduce from ass_parser import StyleInfo, UsageData from font_loader import TTFFont, FontInfo, FontLoader, TTCFont, FontWeight from tests.common import get_file_in_test_directory class FontLoaderTests(unittest.TestCase): def test_returns_all_not_found_fonts(self)...
viarDreams_BoldItalic.ttf')) self.assertIs(font.get_info().italic, True) self.assertIs(font.get_info().bold, True) def test_parses_fonts_with_platform_id_2_strings(self): font = TTFFont(get_file_in_test_directory('VANTATHI.TTF')) self.assertIn('Vanta Thin', font.get_info().names) ...
self.assertIn('Susanna', font.get_info().names) def test_detects_bold_weight(self): font = TTFFont(get_file_in_test_directory('Caviar Dreams Bold.ttf')) self.assertEqual(font.get_info().weight, FontWeight.FW_BOLD) def test_detects_regular_weight(self): font = TTFFont(get_file_in_tes...
see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # import cStringIO import json import zipfile import os from M2Crypto import...
end(entitlement) except KeyError: print("ERROR: Cannot access required field in file '%s'" % entitlement_file) raise finally: entitlements.close() else: raise IncorrectEntitlementsFileFormatError(...
turn self.all_entitlements def get_satellite_certificate(self): return self.sat5_certificate def check_signature(self): if self.signature and self.data: certs = os.listdir(constants.CANDLEPIN_CA_CERT_DIR) # At least one certificate has to match for cert_name...
# ed25519.py - Optimized version of the reference implementation of Ed25519 # # Written in 2011? by Daniel J. Bernstein <djb@cr.yp.to> # 2013 by Donald Stufft <donald@stufft.io> # 2013 by Alex Gaynor <alex.gaynor@gmail.com> # 2013 by Greg Price <price@mit.edu> # # To the extent possible...
""" Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = H(sk) a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2)) A = scalarmult_B(a) return encodepoint(A) def Hint(m): h = H(m) return sum(...
bit(h, i) for i in range(2 * b)) def signature_unsafe(m, sk, pk): """ Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = H(sk) a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2)) r = Hint( ...
import os import json import numpy as np try: from numba.pycc import CC cc = CC('calculate_numba') except ImportError: # Will use these as regular Python functions if numba is not present. class CCSubstitute(object): # Make a cc.export that doesn't do anything def export(*args, **kwar...
: # Recode trajectory into deg, stable, imp. Capture trends that are at least # 95% significant. # # Remember that traj is coded as: # -3: 99% signif decline # -2: 95% signif decline # -1: 90% signif decline # 0: stable # 1: 90% signif increase # 2: 95% signif increase # ...
le x[(x > 1) & (x <= 3)] = 1 return(np.reshape(x, shp)) @cc.export('ldn_recode_state', 'i2[:,:](i2[:,:])') def ldn_recode_state(x): # Recode state into deg, stable, imp. Note the >= -10 is so no data # isn't coded as degradation. More than two changes in class is defined # as degradation in stat...
#!/usr/bin/env python # Copyright 2015 Google Inc. # # Licensed under the Apache License
, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS ...
s and # limitations under the License. """ Sample Google App Engine application that demonstrates how to send mail using Mailgun. For more information, see README.md. """ from urllib import urlencode import httplib2 import webapp2 # Your Mailgun Domain Name MAILGUN_DOMAIN_NAME = 'isrealconsulting.com' # Your Mailg...
""" Legalese -------- Copyright (c) 2015,
2016 Genome Research Ltd. Author: Colin Nolan <cn13@sanger.ac.uk> This file is part of Cookie Monster. Cookie Monster 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...
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, see <http://www.gnu.org/licenses/>. """ from unittest.mock import MagicMock from hgicommon.mixable import Priority from cookiemonster.cook...