prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
fr
om django.conf.urls import patterns, url from proxy import views urlpatterns = patterns('', url(r'^$', views.search, name='search'), url(r'^(?P<bucket_name>\S+?)(?P<key>/\S*)', views.get, name='get') )
from openerp import models,fields class OeMedicalMedicamentCategory(models.Model): _name = 'oemedical.medicament.category' childs = fields.One2many('oemedical.medicament.category', 'parent_id', string='Children', ) name = fields.Char(size=256, string='Name', required=True) ...
Parent', select=True) _constraints = [ (models.Model._check_recursion, 'Error ! You cannot create recursive \n' 'Category.
', ['parent_id']) ]
from django.shortcuts import render, HttpResponse import os # Create your views here. def status(request, task_id): from celery.result import AsyncResult task = AsyncResult(task_id); task.traceback_html = tracebackToHtml(task.traceback) return render(request, 'task/html/task_status.html', ...
'%s:%s' % (os.environ['VIP_FLOWER_HOST'], os.environ['VIP_FLOWER_PORT'])}) def tracebackToHtml(txt): html = str(txt).replace(' '*2, '&nbsp;'*4) html = html.split('\n') html = map(lambda x: '<div style="text-indent: -4em; padding-left: 4em">' + \ x ...
return None import pyrabbit #These values need to be unhardcoded... client = pyrabbit.api.Client('localhost:15672', 'guest', 'guest') names = [x['name'] for x in client.get_queues()] tasks = [x for x in map(safe_int, names) if x is not None] return render(request, 'task/html/task_list.html', ...
from django.test import TestCase from trix.trix_core import trix_markdown class TestTrixMarkdown(TestCase): def test_simple(self): self.assertEqual( trix_markdown.assignment_markdo
wn('# Hello world\n'), '<h1>Hello world</h1>') def test_nl2br(self): self.assertEqual( trix_markdown.assignment_markdown('He
llo\nworld'), '<p>Hello<br>\nworld</p>')
#!/usr/bin/env python2.7 #The MIT License (MIT) #Copyright (c) 2015-2016 mh4x0f P0cL4bs Team #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...
port Refactor def ExecRootApp(): check_dependencies() root = QApplication(argv) app = Initialize() app.setWindowIcon(QIcon('rsc/icon.ico')) app.center(),app.show() exit(root.exec_()) if __name__ == '__main__': if not getuid() == 0: app2 = QApplication(argv) priv = frm_prive...
),app2.exec_() exit(Refactor.threadRoot(priv.Editpassword.text())) ExecRootApp()
from pycp2k.inputsection import InputSection from ._dielectric_cube1 import _dielectric_cube1 from ._dirichlet_bc_cube1 import _dirichlet_bc_cube1 from ._dirichlet_cstr_charge_cube1 import _dirichlet_cstr_charge_cube1 class _implicit_psol
ver1(InputSection): def __init__(self): InputSection.__init__(self) self.DIELECTRIC_CUBE = _dielectric_cube1() self.D
IRICHLET_BC_CUBE = _dirichlet_bc_cube1() self.DIRICHLET_CSTR_CHARGE_CUBE = _dirichlet_cstr_charge_cube1() self._name = "IMPLICIT_PSOLVER" self._subsections = {'DIRICHLET_BC_CUBE': 'DIRICHLET_BC_CUBE', 'DIRICHLET_CSTR_CHARGE_CUBE': 'DIRICHLET_CSTR_CHARGE_CUBE', 'DIELECTRIC_CUBE': 'DIELECTRIC_CUBE...
import random from os.path import join, dirname import numpy as np from sklearn.base import ClassifierMixin, BaseEstimator import fasttext as ft from underthesea.util.file_io import write import os from underthesea.util.singleton import Singleton class FastTextClassifier(ClassifierMixin, BaseEstimator): def __i...
", "-") for _ in y] lines = ["__label__{} , {}".format(j, i) for i, j in zip(X, y)] content = "\n".join(lines) write(train_file, content) if
model_filename: self.estimator = ft.supervised(train_file, model_filename) else: self.estimator = ft.supervised(train_file) os.remove(train_file) def predict(self, X): return def predict_proba(self, X): output_ = self.estimator.predict_proba(X) ...
# Copyright 2016 ZTE 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 ...
re # distribut
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. from django.conf.urls import patterns, url from rest_framework.urlpatterns import fo...
""" NL2BR Extension =========
====== A Python-Markdown extension to treat newlines as hard breaks; like GitHub-flavored Markdown does. Usage: >>> import markdown >>> print markdown.markdown('line 1\\nline 2', extensions=['nl2br']) <p>line 1<br /> line 2</p> Copyright 2011 [Brian Neal](http://deathofagremmie.com/) Dependencies: ...
nsion(markdown.Extension): def extendMarkdown(self, md, md_globals): br_tag = markdown.inlinepatterns.SubstituteTagPattern(BR_RE, 'br') md.inlinePatterns.add('nl', br_tag, '_end') def makeExtension(configs=None): return Nl2BrExtension(configs)
from djan
go.db import models from taggit.managers import TaggableManager class BaseModel(models.Model): name = models.CharField(max_length=50, unique=True) tags = TaggableManager() def __unicode__(self): return self.name class Meta(object): abstract = True
class AlphaModel(BaseModel): pass class BetaModel(BaseModel): pass
#!/usr/bin/env python3 """ Calcu
late the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user. """ from __future__ import print_function import argparse import sys class App(object): """Application.""" def __init__(self, args): self._raw_args = args self._args = None ...
="Calculate Fibbonaci numbers ...") self.prepare_parser() def prepare_parser(self): """Prepare Argument Parser.""" self._argparse.add_argument( "w", type=int, help="Width") self._argparse.add_argument( "h", type=int, help="Height") self._argparse.add...
#!/usr/env/python """ diffusion_in_gravity.py Example of a continuous-time, stochastic, pair-based cellular automaton model, which simulates diffusion by random particle motion in a gravitational field. The purpose of the example is to demonstrate the use of an OrientedRasterLCA. GT, September 2014 """ from __future...
me + report_interval # Run the model
forward in time until the next output step ca.run(current_time+plot_interval, ca.node_state, plot_each_transition=False) #, plotter=ca_plotter) current_time += plot_interval # Plot the current grid ca_plotter.update_plot() # for debugging if _DEBUG: ...
# Copyright 2011 Justin Santa Barbara # 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 requ...
xtensionsTest, self)._get_flags() f['osapi_compute_extension'] = CONF.osapi
_compute_extension[:] f['osapi_compute_extension'].append( 'nova.tests.unit.api.openstack.compute.legacy_v2.extensions.' 'foxinsocks.Foxinsocks') return f def test_get_foxnsocks(self): # Simple check that fox-n-socks works. response = self.api.api_request('/f...
#--coding: utf8-- from django.shortcuts import render from templated_docs import fill_template from templated_docs.http import FileResponse from invoices.forms import InvoiceForm def invoice_view(request): form = InvoiceForm(request.POST or None) if form.is_valid(): doctype = form.cleaned
_data['format'] filename = fill_template( 'invoices/invoice
.odt', form.cleaned_data, output_format=doctype) visible_filename = 'invoice.{}'.format(doctype) return FileResponse(filename, visible_filename) else: return render(request, 'invoices/form.html', {'form': form})
#!/usr/bin/env python import argparse import json import time import logging from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient import RPi.GPIO as GPIO parser = argparse.ArgumentParser(description='Lightbulb control unit.') parser.add_argument('-e', '--endpoint', required=True, help='The AWS Iot endpoint.') ...
= BLUE updateShadow("blue") ti
me.sleep(0.05);
# -*- coding: utf-8 -*- # Copyright(C) 2016 Julien Veyssier # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
ill be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this weboob module. If not, see <...
oob.tools.compat import quote_plus from .browser import LyricsdotcomBrowser __all__ = ['LyricsdotcomModule'] class LyricsdotcomModule(Module, CapLyrics): NAME = 'lyricsdotcom' MAINTAINER = u'Julien Veyssier' EMAIL = 'eneiluj@gmx.fr' VERSION = '2.1' DESCRIPTION = 'Lyrics.com lyrics website' ...
t casperfpga import corr import logging from myQdr import Qdr as myQdr import types import sys import functools from loadWavePulseLut import loadWaveToMem,loadDdsToMem from loadWaveLut import writeBram from Utils.binTools import castBin def snapDdc(fpga,bSnapAll=False,bPlot=False,selBinIndex=0,selChanIndex=0,selChanSt...
ream',selChanStream) fpga.write_i
nt('sel_ctr',ddsAddrTrig) snapshotNames = ['snp2_bin_ss','snp2_ch_ss','snp2_dds_ss','snp2_mix_ss','snp2_ctr_ss','snp3_ddc_ss','snp3_cap_ss'] for name in snapshotNames: fpga.snapshots[name].arm(man_valid=bSnapAll) time.sleep(.1) fpga.write_int('trig_buf',1)#trigger snapshots time.sleep(.1) ...
from . import
stock_move from
. import product_product
#!/usr/bin/env python # # Copyright 2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr, gr_unittest, blocks import math class test_max(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block()...
tb.connect(src, s2v, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def stest_002(self): src_data=[-100,-99,-98,-97,-96,-1] expected_result = [float(max(src_data)),] src = blocks.vector_source_f(src_data) s2v =...
ocks.stream_to_vector(gr.sizeof_float, len(src_data)) op = blocks.max_ff(len(src_data)) dst = blocks.vector_sink_f() self.tb.connect(src, s2v, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def stest_003(self): ...
def
pe0001(upto): total = 0 for i in range(upto): if i
% 3 == 0 or i % 5 == 0: total += i return total print(pe0001(1000))
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor 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...
edirect from django.template.response import TemplateResponse from ..core.util import get_object_or_404 from ..users.decorators import login_redi
rect from ..testexecution.models import TestRunList from .forms import EnvironmentSelectionForm @login_redirect def set_environment(request, testrun_id): """ Given a test run ID, allow the user to choose a valid environment-group from among those valid for that test run, set that environment-group ID in...
import logging from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.http import Http404 from readthedocs.projects.models import Project, Domain log = logg...
main.machine = True domain.cname = True domain.count = domain.count + 1 domain.save() except (ObjectDoesNotExist, MultipleObjectsReturned): log.debug(LOG_TEMPLATE.format( m...
log.exception(LOG_TEMPLATE.format(msg='CNAME 404', **log_kwargs)) raise Http404(_('Invalid hostname')) # Google was finding crazy www.blah.readthedocs.org domains. # Block these explicitly after trying CNAME logic. if len(domain_parts) > 3: # St...
#!/usr/bin/env python3 import argparse import dataclasses from array import array from .edr import (EDRHeader, EDRD
isplayDataHeader, EDRSpectralDataHeader) def parse_args(): parser = argparse.ArgumentParser(description='Print .edr file') parser.add_argument('edr', type=argparse.FileType('rb'), help='.edr input filename') return parser.parse_args() def main(): arg...
t.size)) print_dataclass(edr_header, indent=1) for set_num in range(1, edr_header.num_sets + 1): print('Set {}'.format(set_num)) print('\tDisplay Data Header:') edr_header = EDRDisplayDataHeader.unpack_from( args.edr.read(EDRDisplayDataHeader.struct.size)) print_dat...
''' Motion Event Provider ===================== Abstract class for the implementation of a :class:`~kivy.input.motionevent.MotionEvent` provider. The implementation must support the :meth:`~MotionEventProvider.start`, :meth:`~MotionEventProvider.stop` and :meth:`~MotionEventProvider.update` methods. ''' __all__ = ('M...
nEventProvider: raise NotImplementedError('class MotionEventProvider is abstract') def start(self): '''Start the provider. This method is automatically called when the application is started and if the configuration uses the current provider. ''' pass def st...
the new touch events though the `dispatch_fn` argument. ''' pass
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-17 19:19 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_dependency(settings.AUTH_USER_MODEL), ('orders', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='order', options={'ordering': ['-created'], 'verbose_name': 'З...
name='address', ), migrations.RemoveField( model_name='order', name='email', ), migrations.RemoveField( model_name='order', name='postal_code', ), migrations.AddField( model_name='order', nam...
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def img_tag(obj, cls=""
): if hasattr(obj, "img"): if obj.img: return mark_safe("<img class='" + cls + "' src='" + obj.img.url + "'/>") return mark_safe("<span class='glyphicon glyphicon-picture " + cls + "'></span>") @register.filter def concat(obj, other): try: return str(obj) + str(other) excep...
return "" @register.filter def object_anchor(obj): return mark_safe("<a href='" + object_link(obj) + "'>" + str(obj) + "</a>")
''' Created on Mar 19, 2014 @author: Simon ''' from engine.engine_job import EngineJob class ValidationJob(Engin
eJob): ''' M/R job for validating a trained model. ''' def mapper(self, key, values): data_processor = self.get_data_processor() data_processor.set_data(values) data_processor.normalize_data(self.data_handler.get_statistics()) data_set = data_processor.get_data_set() ...
ucer(self, key, values): vals = list(values) yield key, self.get_validator().aggregate(vals) if __name__ == '__main__': ValidationJob.run()
# -*- coding: utf-8 -*- from __future__ import division from odoo import api, fields, models class A(models.Model): _name = 'test_testing_utilities.a' _description = 'Testing Utilities A' f1 = fields.Char(required=True) f2 = fields.Integer(default=42) f3 = fields.Integer() f4 = fields.Integer(...
ting Utilities Readonly' f1 = fields.Integer(default=1, readonly=True) f2 = fields.Integer(compute='_compute_f2') @api.depends('f1') def _compute_f2(self): for r in self: r.f2 = 2 * r.f1 class C(models.Model): _name = 'test_testing_utilities.c' _description
= 'Testing Utilities C' name = fields.Char("name", required=True) f2 = fields.Many2one('test_testing_utilities.m2o') @api.onchange('f2') def _on_change_f2(self): self.name = self.f2.name class M2O(models.Model): _name = 'test_testing_utilities.m2o' _description = 'Testing Utilities M...
import os import sys if sys.version_info >= (3, 0): sys.exit(0) import requests import json import numpy as np import time import logging import xgboost as xgb cur_dir = os.path.dirname(os.path.abspath(__file__)) from test_utils import (create_docker_connection, BenchmarkException, headers, ...
(app, model_name, version)) def get_test_point(): return [np.random.randint(255) for _ in range(784)] if __name__ == "__main__": pos_label = 3 try: clipper_conn = create_docker_connection( cleanup=True, start_clipper=True) try: clipper_conn.regis...
addr = clipper_conn.get_query_addr() response = requests.post( "http://%s/%s/predict" % (addr, app_name), headers=headers, data=json.dumps({ 'input': get_test_point() })) result = response.json() ...
theSector.fillColor = None for ish in xrange(nshades): sha1 = a1 + ish*shda sha2 = a1 + (ish+1)*shda shc = shader(shsc,shf1 + dsh*ish) if len(series)>1: ...
else: dsh = (shadingAmount-1)/float(nshades-1) sh
f1 = 1 shda = (a2-a1)/float(nshades) shsc = sectorStyle.fillColor theSector.fillColor = None for ish in xrange(nshades): sha1 = a1 + ish*shda sha2 = a1 + (ish+1)*shda ...
Otherwise, create render target file name based on time painting began. now = datetime.datetime.now() time_stamp = now.strftime('%Y_%m_%d__%H_%M_%S__') # VESTIGAL CODE; most versions of this script here altered the pseudorandom sequence of --RANDOM_SEED with the following line of code (that makes an rndStr...
st, I will assume that state image file name and anim frames folder names also do not exist; if I am wrong, those may get overwritten (by other logic in this script). target_render_file_exists = os.path.exists(render_target_
file_base_name + '.png') # If it does not exist, set render target file name to that ( + '.png'). In that case, the following following "while" block will never execute. BUT if it does exist, the following "while" block _will_ execute, and do this: rename the render target file name by appending six rnd hex chars to it...
# # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # SLEPc - Scalable Library for Eigenvalue Problem Computations # Copyright (c) 2002-2015, Universitat Politecnica de Valencia, Spain # # This file is part of SLEPc. # # SLEPc is free software: you can redistribute it and/or modify it u...
glelib = True elif self.isinstall and len(l)==3 and l[0]=='#define' and l[1]=='PETSC_ARCH': self.arch = l[2].st
rip('"') f.close() except: if self.isinstall: self.log.Exit('ERROR: cannot process file ' + petscconf_h + ', maybe you forgot to set PETSC_ARCH') else: self.log.Exit('ERROR: cannot process file ' + petscconf_h) # empty PETSC_ARCH, guess an arch name if self.isinstall and n...
from numpy import array, compress, zeros import wx from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin from spacq.interface.list_columns import ListParser """ Embeddable, generic, virtual, tabular display. """ class VirtualListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin): """ A generic virtual list. """ ma...
col_width) type = self.find_type(data[0,i]) self.types.append(type) def OnGetItemText(self, item, col): """ Return cell value for LC_VIRTUAL. """ return self.display_data[item,col]
class TabularDisplayPanel(wx.Panel): """ A panel to display arbitrary tabular data. """ def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) # Panel. panel_box = wx.BoxSizer(wx.VERTICAL) ## Table. self.table = VirtualListCtrl(self) panel_box.Add(self.table,...
ranged_attacker = "ranged attacker" melee_attacker = "melee attacker" healer = 'healer' dismantling_attacker = 'dismantler' general_attacker = 'general attacker'
tough_attacker = 'tough guy' work_and_carry_attacker = 'multi-purpose
attacker' civilian = 'civilian' scout = 'scout'
import time import tensorflow as tf import numpy as np import pandas as pd from scipy.misc import imread from alexnet import AlexNet sign_names = pd.read_csv('signnames.csv') nb_classes = 43 x = tf.placeholder(tf.float32, (None, 32, 32, 3)) resized
= tf.image.resize_images(x, (227, 227)) # NOTE: By setting `featur
e_extract` to `True` we return # the second to last layer. fc7 = AlexNet(resized, feature_extract=True) # TODO: Define a new fully connected layer followed by a softmax activation to classify # the traffic signs. Assign the result of the softmax activation to `probs` below. shape = (fc7.get_shape().as_list()[-1], nb_cl...
import json import bottle from pyrouted.util import make_spec def route(method, path): def decorator(f): f.http_route = path f.http_method = method return f return decorator class APIv1(object): prefix = '/v1' def __init__(self, ndb, config): self.ndb = ndb ...
(data, self.config) self.config['sources'].append(node) self.ndb.connect_source(node,
spec) @route('DELETE', '/sources') def sources_del(self): node = bottle.request.body.getvalue().decode('utf-8') self.config['sources'].remove(node) self.ndb.disconnect_source(node) @route('GET', '/config') def config_get(self): return bottle.template('{{!ret}}', ...
from ert.test import TestRun from ert.test import path_exists from ert.test import S
ourceEnumerator from ert.test import TestArea , TestAreaContext from ert.test import ErtTestRunner from e
rt.test import PathContext from ert.test import LintTestCase from ert.test import ImportTestCase from tests import EclTest class ErtLegacyTestTest(EclTest): pass
# 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 program is distributed in the hope that it will be useful, # bu...
# TODO: We need to add locking to prevent concurrent access to the # properties so that a client is not accessing while we are # replacing. o_prop = get_properties(self)[1] self.state = new_state n_prop = get_properties(self)[1] changed = get_object_property_diff...
changed += 1 return num_changed
from RPi import GPIO as gpio from robotics.actors.redbot_motor_actor import RedbotMotorActor from robotics.interfaces.spi.mcp3008_spi_interface import MCP3008SpiInterface from robotics.robots.aizek_robot import AizekRobot from robotics.sensors.redbot_wheel_encoder_sensor import RedbotWheelEncoderSensor from robotics.s...
@staticmethod def createAize
kRobot(): gpio.setmode(gpio.BOARD) lmotor = RedbotMotorActor(gpio, 8, 10, 12) rmotor = RedbotMotorActor(gpio, 11, 13, 15) spi = MCP3008SpiInterface(0) wencoder = RedbotWheelEncoderSensor(spi) lsensor = SharpIrDistanceSensor(spi, 5) fsensor = SharpIrDistanceSensor...
i] + [0]*i + [1/scl] chebpol = cheb.poly2cheb(pol) chebint = cheb.chebint(chebpol, m=1, k=[i]) res = cheb.cheb2poly(chebint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5): ...
ual(le
n(coef4), 5) assert_almost_equal(cheb.chebval(x, coef4), y) # coef2d = cheb.chebfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) coef2d = cheb.chebfit(x, np.array([y, y]).T, [0, 1, 2, 3]) assert_almost_equal(coef2d, np.array([coef3, co...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-18 19:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('coursedashboards', '0005_auto_20170915_2036'), ] operations = [ migrations.Create...
me='coursemajor', unique_together=set([]), ), migrations.RemoveField( model_name='coursemajor', name='course', ), migrations.RemoveField( model_name='coursemajor', name='major', ), migrations.AlterField( ...
), migrations.AddField( model_name='courseofferingmajor', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='coursedashboards.Course'), ), migrations.AddField( model_name='courseofferingmajor', ...
""" WSGI config for django_model_deploy project. This
module contains the WSGI application used by Django's development server and an
y production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the who...
# Copyright 2019,2020,2021 Sony Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except i
n 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 IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either e...
specific language governing permissions and # limitations under the License. import pytest import numpy as np import nnabla.functions as F from nbla_test_utils import list_context ctxs = list_context('Div2') @pytest.mark.parametrize("ctx, func_name", ctxs) @pytest.mark.parametrize("seed", [313]) @pytest.mark.param...
"""Utility to compare (Numpy) version strings. The NumpyVersion class allows properly comparing numpy version strings. The LooseVersion and StrictVersion classes that distutils provides don't work; they don't recognize anything like alpha/beta/rc/dev versions. """ import re from scipy._lib.six import string_types ...
else: self.pre_release = ''
self.is_devversion = bool(re.search(r'.dev', vstring)) def _compare_version(self, other): """Compare major.minor.bugfix""" if self.major == other.major: if self.minor == other.minor: if self.bugfix == other.bugfix: vercmp = 0 elif...
""" Django settings for practica4 project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os,...
ion # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { ...
lidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript...
from django import forms from .models import Join class EmailF
orm(forms.Form): email = forms.E
mailField() class JoinForm(forms.ModelForm): class Meta: model = Join fields = ["email",]
# Copyright 2015 The TensorFlow 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 applica...
-> 18100027895074076528 -> mod 10 -> 8 self.assertAllEqual([4, 2, 8], output.eval()) def
testStringToHashBucketsStrongInvalidKey(self): with self.test_session(): input_string = constant_op.constant(['a', 'b', 'c']) with self.assertRaisesOpError('Key must have 2 elements'): string_ops.string_to_hash_bucket_strong( input_string, 10, key=[98765]).eval() if __name__ == '__...
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='orgwolf', version='0...
nment', 'Framework :: Django', 'Framework :: Django :: X.Y', # repla
ce "X.Y" as appropriate 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6'...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='pygments-red', version='0.2', description='Pygments lexer for Ruby + Red.', keywords='pygments ruby red lexer', license='MIT', author='Aleksandar Milicevic', author_email='aleks@csail.mit.edu', url='https:...
lebarsLexer html+handlebars=pygments_red:HandlebarsHtmlLexer slang=pygments_red:Sla
ngLexer errb=pygments_red:ErrbLexer ered=pygments_red:EredLexer redhtml=pygments_red:RedHtmlLexer [pygments.styles] redstyle=pygments_red:RedStyle github=pygments_red:GithubStyle ...
NotImplemented def corrupting_licid(): return AbilityNotImplemented return corrupting_licid, corrupting_licid, @card("Volrath's Gardens") def volraths_gardens(card, abilities): def volraths_gardens(): return AbilityNotImplemented return volraths_gardens, @card("Volrath's Shapeshi...
def honor_guard(): return
AbilityNotImplemented return honor_guard, @card("Wall of Essence") def wall_of_essence(card, abilities): def wall_of_essence(): return AbilityNotImplemented def wall_of_essence(): return AbilityNotImplemented return wall_of_essence, wall_of_essence, @card("Flowstone Mauler") def...
# -*- coding: utf-8 -*- """ Authors: Tim Hessels UNESCO-IHE 2017 Contact: t.hessels@unesco-ihe.org Repository: https://github.com/wateraccounting/wa Module: Collect/JRC Description: This module downloads JRC water occurrence data from http://storage.googleapis.com/global-surface-water/downloads/. Use the JRC...
=[41, 45], lonlim=[-8, -5]) """ from .O
ccurrence import main as Occurrence __all__ = ['Occurrence'] __version__ = '0.1'
drunkenDoodling = { 'ghost': "Salt and iron, and don't forget to burn the corpse", 'wendigo': 'Burn it to death', 'phoenix': 'Use the colt', 'angel': 'Use the angelic blade', 'werewolf': 'Silver knife or bullet to the heart', 'shapeshifter': 'Sil
ver knife or bullet to the heart', 'rugaru': 'Burn it alive', 'reaper': "If it's nasty, you should gank who controls it", 'demon': "Use Ruby's knife, or some Jesus-juice", 'vampire'
: 'Behead it with a machete', 'dragon': 'You have to find the excalibur for that', 'leviathan': 'Use some Borax, then kill Dick', 'witch': 'They are humans', 'djinn': "Stab it with silver knife dipped in a lamb's blood", 'pagan god': 'It depends on which one it is', 'skinwalker': 'A silver bulle...
""" Created on 9 Nov 2012 @author: plish """ class TrelloObject(object): """ This class is a base object that should be used by all trello objects; Board, List, Card, etc. It contains methods needed and used by all those objects and masks the client calls as methods belonging to the object. """ ...
f.fetch_json(base_uri + '/boards') def get_board_json(self, base_uri): return self.fetch_json(base_uri + '/board') def get_lists_json(self, base_uri): return self.fetch_json(base_uri + '/lists') d
ef get_list_json(self, base_uri): return self.fetch_json(base_uri + '/list') def get_cards_json(self, base_uri): return self.fetch_json(base_uri + '/cards') def get_checklist_json(self, base_uri): return self.fetch_json(base_uri + '/checklists') def get_members_json(self, base_uri...
# -*- coding: iso-8859-1 -*- # # Copyright (C) 2001 - 2020 Massimo Gerardi all rights reserved. # # Author: Massimo Gerardi massimo.gerardi@gmail.com # # Copyright (c) 2020 Qsistemi.com. All rights reserved. # # Viale Giorgio Ribotta, 11 (Roma) # 00144 Roma (RM) - Italy # Phone: (+39) 06.87.163 # # # Si veda ...
lf.Destroy() def getColTxt(self, index, col): item = self.lc.GetItem(index, col) return item.GetText() def DblClick(self, event): self.cnt[1].SetValue(self.lc.GetItemText(self.currentItem)) self.cnt[2].SetValue(self.getColTxt(self.currentItem, 1)) se...
entItem = event.m_itemIndex self.DblClick(self)
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
not limitate the "read" of this models because user should need to access those documents, for example, to see partner due. """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'images': [ ], 'depends': [ 'acco
unt_voucher', ], 'data': [ 'views/res_store_view.xml', 'views/res_users_view.xml', 'views/account_view.xml', 'security/multi_store_security.xml', 'security/ir.model.access.csv', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': ...
from xmcam import * from xmconst import * from time import sleep CAM_IP = '192.168.1.10' CAM_PORT = 34567 if __name__ == '__main__': xm = XMCam(CAM_IP, CAM_PORT, 'admin', 'admin') login = xm.cmd_login() print(login) print(xm.cmd_system_function()) print(xm.cmd_system_info()) print(xm.cmd_chan...
print(xm.cmd_storage_info()) print(xm.cmd_users()) print(xm.cmd_ptz_control(PTZ_LEFT)) sleep(1) print(xm.cmd_ptz_control(PTZ_LEFT, True)) cfg = xm.cmd_config_export('export.cfg') print('Config =
=>', cfg) snap = xm.cmd_snap('test.jpg') print('SNAP ==>', snap)
""" Store status messages in the database. """ from django.db import models from django.contrib import admin from django.core.cache import cache from xmodule_django.models import CourseKeyField from config_models.models import ConfigurationModel from config_models.admin import ConfigurationModelAdmin class GlobalS...
pass cache.set(cache_key, msg) return msg def __unicode__(self): return "{} - {} - {}".format(self.change_date, self.enabled, self.message) class CourseMessage(models.M
odel): """ Model that allows the user to specify messages for individual courses. This is not a ConfigurationModel because using it's not designed to support multiple configurations at once, which would be problematic if separate courses need separate error messages. """ global_message = models...
from time import time import argparse import numpy as np from sklearn.dummy import DummyClassifier from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.metrics import accuracy_score from sklearn.utils.validation import check_array from sklearn.ensemble import RandomForestClassifier from sklearn.en...
print("Classification performance:") print("===========================") print() print("%s %s %s %s" % ("Classifier ", "train-time", "test
-time", "Accuracy")) print("-" * 44) for name in sorted(accuracy, key=accuracy.get): print("%s %s %s %s" % (name.ljust(16), ("%.4fs" % train_time[name]).center(10), ("%.4fs" % test_time[name]).center(10), ...
"""Queue item for deep analysis by irwin""" from default_imports import * from modules.queue.Origin import Origin from modules.game.Game import PlayerID from datetime import datetime import pymongo from pymongo.collection import Collection IrwinQueue = NamedTuple('IrwinQueue', [ ('id', PlayerID), ('o...
Queue: return IrwinQueue( id=bson['_id'], origin=bso
n['origin']) @staticmethod def writes(irwinQueue: IrwinQueue) -> Dict: return { '_id': irwinQueue.id, 'origin': irwinQueue.origin, 'date': datetime.now() } class IrwinQueueDB(NamedTuple('IrwinQueueDB', [ ('irwinQueueColl', Collection) ])): de...
#!/usr/bin/env python import unittest from SDDetector.Entities.Gene import Gene from SDDetector.Entities.Transcript import Transcript from SDDetector.Entities.CDS import CDS from SDDetector.Parser.Gff.GffGeneParser import GffGeneParser class TestGffGeneParser(unittest.TestCase): def setUp(self): pass ...
pt('G00001.1','Chr1',23988,24919,-1,'G00001',[CDS('G00001.1_cds_1','Chr1',23988,24083, -1, 'G00001.1'),CDS('G00001.1_cds_1','Chr1',24274,24427,-1,'G00001.1'),CDS('G00001.1_cds_1','Chr1',24489,24919,-1,'G00001.1')])])] # self.assertEqual(iGffGeneParser.getAll
Genes()[0],lGenes[0]) if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(TestGffGeneParser) unittest.TextTestRunner(verbosity=2).run(suite)
ance # when iterating and indexing the result (see usage in `pad`) x_view = x.view() x_view.shape = (ndim, 2) return x_view.tolist() # def _pad_dispatcher(array, pad_width, mode=None, **kwargs): # return (array,) ############################################################################### # Pub...
unique pad widths for each axis. ((before, after),) yields
same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes. You cannot specify ``cupy.ndarray``. mode(str or function, optional): One of the following string values or a user supplied function 'constant' (def...
from django.core.management.base import BaseCommand, CommandError from corehq.elastic import get_es_new from corehq.pillows.utils import get_all_expected_es_indices class Command(BaseCommand): help = "Update dynamic settings for existing elasticsearch indices." def add_arguments(self, parser): parse...
o, settings in to_update: mapping_res = es.indices.put_settings(index=index_info.index, body=settings) if mapping_res.get('acknowledged', False): print("{} [{}]:\n Index settings successfully updated".format( index_info.alias, ...
else: print(mapping_res) def _confirm(message): if input( '{} [y/n]'.format(message) ).lower() == 'y': return True else: raise CommandError('abort')
# Copyright 2019 The dm_control Authors. # # 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 Lic
ense at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR C
ONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Composer models of Kinova robots.""" from dm_control.entities.manipulators.kinova....
evice is managed by Google, but used only by you. short_description: Creates a GCP TargetVpnGateway version_added: 2.7 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in ...
t(link), kind, allow_not_found) def self_link(module): return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetVpnGateways/{name}".format(**module.params) def collection(module): return "https://www.googleapis.com/compute
/v1/projects/{project}/regions/{region}/targetVpnGateways".format(**module.params) def return_if_object(module, response, kind, allow_not_found=False): # If not found, return nothing. if allow_not_found and response.status_code == 404: return None # If no content, return nothing. if response....
#!/usr/bin/env python # # Copyright 2007 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 o...
esServiceError.UNEXPECTED_STATE) def _Dynamic_StopModule(self, request, response, request_id): try: module, version, dispatcher = self._G
etModuleAndVersionFromRequest( request, request_id) dispatcher.stop_module(module, version) except (request_info.ModuleDoesNotExistError, request_info.VersionDoesNotExistError, request_info.NotSupportedWithAutoScalingError): raise apiproxy_errors.ApplicationError( ...
adlib.py # # A lot of help from: # http://marcitland.blogspot.com/2011/02/python-active-directory-linux.html # import sys is my friend! import sys import logging import ldap from person import Person #import netrc import base64,zlib import ldap.modlist as modlist from secure import ADurl, adusername, adpassword i...
#~ print "error finding username: %s" % error_message return False def addUser(self): # Build User if self.perrec.ADContainer == 'noOU': logger.debug("User does not have container: %s" % self.perrec.userid) logger.error("AD Account not cre...
se user_dn = 'cn=' + self.perrec.userid + ',' + self.perrec.ADContainer logger.info('User DN for new user: %s', user_dn) user_attrs = {} user_attrs['objectClass'] = \ ['top', 'person', 'organizationalPerson', 'user'] user_attrs['cn'] = str(self.perrec.userid) user_attrs['userPrincipalName'] = str(sel...
from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib import messages from models import UserVote from forms import UserVoteForm def vote(request): if request.method ...
request.POST) if form.is_valid(): vote = form.save(commit=False) vote = UserVote.objects.vote(request.user, vote.vote) messages.info(request, "Your mood is %s" % vote.get_v
ote_display()) else: form = UserVoteForm() return HttpResponseRedirect(reverse('dashboard'))
# coding: utf-8 """`MemoryFS` opener definition. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import typing from .base import Opener from .registry import registry if typing.TYPE_CHECKING: from typing import Text from .parse import ...
F401 @registry.install class
MemOpener(Opener): """`MemoryFS` opener.""" protocols = ["mem"] def open_fs( self, fs_url, # type: Text parse_result, # type: ParseResult writeable, # type: bool create, # type: bool cwd, # type: Text ): # type: (...) -> MemoryFS fro...
#!/usr/bin/env python # coding=utf-8 __author__ = 'Jayin Ton' from flask import Flask app = Flask(__name__) host = '127.0.0.1' port = 8000
@app.route('/') def index()
: return 'welcome' if __name__ == '__main__': app.run(host=host, port=port, debug=True)
#!/usr/bin/env python from distutils.core import setup,Extension from distutils.command.build_py import build_py dist = setup(name='PyMobot', version='0.1', description='Mobot Control Python Library', author='David Ko', author_email='david@barobo.com', url='http://www.barobo.com', packages=
['barobo'], ext_modules=[Extension('barobo._mobot', ['barobo/mobot.i'], swig_opts=['
-c++', '-I../'], include_dirs=['../', '../BaroboConfigFile', '../BaroboConfigFile/mxml-2.7'], define_macros=[('NONRELEASE','1')], extra_compile_args=['-fpermissive'], library_dirs=['../', '../BaroboConfigFile', '../BaroboConfigFile/mxml-2.7'], libraries=['baroboStatic', 'baroboconfigfile',...
#!/usr/bin/env python # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from tinycss.css21 import CSS21Parser from tinycss.parsing import remove_whit...
ions=(), negated=False): self.media_type = media_type self.expressions = expressions self.negated = n
egated def __repr__(self): return '<MediaQuery type=%s negated=%s expressions=%s>' % ( self.media_type, self.negated, self.expressions) def __eq__(self, other): return self.media_type == getattr(other, 'media_type', None) and \ self.negated == getattr(other, 'negated', ...
# ext
ension imports from _NetworKit import PageRankNibble, GC
E
_(copy.copy(x) is x, repr(x)) def test_copy_list(self): x = [1, 2, 3] self.assertEqual(copy.copy(x), x) def test_copy_tuple(self): x = (1, 2, 3) self.assertEqual(copy.copy(x), x) def test_copy_dict(self): x = {"foo": 1, "bar": 2} self.assertEqual(copy.copy(...
etstate_setstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return self.foo def __setstate__(self, state): self.foo = state def __cmp__(self, other): return cmp(se...
x = 42 y = copy.deepcopy(x) self.assertEqual(y, x) def test_deepcopy_memo(self): # Tests of reflexive objects are under type-specific sections below. # This tests only repetitions of objects. x = [] x = [x, x] y = copy.deepcopy(x) self.assertEqu...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse #import imp from validator import * from settings import * from utils import * parser = argparse.ArgumentParser(description='Sync two Databases', epilog="Es: python main.py -run test --db-master=mysql://root:remotepasswd@192.168.0.21...
t the --no-schemacheck this will start the Schema Comparison to control # that the two files are identical if not args.no_schemacheck: SchemaComp
arator() # use imp to import the tables_schemes. This make all the things more simple ! # deprecated: I abandoned it because of ugly warnings like this: # RuntimeWarning: Parent module 'master_schema' not found while handling absolute import... #master_schema = imp.load_source('master_schema.py', DB_MAP_FOLDER+'/...
t(num): for x in ['bytes','KB','MB']: num /= 1024.0 return "%3.5f" % (num) def get_vm_permissions(auth_manager, vm_mor, request): vm_mor_type = "VirtualMachine" _this = request.new__this(auth_manager) _this.set_attribute_type(auth_manager.get_attribute_type()) request.set_element__this(...
n dvpgs def get_path(entity, entities_info): parent = entity.get('parent') display_name = "%s" % (entity['name']) if parent and parent in entities_info: return get_path(entities_info[parent], entities_info) + " > " + display_name return display_name def get_paths_dict(server, pro...
ies_info = {} paths = {} # getting managed entities props2 = server._retrieve_properties_traversal(property_names=properties2, obj_type='ManagedEntity') # building a dictionary with the Managed Entities info for prop in props2: mor = prop.Obj entity = {'id':mor, 'name':None, 'pare...
from PdfProcessor import * import argparse from datetime import datetime import ConfigParser import ProcessLogger import traceback from urllib2 import HTTPError, URLError parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text') parser.add_argument('-l','--language', help='Language of inp...
debug(traceback.format_exception(*sys.exc_info())) except HTTPError as e: logger.error("HTTPError: [%s] %s", e.code, e.reason); logger.debug(traceback.format_exception(*sys.exc_info())) except OSError as e: logger.error("OSError: %s [%s] in %s", e.strerror,
e.errno, e.filename); logger.debug(traceback.format_exception(*sys.exc_info())) except Exception as e: logger.error("Exception: %s ", e); logger.debug(traceback.format_exception(*sys.exc_info())) finally: logger.info("Processing ended at %s ", str(datetime.now()));
#!/usr/bin/python import requests import time, Cookie # Instantiate a Simple
Cookie object cookie = Cookie.SimpleCookie() # The SimpleCookie instance is a mapping cookie['lastvisit'] = str(time.time()) s = requests.session() s.cookies.clear() # Output the HTTP message containing the cookie print cookie print 'Content-Type: text/html\n' print '<html><body>' print 'Server time is', time....
time()) print '</body></html>'
""" commswave ========= Takes device communications up and down according to a timefunction. Comms will be working whenever the timefunction returns non-zero. Configurable parameters:: { "timefunction" : A timefunction definition "threshold" : (optional) Comms will only work when the timefunction ...
thresh = 0.0 if self.comms_tf_threshold is not None: thresh = self.comms_tf_threshold return self.comms_timefunction.state() > thresh def comms_ok(self): if self.comms_gate_properties
is not None: # If we're gating individual properties, then don't gate overall comms return super(Commswave, self).comms_ok() else: self.messages_attempted += 1 is_ok = super(Commswave, self).comms_ok() is_ok = is_ok and self.timefunction_says_communicate() ...
import json from plugins import gateway_speaker from plugins.magnet import MAGNET_STORE_KEY DOOR_SENSO
R_SID = '158d0001837ec2' def run(store, conn, cursor): """Play sound on the Gateway when somebody opens the door""" p = store.pubsub(ignore_subscribe_messages=True) p.subscribe(MAGNET_STORE_KEY) for message in p.listen(): if mess
age.get('type') != 'message': continue data = json.loads(message.get('data').decode()) if data.get('sid') == DOOR_SENSOR_SID and data.get('status') == 'open': gateway_speaker.play(3) # Standard alarm sound
# Copyright 2019 Google Inc. 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 law or ...
metric.value if p_value < P_VALUE_THRESHOLD: return template.LOW_P_VALUE.format( name_one=name_list[0], name_two=name_list[1], metric='p-value', value="{:.2E}".format(Decimal(str(p_value))), test_name
=analysis_name ) return None
elopment tools config settings' _inherit = ['res.config.settings'] _rec_name = 'id' _order = 'id ASC' # ---------------------------- ENTITY FIELDS ------------------------------ email_to = fields.Char( string='Email to', required=False, readonly=False, index=False...
email_to=self.get_email_to(), email_capture=self.get_email_capture(), developing_modules_enabled=self.get_developing_modules_enabled(), developing_module_ids=self.get_developing_module_ids(), search_default_app=self.ge
t_search_default_app(), development_mode=self.get_debug_mode(), ) @api.one def set_default_values(self): self._set_email_to() self._set_email_capture() self._set_developing_modules_enabled() self._set_developing_module_ids() self._set_search_default_a...
project.kill(service_names=options['SERVICE'], signal=signal) def logs(self, project, options): """ View output from containers. Usage: logs [options] [SERVICE...] Options: --no-color Produce monochrome output. """ containers = project.container...
if options['--entrypoint']: container_options['entrypoint'] = options.get('--entrypoint') if options['--rm']: container_options['restart'] = None
if options['--user']: container_options['user'] = options.get('--user') if not options['--service-ports']: container_options['ports'] = [] try: container = service.create_container( quiet=True, one_off=True, insecur...
# Copyright 2018 Silvio Gregorini (silviogregorini@openforce.it) # Copyright (c) 2018 Openforce Srls Unipersonale (www.openforce.it) # Copyright (c) 2019 Matteo Bi
lotta # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit
= "res.config.settings" sp_description = fields.Char( related="company_id.sp_description", string="Description for period end statements", readonly=False, )
"""General-use classes to interact with the ApplicationAutoScaling service through CloudFormation. See Also: `AWS developer guide for ApplicationAutoScaling <https://docs.aws.amaz
on.com/autoscaling/application/APIReference/Welcome.html>`_ """ # noinspection PyUnresolvedReferences from .._raw import applicationautoscaling as _raw # noinspection PyUnresolvedReferences from ..
_raw.applicationautoscaling import *
# Created By: Virgil Dupras # Created On: 2009-11-27 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/g...
pe from ..filter_bar import FilterBar tr = trget('ui') class TransactionFilterBar(FilterBar): BUTTONS = [ (tr("All"), None), (tr("Income"), FilterType.Income), (t
r("Expenses"), FilterType.Expense), (tr("Transfers"), FilterType.Transfer), (tr("Unassigned"), FilterType.Unassigned), (tr("Reconciled"), FilterType.Reconciled), (tr("Not Reconciled"), FilterType.NotReconciled), ]
# -*- coding: UTF-8 """ Entry decorators for python plugins Functions ========= chat_message -- Decorator for chat message plugin chat_command -- Decorator for chat command plugin chat_accost -- Decorator for chat accost plugin """ from dewyatochka.core.plugin.loader.internal import entry_point from dew...
chat_command', 'chat_message', 'chat_accost'] # Commands already in use _reserved_commands = set() def chat_message(fn=None, *, services=None, regular=False, system=False, own=False) -> callable: """ Decorator to mark function as message handler entry point :param callable fn: Function if decorator is invo...
this handler for regular messages :param bool system: Register this handler for system messages :param bool own: Register this handler for own messages :return callable: """ return entry_point(PLUGIN_TYPE_MESSAGE, services=services, regular=True, system=False, own=False)(fn) \ if fn is not N...
navigator.navigator().downloads() elif action == 'libraryNavigator': from resources.lib.indexers import navigator navigator.navigator().library() elif action == 'toolNavigator': from resources.lib.indexers import navigator navigator.navigator().tools() elif action == 'searchNavigator': from reso...
b.indexers import movies movies.mov
ies().get(url) elif action == 'moviePage': from resources.lib.indexers import movies movies.movies().get(url) elif action == 'movieWidget': from resources.lib.indexers import movies movies.movies().widget() elif action == 'movieSearch': from resources.lib.indexers import movies movies.movies(...
# %FILEHEADER% from ..filebased import FileBasedBackend from .. import NONE, MissingOption from xmlserialize import serialize_to_file, unserialize_file from lxml.etree import XMLSyntax
Error class XMLBackend(dic
t, FileBasedBackend): ROOT_ELEMENT = 'configuration' initial_file_content = '<{0}></{0}>'.format(ROOT_ELEMENT) def __init__(self, backref, extension='xml', filename=None): dict.__init__(self) FileBasedBackend.__init__(self, backref, extension, filename) def read(self): try: ...
import re import urllib from xbmcswift2 import xbmc from meta import plugin, LANG from meta.gui import dialogs from meta.utils.text import to_unicode from meta.library.live import get_player_plugin_from_library from meta.navigation.base import get_icon_path, get_background_path from meta.play.players import get_needed_...
s import get_needed_langs, ADDON_PICKER from meta.play.base import active_players, active_channelers, action_cancel, action_play, on_play_video from settings import SETTING_USE_SIMPLE_SELECTOR, SETTING_LIVE_DEFAULT_PLAYER_FROM_CONTEXT, SETTING_LIVE_DEFAULT_PLAYER_FROM_LIBRARY, SETTING_LIVE_DEFAULT_PLAYER, SETTING_LIVE...
tring as _ def play_channel(channel, program, language, mode): # Get players to use if mode == 'select': play_plugin = ADDON_SELECTOR.id elif mode == 'context': play_plugin = plugin.get_setting(SETTING_LIVE_DEFAULT_PLAYER_FROM_CONTEXT, unicode) elif mode == 'library': play_plugi...
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.conf import se...
created_on = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_('created on')) message = models.CharField(max_length=140, editable=False, default="", verbose_name=_('message')) identifier = InternalIdentifierField(unique=False) priority = EnumIntegerField(Priority, default=Priority.N
ORMAL, db_index=True, verbose_name=_('priority')) _data = JSONField(blank=True, null=True, editable=False, db_column="data") marked_read = models.BooleanField(db_index=True, editable=False, default=False, verbose_name=_('marked read')) marked_read_by = models.ForeignKey( settings.AUTH_USER_MODEL, b...
interval=interval) self._checkers[path] = checker self._loop.call_soon_threadsafe(checker.start) def stop_checking(self, path, timeout=None): """ Stop checking path. If timeout is set, wait until the checker has stopped, or the timeout has expired. """ ...
int the process may be still running. """ assert self._state is not IDLE self._reader = None self._err = data rc = self._proc.poll() # About 95% of runs, the process has terminated at this point. If not, # start the reaper to wait for it. if rc is ...
_check_completed(rc) def _check_completed(self, rc): """ Called when the dd process has exited with exit code rc. """ assert self._state is not IDLE now = self._loop.time() elapsed = now - self._check_time _log.debug("FINISH check %r (rc=%s, elapsed=%.02f)", ...
# coding: utf-8 # # Copyright © 2012-2015 Ejwa Software. All rights reserved. # # This file is part of gitinspector. # # gitinspector 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 Lic...
ITNESS 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 gitinspector. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals DEFAULT
_EXTENSIONS = {"java":"java", "c":"c", "cc":"c", "cpp":"cpp", "h":"cpp", "hh":"cpp", "hpp":"cpp", "py":"python", "glsl":"opengl", "rb":"ruby", "js":"javascript", "sql":"sql", "fltar":"ansible","pkb":"sql", "pks":"sql","txt":"text", "drt":"drools", "drl":"drools", "bpmn":"proc...
# The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS"basis, #...
def process(self, data, url_object): """Process XML data. Converts document to json before processing with TextProcessor. if XML is not well formed, treat it as HTML """ logging.info("Process XML %s" % url_object.url) try: data = json.dumps(xmltodict.p...
f).process(data,url_object) Processor.register_processor(XmlProcessor.item_type, XmlProcessor)
# Copyright 2020 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 agreed to in writing, ...
age = "jupyterlab_gitsync-{}.tgz".format(version) if not os.path.exists(os.path.join(os.getcwd(), npm_package)): raise FileNotFoundError("Cannot find NPM package. Did you run `npm pack`?") data_files = [ ("share/jupyter/lab/extensions", (npm_package,)), ("etc/jupyter/jupyter_notebook_config.d", ("jupyte...
tup( name="jupyterlab_gitsync", version=version, description="JupyterLab Git Sync", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/GoogleCloudPlatform/jupyter-extensions", data_files=data_files, license="Apache License 2.0", ...
import logging from time import sleep from tools.audios
ink import AudioSink demo = logging.getLogger('Demo') logging.basicConfig(level=logging.DEBUG) p = AudioSink() with open("sample.wav", 'rb') as f: a = f.read() demo.info("add the first track") p.add(a, "a") sleep(2) with open("sample.wav", 'rb') as f: b = f.read() demo.info("add a second track") p.add(b,...
= 40 sleep(15) demo.info("close the AudioSink") p.close()
import numpy import os import sys # This script depends on a SJSON parsing package: # https://pypi.python.org/pypi/SJSON/1.1.0 # https://shelter13.net/projects/SJSON/ # https://bitbucket.org/Anteru/sjson/src import sjson if __name__ == "__main__": if sys.version_info < (3, 4): print('Python 3.4 or higher needed to...
numpy.loadtxt(entry['file'], delimiter=',', dtype=input_data_type_def, skiprows=1, usecols=columns_to_extract) filter = entry.get('filter', None) if filter != None: best_variable_data_mask = csv_data['algorithm_names'] == bytes(entry['filter'], encoding = 'utf-8') csv_data = csv_data[best_variable_data_mask]...
der']) output_csv_data = numpy.column_stack(output_csv_data) with open(output_csv_file_path, 'wb') as f: header = bytes('{}\n'.format(','.join(output_csv_headers)), 'utf-8') f.write(header) numpy.savetxt(f, output_csv_data, delimiter=',', fmt=('%s'))
from common import * DEBUG = True MONGODB_SETTINGS = { 'HOST': '127.0.0.1', 'PORT': 27017, 'DB': 'myhoard_dev', 'USERNAME': 'myhoard', 'PASSWORD': 'myh0@rd', } # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'NOTSET', 'handlers...
'level': 'INFO', 'formatter': 'standard', 'filename': '/home/pat/logs/dev/myhoard.log', 'mode': 'a',
'maxBytes': 2 * 1024 * 1024, # 2MiB 'backupCount': 64, }, }, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', }, }, }
class Solution(object): def maxSumOfThreeSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ window = [] c_sum = 0 for i, v in enumerate(nums): c_sum += v if i >= k: c_sum -
= nums[i-k] if i >= k-1: window.append(c_sum) left = [0] * len(window) best = 0 for i in range(len(window)): if window[i] > window[best]: best = i left[i] = best right = [0] * len(window) best = len(window) ...
ight[i] = best ans = None for b in range(k, len(window) - k): a, c = left[b-k], right[b+k] if ans is None or (window[a] + window[b] + window[c] > window[ans[0]] + window[ans[1]] + window[ans[2]]): ans = a, b, c retu...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.exterior_equipment import ExteriorFuelEquipment log = logging.getLogger(__name__) class TestExteriorFuelEquipment(unittest.TestCase): def setUp(self): self.fd, self...
iorfuelequipments[0].name, var_name)
self.assertEqual(idf2.exteriorfuelequipments[0].fuel_use_type, var_fuel_use_type) self.assertEqual(idf2.exteriorfuelequipments[0].schedule_name, var_schedule_name) self.assertAlmostEqual(idf2.exteriorfuelequipments[0].design_level, var_design_level) self.assertEqual(idf2.exteriorfuelequipment...
""" sphinxit.core.constants ~~~~~~~~~~~~~~~~~~~~~~~ Defines some Sphinx-specific constants. :copyright: (c) 2013 by Roman Semirook. :license: BSD, see LICENSE for more details. """ from collections import namedtuple RESERVED_KEYWORDS = ( 'AND', 'AS', 'ASC', 'AVG', 'BEGIN', ...
N', 'OR', 'ORDER', 'REPLACE', 'ROLLBACK', 'SELECT', 'SET', 'SHOW', 'START', 'STATUS', 'SUM', 'TABLES', 'TRANSACTION', 'TRUE', 'UPDATE', 'VALUES', 'VARIABLES', 'WARNINGS', 'WEIGHT', 'WHERE', 'WITHIN' ) ES
CAPED_CHARS = namedtuple('EscapedChars', ['single_escape', 'double_escape'])( single_escape=("'", '+', '[', ']', '=', '*'), double_escape=('@', '!', '^', '(', ')', '~', '-', '|', '/', '<<', '$', '"') ) NODES_ORDER = namedtuple('NodesOrder', ['select', 'update'])( select=( 'SelectFrom', 'Whe...