prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
r FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston,...
mport os import llnl.util.tty as tty from llnl.util.filesystem import mkdirp, working_dir import spack from spack.util.executable import ProcessError, which _SPACK_UPSTREAM = 'https://github.com/spack/spack' description = "create a new installation of spack in another prefix" section = "admin" level = "long" def ...
import squeezeboxserver import t
ime squeezebox = squeezeboxserver.SqueezeboxServer("192.168.1.65:9000") players = squeezebox.players() for p in players: print ("MAC: %s" % p['playerid']) time.sleep(10) squeezebox.power("00:04:20:06:8c:55", "on") squeezebox.playlist("00:04:20:06:8c:55", "play") time.sleep(10) squeezebox.playlist("...
, "stop") time.sleep(3) squeezebox.power("00:04:20:06:8c:55", "off")
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 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 # with...
py 5357 2011/09/09 21:31:03 bdeegan" __doc__ = """ Common functions for Microsoft Visual Studio and Visual C/C++. """ import copy import os import re import subprocess import SCons.Errors import SCons.Platform.win32 import SCons.Util from SCons.Tool.MSCommon.sdk import mssdk_exists, \ ...
xists, \ msvc_setup_env, \ msvc_setup_env_once from SCons.Tool.MSCommon.vs import get_default_version, \ get_vs_by_version, \ merge_default_version, \ ...
import re def fun(s): # return True if s is a valid email, else return False f = "^[a-zA-Z][\w-]*@[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$" if not re.match(f, s): return False username, after = re.spli
t(r'[@]', s) websitename, extension = re.split(r'[.]', after) if(len(extension) > 3): return False return True def filter_mail(emails): return list(filter(fun, emails)) if __name__ == '__main__': n = int(input()) emails = [] for _
in range(n): emails.append(input()) filtered_emails = filter_mail(emails) filtered_emails.sort() print(filtered_emails)
from models import Event from django.views.generic
import DetailView, ListView class EventListView(ListView): template_name = 'agenda/event_list.html' queryset = Event.objects.upcoming() paginate_by = 20 class EventArchiveview(EventListView): queryset = Event.objects.past() class EventDetailView(DetailView): model = Event te
mplate_name = 'agenda/event_detail.html'
# 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...
, 8) out = tf.keras.laye
rs.Dense(4)(max_inp) model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) ``` Args: inputs: A list of input tensors (at least 2) of same shape. **kwargs: Standard layer keyword arguments. Returns: A tensor (of same shape as input tensor) with the element-wise maximum of ...
#!/usr/bin/env python """ demonstrate adding a FigureCanvasGTK3Agg widget to a Gtk.ScrolledWindow using GTK3 accessed via pygobject """ from gi.repository import Gtk from matplotlib.figure i
mport Figure from numpy import arange, sin, pi from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas win = Gtk.Window() win.
connect("delete-event", Gtk.main_quit ) win.set_default_size(400,300) win.set_title("Embedding in GTK") f = Figure(figsize=(5,4), dpi=100) a = f.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) a.plot(t,s) sw = Gtk.ScrolledWindow() win.add (sw) # A scrolled window border goes outside the scrollbars and viewp...
import os import sys from Bio import Entrez import wx from xml.dom import minidom import re class etPlugin(): def GetName(self): ''' Method to return name of tool ''' return "ESummary" def GetBMP(self, dirH): ''' Method to return identifying image ''...
arent.dbGoMenu[itnum], parent.helpDB)) parent.lowDB,dummy = parent.menuHandlers[tempIdNum] #Setup the database menu options parent.dbaseMenu = wx.Menu() for itnum,tool in enumerate(parent.dbList): parent.dbaseMenu.Append(parent.dbGoMenu[itnum], tool, ...
(2,parent.dbaseMenu, "Database") parent.menuBar.UpdateMenus() parent.dbCB = wx.ComboBox(parent=parent.panelSQ, id=-1, pos=(256,6), choices=parent.dbList, style=wx.CB_READONLY) tempChk = 0 while tempChk < len(parent.dbList): if tempVal == parent.dbLis...
#!/usr/bin/env import subprocess, os, random, copy output_filename = "twelvetone_ex.ly" output_file = open(output_filename, "w") notes = ['c','cis','d','dis','e','f','fis','g','gis','a','ais','b'] temp_tt_array = [] def twelvetone_gen(): notes_svd = copy.copy(notes) a = 11 while len(temp_tt_array) < 12...
t_a
rray output_file.write(r'''\version "2.16.0"\header{tagline=""}\paper{indent=0 line-width=130 top-margin=13}\layout{\context{\Staff \remove "Stem_engraver" \remove "Time_signature_engraver" \override Stem #'transparent = ##t}}\score{\transpose c c' << \new Staff''') temp_tt_string = '' for x in range(0, 16): out...
# # This file is part of pyasn1-modules software. # # Created by Russ Housley # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder f...
CAQ0E NRYzVGhpcyBjZXJ0aWZpY2F0ZSBjYW5ub3QgYmUgdHJ1c3RlZCBmb3IgYW55IHB1 cnBvc2UuMFMGA1UdEQRMMEqgNgYIKwYBBQUHCAOgKjAoDBs4MjYyMDgtNDE3MDI4 LTU0ODE5NS0yMTUyMzMGCSsGAQQBgaxgMIEQZ2FpbEBleGFtcGxlLmNvbTAKBggq hkjOPQQDAwNoADBlAjBT+36Y/LPaGSu+61P7kR97M8jAjtH5DtUwrWR02ChshvYJ x0bpZq3PJaO0WlBgFicCMQCf+67wSvjxxtjI/OAg4t8NQIJW1LcehS...
SVMeDFsCo= """ def setUp(self): self.asn1Spec = rfc5280.Certificate() def testDerCodec(self): substrate = pem.readBase64fromText(self.cert_pem_text) asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec) self.assertFalse(rest) self.assertTrue(asn1Object.pret...
""" Filenames of the tests """ import os from os.path import join as pjoin from .. import LiF_g4 # This is a 2x2x2 q-point grid. The weights can be obtained from abinit. nqpt = 3 wtq = [0.125, 0.5, 0.375] # Indices of the q-points in the 4x4x4 grid. iqpt_subset = [0, 2, 6] dirname = os.path.dirname(__file__) fna...
) for key in ('eigq_fnames', 'ddb_fnames', 'eigr2d_fname
s', 'gkk_fnames'): for i in iqpt_subset: fnames[key].append(LiF_g4.fnames[key][i]) refdir = pjoin(dirname, 'epc_outputs')
""" """ from Tkinter import * from areavi import AreaVi from ttk import Notebook class PanedHorizontalWindow(PanedWindow): """ """ def __init__(self, *args, **kwargs): """ """ PanedWindow.__init__(self, orient=HORIZONTAL, *args, **kwargs) def create_area(self): ""...
ef
load(self, *args): """ """ base = PanedHorizontalWindow(master=self) self.add(base) for ind in args: base.load(ind) return base class NoteVi(Notebook): """ """ def __init__(self, *args, **kwargs): """ """ Notebook.__...
ort json_encoding from ..xmlrpc import client as xmlrpcclient from ...sfa.trust.credential import Credential class Framework_Base(): """ Framework_Base is an abstract class that identifies the minimal set of functions that must be implemented in order to add a control framework to omni. Instruc...
PC client over SSL with a client side certificate.""" return xmlrpcclient.make_client(url, keyfile, certfile, verbose=verbose, timeout=timeout, allow_none=al...
logger = self.logger else:
""" WSGI config for elixirapp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os, sys from django.core.wsgi
import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "elixirapp.settings") os.
environ["CELERY_LOADER"] = "django" sys.path.insert(0,'/elixir/application/backend') application = get_wsgi_application()
# -*- coding: utf-8 -*- """ database.use_tornado_database ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Using tornado.database with MySQL http://flask.pocoo.org/snippets/11/ """ import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from tornado.database import Connectio...
DB_PASSWD) @app.after_request def close_connection(response): g.db.close()
return response @app.route("/") def index(): newsitems = g.db.iter("select * from newsitems") return render_template("index.html", newsitems=newsitems) """ {% for item in newsitems %} <h3>{{ item.title }}</h3> {% endfor %} You can get much of the same functionality in SQLAlchemy 0.6 using NamedTuples, with...
from biokbase.workspace.client import Workspace from biokbase.narrative_method_store.client import NarrativeMethodStore from biokbase.userandjobstate.client import UserAndJobState from biokbase.catalog.Client import Catalog from biokbase.service.Client import Client as ServiceClient from biokbase.execution_engine2.exec...
ame == 'execution_engine' or client_name == 'job_service': c = execution_engine2(URLS.execution_engine2, token=token) elif client_name == 'job_service_mock': c = JobServiceMock() else: raise ValueError('Unknown client name "%s"' % client_name) return c class JobServiceMock(): ...
__init__(self): self.client = get('service') def check_job(self, job_id): return self.client.sync_call('narrative_job_mock.check_job', [job_id])[0] def check_jobs(self, params): return self.client.sync_call('narrative_job_mock.check_jobs', [params])[0]
# _*_ coding: utf-8 _*_ import os try: from cStringIO import StringIO # python 2 except ImportError: from io import StringIO # python 3 from collections import OrderedDict import unittest from tornado.escape import to_unicode from tortik.util import make_qs, update_url, real_ip from tortik.util.xml_etree im...
('г', 'd'), ('b', ['2', '1'])])) self.assertIsInstance(qs, str) self.assertEqual(qs, 'z=%D1%8F&%D0%B3=d&b=2&b=1') def test_unicode_params(self): self.assertQueriesEqual( make_qs({'при': 'вет', u'по': u'ка'}), '%D0%BF%D1%80%D0%B8=%D0%B2%D0%B5%D
1%82&%D0%BF%D0%BE=%D0%BA%D0%B0' ) def test_make_qs_comma(self): query_args = {'a': '1,2,3', 'b': 'asd'} self.assertQueriesEqual(make_qs(query_args, '/,'), 'a=1,2,3&b=asd') def test_make_qs_comma_quoted(self): # default value for `safe` parameter of make_qs is '/' so commas ...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
min.salles.items(): msg += "\n " + salle.ident.ljust(20) + " " msg += direc
tion.ljust(10) if salle in chemin.salles_retour and \ chemin.salles_retour[salle]: msg += " (retour " + chemin.salles_retour[salle] + ")" personnage << msg
# Copyright 2008-2015 Nokia Solutions and Networks # # 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...
NormalizedDict(MutableMapping): """Custom dictionary implementation automatically normalizing keys.""" def __init__(self, initial=None, ignore=(), caseless=True, spaceless=True): """Initializes with possible initial value and normalizing spec. Initial values can be either a dictionary or an it...
s with `normalize` method. """ self._data = {} self._keys = {} self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) if initial: self._add_initial(initial) def _add_initial(self, initial): items = initial.items() if hasattr(initial, 'items...
import os from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker metadata = MetaData() def get_sa_db_uri(driver='', username='', password='', host='', port='', database=''): """get SQLAlchemy DB URI: driver://username:password@host:port/database""" assert driv...
river == 'sqlite': # get absolute file path if not database.startswith('/'): db_file = os.path.abspath(database) else: db_file = database db_uri = '%s:///%s' % (driver, db_file) else: db_uri
= ('%s://%s:%s@%s:%s/%s' % (driver, username, password, host, port, database)) return db_uri class DB(object): def __init__(self, db_uri): self.engine = create_engine(db_uri, convert_unicode=True) self.session = scoped_session( sessionmaker(autocommit=False, ...
[-6., -5.], self.evaluate(var1)) def testPrecomputedGradient(self): for dtype in [dtypes.half, dt
ypes.float32, dtypes.float64]: with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) cost = 5 * var0 + 3 * var1 grad_loss = constant_op.constant([42, -42], dtype=dtype) global_step = variables.Varia...
sgd_op = gradient_descent.GradientDescentOptimizer(3.0) opt_op = sgd_op.minimize( cost, global_step, [var0, var1], grad_loss=grad_loss) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(...
# Copyright (C) 2017 Nippon Telegraph and Telephone 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 appli...
ode. IFF_ALLMULTI = 1 << 9 # Receive all multicast packets. IFF_MASTER = 1 << 10 # Master of a load balancing bundle. IFF_SLAVE = 1 << 11 # Slave of a load balancing bundle. IFF_MULTICAST = 1 << 12 # Supports multicast. IFF_PORTSEL = 1 << 13 # Is able to select media type via ifmap. IFF_AUTOMEDIA =...
16 # Driver signals L1 up. (since Linux 2.6.17) IFF_DORMANT = 1 << 17 # Driver signals dormant. (since Linux 2.6.17) IFF_ECHO = 1 << 18 # Echo sent packets. (since Linux 2.6.25) # Private interface flags # from linux/netdevice.h IFF_802_1Q_VLAN = 1 << 0 # 802.1Q VLAN device. IFF_EBRIDGE = 1 <...
""" keyring_demo.py This demo shows how to create a new keyring and enable it in keyring lib. Created by Kang Zhang on 2009-07-12 """ import os KEYRINGRC = "keyringrc.cfg" def load_keyring_by_config(): """This function shows how to enable a keyring using config file """ # create the config file co...
t the keyring lib, the lib will automaticlly load the # config file and load the user defined module import keyring # invoke
the keyring to store and fetch the password try: keyring.set_password("demo-service", "tarek", "passexample") print "password stored sucessfully" except keyring.backend.PasswordSetError: print "failed to store password" print "password", keyring.get_password("demo-service", "tarek") ...
#!/usr/bin/e
nv python from algorithms.sorting.selection_sort import * from __prototype__ import * if __name__ == '__main__': test_all(selection_so
rt)
# Data fitting wrappers with optimized parameters. # # Copyright (C) 2010-2011 Huang Xin # # See LICENSE.TXT that came with this file. from __future__ import division import math import numpy as np import scipy.ndimage as nd from sinusoidfitter import onedsinusoidfit,onedsinusoid from gaussfitter import gaussfit,oned...
= gaborfit(img,params=params,returnfitimage=True,limitedmin=limitedmin,\ limitedmax=limitedmax,minpars=minpars,maxpars=maxpars) return params,img elif return_all: params,errors = gaborfit(img,params=params,return_all=True,limitedmin=limitedmin,\ ...
limitedmax=limitedmax,minpars=minpars,maxpars=maxpars) return params,errors
.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License....
stribute.get_replica_context().all_reduce()` to optimize collective operation performance. Note that these are only hints, which may or may not change the actual behavior. Some options only apply to certain strategy and are ignored by others. One common optimization is to break gradients all-reduce into multip...
tribute.experimental.CollectiveHints( bytes_per_pack=50 * 1024 * 1024) grads = tf.distribute.get_replica_context().all_reduce( 'sum', grads, experimental_hints=hints) optimizer.apply_gradients(zip(grads, vars), experimental_aggregate_gradients=False) ``` - timeout_seconds ```python strat...
from __future__ import print_function import numpy as np from stompy.grid import exact_delaunay, unstructured_grid Triangulation=exact_delaunay.Triangulation from stompy.spatial import robust_predicates def test_gen_intersected_elements(): dt = Triangulation() pnts = [ [0,0], [5,0], ...
assert len(elts)==1 assert elts[0][0]=='edge' def test_gen_int_elts_dim0(): dt = Triangulation() assert len(list(dt.gen_intersected_elements(pA=[-1,0
],pB=[1,0])))==0 dt.add_node(x=[0,0]) assert len(list(dt.gen_intersected_elements(pA=[-1,0],pB=[1,0])))==1 assert len(list(dt.gen_intersected_elements(pA=[-1,0],pB=[1,1])))==0
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop 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.http import JsonRespons...
xt": item.get("sku")}, {"title": "", "text": " ", "raw": item.get("stock_information")}, {"title": "", "text": " ", "raw": item.get("adjust_stock")}, ] def get_queryset(self): return StockCount.objects.filter( supplier__module_identifier="simple_supplier", ...
).order_by("product__id") def get_context_data(self, **kwargs): context = super(PicotableListView, self).get_context_data(**kwargs) context["toolbar"] = None context["title"] = _("Stock management") return context def get_stock_information(self, instance): return get_st...
import os import psutil import sys __all__ = [ 'BeerProgress' ] _default_display = { 'cpu': True, 'mem': True, 'progressbar': True, 'percent': True, 'tasks_ratio': True, 'skipped_tasks': True, 'fd_count': True, 'context_switches': True } class BeerProgress(object): def __in...
completed_tasks(self, completed_tasks): self._completed_tasks = completed_tasks @property def total_tasks(self): return self._total_tasks @total_tasks.setter def total_tasks(self, total_tasks): self._tot
al_tasks = total_tasks @property def skipped_tasks(self): return self._skipped_tasks @skipped_tasks.setter def skipped_tasks(self, skipped_tasks): self._skipped_tasks = skipped_tasks def print_progress(self, same_line=True, stream=sys.stderr): if same_line: str...
import random import sys sys.setrecursionlimit(7000) def selection_sort(array, counter): for i in range(0,len(array)): min_val = array[i:len(array)+1][0] for j in array[i:len(array)+1]: counter += 1 if j < min_val: min_val = j k = array[i:len(array)+...
ut_list) while opt_input.upper() != 'Q': print_menu() opt_input = raw_input("Enter an option from the menu above: ") input_list = list(og_list) counter = 0 if opt_input.upper() == 'A': array = selection_sort(input_list, counter) print_list(array) ...
elif opt_input.upper() == 'B': array = insertion_sort(input_list, counter) print_list(array) elif opt_input.upper() == 'C': array = quick_sort_random(input_list, counter) print_list(array) elif opt_input.upper() == 'D': array = quick_sort_firs...
# Copyright Amazon
.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Contains common test fixtures used to run unit tests. """ import sys # This is needed so Python can find test_tools on the path
. sys.path.append('../../..') from test_tools.fixtures.common import *
ing the # output of the standard diff tool, parsing it into separate changes, then # ignoring changes that are know to be safe, such as adding or removing # blank lines, etc... # Option('gen', 'IDL generated files', default='hdir') Option('src', 'Original ".h" files', default='../c') Option('halt', 'Stop if a differen...
: match = True for j in range(cnt): if last.now[i] != next.was[(i + j) % cnt]: match = False break; if match: return True return False def FilterLinesIn(output): was = [] now = [] filter = [] for index in range(len(output)): filter.append(False) line = o...
[index] if len(line) < 2: continue if line[0] == '<': if line[2:].strip() == '': continue was.append((index, line[2:])) elif line[0] == '>': if line[2:].strip() == '': continue now.append((index, line[2:])) for windex, wline in was: for nindex, nline in now: if filter[nin...
# Problem B # Small dataset # O = G = V = 0. (Each unicorn has only one hair color in its mane.) def solve(N, R, Y, B): res = "" imp = "IMPOSSIBLE " if sum((R,Y,B)) == 0:
return "" if max(R,Y,B) > N//2 : return imp
if (R==Y) and (Y==B): return "RYB"*R elif (R==Y) and (B == 0): return "RY"*R elif (R==B) and (Y == 0) : return "RB"*R elif (Y==B) and (R == 0) : return "YB"*Y arr = [["R",R],["Y",Y],["B",B]] arr.sort(key=lambda x:x[1], reverse=True) sum_arr = lambda x : x[0][...
# -*- coding: utf-8 -*- from __fu
ture__ import ( absolute_import, division, print_function,
unicode_literals )
class InvalidUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): ...
def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.p...
return rv class Conflict(Exception): status_code = 409 def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(se...
"""Tests for the frequency module in analysis""" import pytest from lantern.analysis import frequency def test_frequency_analyze(): """Testing frequency analyze works for ngram = 1""" assert frequency.frequency_analyze("abb") == {'a': 1, 'b': 2} def test_frequency_analyze_bigram(): """Testing frequenc...
ef test_index_of_coincidence(): """T
esting index of coincidence for a piece of text""" assert frequency.index_of_coincidence("aabbc") == 0.2 def test_index_of_coincidence_multiple_texts(): """Testing index of coincidence with multiple texts""" assert frequency.index_of_coincidence("aabbc", "abbcc") == 0.2 def test_index_of_coincidence_non...
ep 03 12:00:00 2016 Aims ---- - normalization Notes ----- This is migrated from **SLAM** package """ from __future__ import division import numpy as np from joblib import Parallel, delayed from .extern.interpolate import SmoothSpline def normalize_spectrum(wave, flux, norm_range, dwave, p...
) * (flux > 0.) else: ind_good_init = 1. * (flux > 0.) ind_good_init = ind_good_init.astype(np.bool) # print("@Cham: sum(ind_good_init)", np.sum(ind_good_init)) flux_smoothed1 = SmoothSpline(wave[ind_good_init], flux[ind_good_init], p=p[0], va
r=var[ind_good_init])(wave) dflux = flux - flux_smoothed1 # collecting continuum pixels --> ITERATION 1 ind_good = np.zeros(wave.shape, dtype=np.bool) for i_bin in range(n_bin): ind_bin = np.logical_and(wave > wave1 + (i_bin - 0.5) * dwave, wave <= wave1 + (i_bi...
#!/usr/bin/env python import json import optparse import os import subprocess import sys import tempfile CHUNK_SIZE = 2**20 DEFAULT_DATA_TABLE_NAME = "bowtie_indexes" def get_id_name( params, dbkey, fasta_description=None): # TODO: ensure sequence_id is unique and does not already appear in location file se...
n( filename ).read() ) target_directory = params[ 'output_data' ][0]['extra_files_path'] os.mkdir( target_directory ) data_manager_dict = {} dbkey = options.fasta_dbkey if dbkey in [ None, '', '?' ]: raise Exception( '"%s" is not a valid dbkey. You must specify
a valid dbkey.' % ( dbkey ) ) sequence_id, sequence_name = get_id_name( params, dbkey=dbkey, fasta_description=options.fasta_description ) # build the index build_bowtie_index( data_manager_dict, options.fasta_filename, params, target_directory, dbkey, sequence_id, sequence_name, data_table_name=options....
# -*- coding: utf-8 -*- from psycopg2 import IntegrityError from openerp.addons.mail.tests.common import TestMail class TestMailFollowers(TestMail): def setUp(self): super(TestMailFollowers, self).setUp() Subtype = self.env['mail.message.subtype'] self.mt_mg_def = Subtype.create({'name':...
id'), self.user_employee.partner_id) self.assertEqual(self.group_pigs.message_follower_ids.mapped('channel_id'), self.env['mail.channel']) follower = self.env['mail.followers'].search([
('res_model', '=', 'mail.channel'), ('res_id', '=', self.group_pigs.id), ('partner_id', '=', self.user_employee.partner_id.id)]) self.assertEqual(len(follower), 1) self.assertEqual(follower.subtype_ids, self.default_group_subtypes) def test_followers_subtypes_specified(...
# Copyright 2019 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, ...
rrently # being minimized. Create a special token combiner that adds these # portions of the test to the combined tokens. if token.token_type == HTMLMinimizer.Token.TYPE_HTML: curr
ent_minimizer = chunk_minimizer.ChunkMinimizer( self.test_function, chunk_sizes=HTMLMinimizer.CHUNK_SIZES[level], token_combiner=token_combiner, tokenizer=current_tokenizer, **self.kwargs) else: current_minimizer = js_minimizer.JSMi...
[[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]], [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]], [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]], [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]], [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0...
-0.33333333 0.33333333 -0.33333333\n' ' -0.33333333 -0.33333333 -0.33333333\n' '8\n4\n0\n2\n4\n0\n4\n0\n2\n5\n0\n4\n0\
n3\n4\n0\n' '4\n0\n3\n5\n0\n4\n1\n2\n4\n1\n4\n1\n2\n5\n1\n4\n' '1\n3\n4\n1\n4\n1\n3\n5\n1\n') allcg_str = allcg.__str__() self.assertTrue('\n#=======================================================#\n' '# List of coordination geo...
f
rom AsynMongo import Collection
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_osm_find_first ---------------------------------- Tests for `osm-find-first` module. """ import unittest import tempfile import re import httpretty import osm_find_first def v(string): return string.format(version=osm_find_first.__version__) class Test...
retty.activate def testEmptyDoesNothing(self
): httpretty.register_uri(httpretty.GET, re.compile( "http://api.openstreetmap.org/api/0.6/(node|way|relation)/[0-9]+/1"), body='<osm><relation id="1" uid="123" user="testuser" timestamp="2000-01-01 115:24:02"></relatio...
# Python - 3.6.0 Test.assert_equals(cube_checker(-12,2), False) Test.assert_equals(cube_checker(8, 3), False) Test.assert_equals(cube_checker(8, 2), True) Test.assert_equals
(cube_checker(-8,-2), False) Test.assert_equals(cube_checker(0, 0), False) Test.assert_equals(
cube_checker(27, 3), True) Test.assert_equals(cube_checker(1, 5), False) Test.assert_equals(cube_checker(125, 5),True) Test.assert_equals(cube_checker(125,-5),False) Test.assert_equals(cube_checker(0, 12), False) Test.assert_equals(cube_checker(12, -1),False) Test.assert_equals(cube_checker(1, 1), True)
print nodes[node] result.append((node, node)) return result def do_disable_host(self, host): status, data = self._request("POST", "execute", body={'command': 'disable_host', 'args': {'host': host}}) return data def _load_filters(self): return CO...
rced_hosts_str = ', '.join(forced_hosts) msg = _LI('Host filter forcing available hosts to %s') else: forced_hosts_str = ', '.join(hosts_to_force) msg = _LI("No hosts matched due to not matching "
"'force_hosts' value of '%s'") LOG.info(msg % forced_hosts_str) def _match_forced_nodes(host_map, nodes_to_force): forced_nodes = [] for (hostname, nodename) in list(host_map.keys()): if nodename not in nodes_to_force: ...
odule. (Ripped from coursera-dl) TODO: Convert to Hy and make generic. """ import logging import os import ssl import tempfile import getpass import requests from requests.adapters import HTTPAdapter try: # Workaround for broken Debian/Ubuntu packages? (See issue #331) from requests.packages.urllib3.poolmanager...
class.coursera.org. To access the class pages we need two cookies on class.coursera.org: csrf_token, session """ # First, chec
k if we already have the .coursera.org cookies. if session.cookies.get('CAUTH', domain=".coursera.org"): logging.debug('Already logged in on accounts.coursera.org.') else: login(session, username, password, class_name=class_name) try: session.cookies.clear('class.coursera.org', '/' ...
from .settings import info class get_settings: def __init__(self): self.settings = info() self.repo = self.settings['repo'] self.repo_path = self.repo['repo_path'] self.repo_url = self.repo['repo_url'] self.key = self.repo['ssh_key'] self.slack = self.settings['slack...
rl) de
f repo_path(self): return(self.repo_path) def ssh_key(self): return(self.key) def slack(self): return(self.slack) def slack_token(self): return(self.slack_token)
""" * Copyright (c) 2012-2017, Nic McDonald and Adriana Flores * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, t...
ITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROF...
N ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. """ import codecs import re import os import sys try: from setuptools import setup except: print('please install setuptools via pip:') print(' pip3 install setuptools') sys.exit(-1) def find_version(*file_paths):...
maj
or =
0 minor = 37 patch = 0
import json from requests import Request, Session class Requester: @staticmethod def verifyconnection(url="http://google.com"): return Requester.request(url, method='GET', decode=False) @staticmethod def request(url, method=None, data=None, decode=True): if not url.startswith('http://...
url.startswith('https://'): url = 'http://' + url request = Request(method, url) if data: request.data = json.dumps(data) with Session() as session: prepped = session.prepare_request(request) try: response = session.send(prepped...
return False if decode: return json.loads(response.text) else: return response
# # Copyright (C) 2000 Stephen Davies # Copyright (C) 2000 Stefan Seefeld # All rights reserved. # Licensed to the public under the terms of the GNU LGPL (>= 2), # see the file COPYING for details. # from Synopsis.Processor import Parameter from Synopsis import FileTree from Synopsis.Formatters.HTML.View import View f...
de (file or directory).""" if isinstance(node, FileTree.File): # Leaf node ref = rel(self.filename(), self.directory_layout.file_index(node.path)) text = href(ref, node.filename, target='detail') self.write('<li>%s</li>'%
text) return # Non-leaf node children = node.children children.sort(self._node_sorter) if len(node.path): self.write('<li>%s<ul class="tree">'%node.filename+os.sep) if len(children): for child in children: self.process_file_tree_node(child) if l...
=['GET']) @login_required def past(): # render past events if not g.user.is_editor(): flash(mustBeStudentCoord[0],mustBeStudentCoord[1]) return redirect(url_for('index')) allusers = Users.query.order_by(Users.lname.asc()) events = Opps.query.filter(Opps.date < datetime.now()).order_...
'email']: flash('Please enter an email address.','danger') elif not re.match(r"(.*@gcc\.edu)", request.form['email']): flash('Please enter a valid GCC email address.','danger')
elif not re.match(r"(\d{6})", request.form['gccid']): flash('Please enter a valid GCC ID number','danger') elif request.form['password'] != request.form
#!/usr/bin/python ############################################################################### # Module Writen to OpenERP, Open Source Management Solution # Copyright (C) OpenERP Venezuela (<http://www.vauxoo.com>). # All Rights Reserved ######################################################################...
U Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ###############################################################################
{ "name": "Costing Method Settings", "summary": "Set product default cost method", "version": "1.6", "author": "Vauxoo", "website": "http://www.vauxoo.com/", "category": "Settings", "depends": [ "purchase", ], "data": [ "wizard/res_config_view.xml" ], "demo": ...
com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: ...
ert source is None. (2) if `client_options.client_cert_source` is provided, use the provided one; if the default client cert source exists, use the default one; otherwise the client cert source is None. The API endpoint is determined in the following order: (1) if `client_option...
, use the default mTLS endpoint; if the environment variabel is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. More details can be found at https://google.aip.dev/auth/4114. A...
#!/usr/bin/env python # # ----------------------------------------------------------------------------- # Copyright (C) 2015 Daniel Standage <daniel.standage@gmail.com> # # This file is part of tag (http://github.com/standage/tag) and is licensed # under the BSD 3-clause license: see LICENSE. # ------------------------...
m tag import select from tag import transcript from gzip import open as gzopen import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions def open(filename, mode): if mode not in ['r', 'w']: raise ValueError('invalid mode "{}"'.format(m
ode)) if filename in ['-', None]: # pragma: no cover filehandle = sys.stdin if mode == 'r' else sys.stdout return filehandle openfunc = builtins.open if filename.endswith('.gz'): openfunc = gzopen mode += 't' return openfunc(filename, mode)
SECRET_KEY = 'secret' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', ...
"}, "CONFIG_RELOAD_
INTERVAL": 0, # Always reload settings } LOGIN_URL = "django_auth_adfs:login" LOGIN_REDIRECT_URL = "/"
# -*- coding:utf-8 -*- from django.db import models # Create your models here. class UserType(models.Model): display = models.CharField(max_length=50) def __unicode__(self): return self.display class Admin(models.Model): username = models.CharField(max_length=50) password = models.Cha...
= True) user_type = models.ForeignKey('UserType') def __unicode__(self): return self.username class Chat(models.Model): content = models.TextField() user = models.ForeignKey('Admin') create_date = models.DateTimeField(auto_now_add = True) def __unicode__(self): ...
return self.content class NewType(models.Model): display = models.CharField(max_length=50) def __unicode__(self): return self.display class News(models.Model): title = models.CharField(max_length=30) summary = models.CharField(max_length=256) url = models.URLField() ...
import serial,time,socket import hart_protocol import sys port = 3 if len(sys.argv) < 4: print "Error, usage " + sys.argv[0] + " port long_address new_longtag"
print "Usage hex string (5 hex digits) as address and LATIN-1 string as new long tag" quit() address = sys.argv[2].decode('hex') if len(address) != 5: print "Error, address should be 5 bytes long!" longtag = sys.ar...
gv[1]) - 1 print "Opening COM" + str(port + 1) + "..." preambles = 10 delimiter = '\x82' # master command with long address command = '\x16' # write long tag ln = 32 # long address exact length pack = delimiter + address + command + chr(ln) + longtag packet = '\xff' * preambles + pack + hart_protocol.get_...
# Linktastic Module # - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems # # Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic. # # The MIT License (MIT) # Copyright (c) 2012 Solipsis Development # # Permission is here...
s.check_output( 'cmd /C mklink /J %s %s' % (_escape_param(dest), _escape_param(src)), stderr=subprocess.STDOUT, startupinfo=i
nfo) except CalledProcessError as err: raise IOError(err.output.decode('utf-8')) # TODO, find out what kind of messages Windows sends us from mklink # print(stdout) # assume if they ret-coded 0 we're good def _junctionlink_windows(src, dest): try: subprocess.check_output( ...
from ailment.expression import UnaryOp from .base import PeepholeOptimizationExprBase class RemoveRedundantNots(Peepho
leOptimizationExprBase): __slots__ = () name = "Remove redundant Nots" expr_classes = (UnaryOp, ) # all expressions are allowed def optimize(self, expr: UnaryOp): # Not(Not(expr)) ==> expr if expr.op == "Not" \ and isinstance(expr.operand, UnaryOp) \ a...
d.operand return None
rom_request() command = json_get_str(self.body, NKeys.COMMAND, required=True) log.debug(f"NLPRP request received from {self.request.remote_addr}: " f"username={self.username}, command={command}") if DEBUG_SHOW_REQUESTS: log.debug(f"Request: {self.body!r}") r...
essor_data } if process_request.include_text: doc_result[NKe
ys.TEXT] = text results.append(doc_result) response_info = { NKeys.CLIENT_JOB_ID: process_request.client_job_id, NKeys.RESULTS: results, } return self.create_response(status=HttpStatus.OK, extra_info=response_info) def...
import urllib.parse from wptserve.utils import isomorphic_encode def main(request, response): """Handler that causes multiple redirections. Redirect chain is as follows: 1. Initial URL containing multi-redirect.py 2. Redirect to cross-origin URL 3. Redirect to same-origin URL 4. Fin...
"&tao_steps=" + isomorphic_encode(str(next_tao_steps)) redirect_url_path += b"&step=" if tao_
steps > 0: response.headers.set(b"timing-allow-origin", tao_value) if step == 1: # On the first request, redirect to a cross origin URL redirect_url = cross_origin + redirect_url_path + b"2" elif step == 2: # On the second request, redirect to a same origin URL redirect_...
from flask_login import LoginManager from server.users.models import User login_manager = Log
inManager() @login_manager.user_loader def load_user
(user_id): return User.get(user_id=user_id)
that type, then return True # this is used in db_query to check if permission on DocType if verbose: print "Has a shared document" return True return False role_permissions = get_role_permissions(meta, user=user, verbose=verbose) if not role_permissions.get(ptype): return false_if_not_shared() i...
["User"]] for ptype in rights: if p.get(ptype): perms["user_permission_doct
ypes"].setdefault(ptype, []).append(user_permission_doctypes) else: user_permission_doctypes = get_linked_doctypes(meta.name) # if atleast one record having both Apply User Permission and If Owner unchecked is found, # don't match for those rights for ptype in rights: if ptype in dont_match: if...
from
playerGst im
port *
or showing a rendered image derived from a Legend. """ class RenderThread(Thread): def __init__(self, plugin, size, handler): super().__init__() self.plugin = plugin self.size = size self.handler = handler def run(self): wx.PostEvent(self...
ze()) self.legend_image.fit = False main_sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(main_sizer) main_sizer.Add(self.legend_image, 0, wx.EXPAND | wx.BOTTOM, 0) self.legend_image.Bind(wx.EVT_LEFT_DOWN, self.OnLef
tDown) self.legend_image.Bind(wx.EVT_MOTION, self.OnMotion) self.legend_image.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.legend_image.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnCaptureLost) self.legend_image.Bind(wx.EVT_RIGHT_DOWN, self.OnRightClick) self.Bind(wx.EVT_PAINT, self.OnPain...
import random def prio(): action_lst = [] lim
= 1000 for _ in range(lim): k = rando
m.randint(1, 201) action_lst.append(k) return action_lst
__author__ = 'Tom' import pickle import urllib2 import os import pymel.core as pm import project_data as prj reload(prj) class updater(): def __init__(self): self.master_url = 'https://raw.githubusercontent.com/tb-animator/tbtools/master/' self.realPath = os.path.realpath(__file__) self.ba...
win.set_label(fileName) try: self.copy_from_url(url, local_dir) except: print "skipping", url win.finish_bar() pm.optionVar(floatValue=('tb_version', self.project_info.version) ) class updaterWindow(): def __init__(self): self.pr...
.text(self.file_text, edit=True, label=text) def step_bar(self,): pm.progressBar(self.progress_bar, edit=True, step=1) def finish_bar(self): max_value = pm.progressBar(self.progress_bar, query=True, maxValue=True) pm.progressBar(self.progress_bar, edit=True, maxValue=max_value) ...
import pymongo import getpass import os import base64 import ConfigParser import sys from database import * from pymongo.errors import DuplicateKeyError db, logger = None, None def setup_config(args): '''Saves MongoDB settings to a configuration file''' config = ConfigParser.SafeConfigParser() config.a...
enter the settings for your MongoDB server:' config.set('MongoDB', 'host', args.host or raw_i
nput('Host [localhost]: ') or 'localhost') config.set('MongoDB', 'port', args.port or raw_input('Port [27017]: ') or '27017') config.set('MongoDB', 'database', args.database or raw_input('Database [cssscl]: ') or 'cssscl') #config.set('MongoDB', 'username', args.username or raw_input('Username [none]: ')) ...
# Copyright 2011-2018 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later ve
rsion. import os from urllib.parse import quote_plus from gi.repository import Gtk import quodlibet from quodlibet import _ from quodlibet import qltk from quodlibet.formats import AudioFile from quodlibet.pattern import Pattern from quodlibet.plugins.songsmenu import So
ngsMenuPlugin from quodlibet.qltk import Icons from quodlibet.qltk.cbes import StandaloneEditor from quodlibet.qltk.x import SeparatorMenuItem from quodlibet.util import connect_obj, print_w, print_d from quodlibet.util import website from quodlibet.util.path import uri_is_valid from quodlibet.util.tags import USER_TAG...
# coding=utf-8 # Copyright 2017 Christopher Bartz <bartz@dkrz.de> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with th
e 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, s
oftware # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .server import app
import django_filters from django.contrib.auth import get_user_model from .models import Sprint, Task User = get_user_model() class NullFilter(django_filters.BooleanFilter): """Filter on a field set as null or not.""" def filter(self, qs, value): if va
lue is not None: return qs.filter(**{'%s__isnull' % self.name: value}) return qs class SprintFilter(django_filters.FilterSet): end_min = django_filters.DateFilter(name='end', lookup_type='gte') end_max = django_filters.DateFilter(name='end', lookup_type=
'lte') class Meta: model = Sprint fields = ('end_min', 'end_max', ) class TaskFilter(django_filters.FilterSet): backlog = NullFilter(name='sprint') class Meta: model = Task fields = ('sprint', 'status', 'assigned', 'backlog', ) def __init__(self, *args, **kwargs): ...
from lxml import etree import sys REQUEST_BODY_PART_1 = '<![CDATA[actualEvent=' REQUEST_BO
DY_PART_2 = '&queryEmail=' REQUEST_BODY_PART_3 = ']]>' CONTENT_TYPE = 'Content-type: application/x-www-form-urlencoded'
def usage(): print "python create_test_case [URL]"\ " [EVENT_NAME] [AMOUNT_CASES] [TEST_CASE_FILENAME]" def main(): if len(sys.argv) != 5: usage() root = etree.Element('testcases') url = sys.argv[1] event = sys.argv[2] amount_cases = int(sys.argv[3]) test_case_filename = s...
from dja
ngo.
apps import AppConfig class ReqsConfig(AppConfig): name = 'reqs'
import sys import os import importlib import glob # Imoprt and instantiate each Cmd object. _this_dir = os.path.dirname(__file__) _this_mod = os.path.basename(_this_dir)
def build_cmds(sub_parser): cmd_objs = {} imlist = glob.glob(os.path.join(_this_dir, "*.py")) imlist.remove(os.path.join(_this_dir, "__init__.py")) imlist.remove(os.path.join(_this_dir, "base.py")) imlist = [os.path.basename(x) for x in imlist] imlist = [os.path.splitext(x)[0] for x in imlist...
print("Found Command: ", mod.Cmd.name) cmd_objs[mod.Cmd.name] = mod.Cmd(sub_parser) cmd_objs[mod.Cmd.name].build() # end for im in imlist # print(cmd_objs) return cmd_objs #build_cmds()
"" if protocol is None: protocol = ssl.PROTOCOL_SSLv23 ctx = _SSLContext(protocol) ctx.load_cert_chain(cert_file, pkey_file) return ctx class _SSLContext(object): '''A dummy class with a small subset of Python3's ``ssl.SSLContext``, only intended to be used with and by Werkzeug.''' ...
ion is running from within the Werkzeug reloader subprocess. .. versionadded:: 0.10 """ return os.environ.get('WERKZEUG_RUN_MAIN') == 'true' def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_in...
er_type='auto', threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): """Start a WSGI application. Optional features include a reloader, multithreading and fork support. This function has a command-line interface too...
r), KeyValue(key = 'Output', value = stdout) ] return diag_vals, diag_msgs, diag_level tmp = stdout.strip() if unicode(tmp).isnumeric(): temp = float(tmp) / 1000 diag_vals.append(KeyValue(key = 'Core %d Temp' % index, value = str(temp))) ...
ck.format_exc())) return level, load_dict[level], vals # Add msgs output ##\brief Uses 'free -m' to check free memory def check_memory(): values = [] level = DiagnosticStatus.OK msg = '' mem_dict = { 0: 'OK', 1: 'Low Memory', 2: 'Very Low Memory' } try: p = subprocess.Popen('free -m'...
stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) stdout, stderr = p.communicate() retcode = p.returncode if retcode != 0: values.append(KeyValue(key = "\"free -m\" Call Error", value = str(retcode))) return Diagnosti...
des the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing whenever possible. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and i...
and not sort_keys and not item_sort_key and not for_json and not ignore_nan and int_as_stri
ng_bitcount is None and not kw ): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding...
ware: 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 project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without...
tClass(fg, 'was-validated') e
rrors = set(['invalid-%s' % e for e in errors]) for feedback in fg.find_elements_by_css_selector('.invalid-feedback'): classes = set(self.get_classes(feedback)) if errors & classes: self.assertTrue(feedback.is_displayed(), '.%s is not displayed' % ('.'.join(classes))) ...
# Copyright 2013 IBM Corp. # # 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 t...
response = self._do_post('servers/%s/action' % self.uuid, 'lock-server', {}) self.assertEqual(response.status, 202) def test_post_unlock_server(self): # Get api
samples to unlock server request. self.test_post_lock_server() response = self._do_post('servers/%s/action' % self.uuid, 'unlock-server', {}) self.assertEqual(response.status, 202)
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
ABLE 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== """Python Cryptography Toolkit A collec...
key (AES, TDES, Salsa20, ChaCha20, CAST, Blowfish, ARC4) and public-key encryption (RSA PKCS#1) algorithms Crypto.Hash Hashing algorithms (SHA-1, SHA-2, SHA-3, BLAKE2, HMAC, MD5) Crypto.IO Encodings useful for cryptographic data (PEM, PKCS#8) Crypto.Protocol Cryptographic protocols (key derivation functions, Shamir'...
# Part of Odoo. See LICENSE file for full copyright and licensing details. from openerp import _, api, fields, models class Job(models.Model): _inherit = "hr.job" _name = "hr.job" _inherits = {'mail.alias': 'alias_id'} @api.model def _default_address_id(self): return self.env.user.compan...
2many( 'hr.recruitment.stage', 'job_stage_rel', 'job_id', 'stage_id', 'Job Stages', default=[(0, 0, {'name': _('New')})]) document_ids = fields.One2many('ir.attachment', compute='_compute_document_ids', string="Applications") documents_count = fields.Integer(compute='_compute_document_id...
or this job position and you will be able to print/answer this interview from all applicants who apply for this job") alias_id = fields.Many2one( 'mail.alias', "Alias", ondelete="restrict", required=True, help="Email alias for this job position. New emails will automatically create new applicants fo...
""" Wire-level packet handling """ from mysqlproxy.types import FixedLengthInteger, \ FixedLengthString, LengthEncodedInteger, \ RestOfPacketString from mysqlproxy import capabilities from StringIO import StringIO __all__ = [ 'PacketMeta', 'IncomingPacketChain', 'OutgoingPacketChain', 'Packet',...
Integer(2, self.warnings)) ] eli
f transactions: self.fields.append(('status_flags', FixedLengthInteger(2, self.status_flags))) ok_message = kwargs.pop('info', 'k thanks') self.fields.append(('ok_message', RestOfPacketString(ok_message))) class ERRPacket(Packet): """ Error packet """ def __init__(self, cap...
import time import requests from .exceptions import HttpError from .json import json_loads def check_rep(rep): if (rep.status_code // 100) != 2: raise HttpError(rep.text, rep.status_code) def rep_to_json(rep): check_rep(rep) # we use our json loads for date parsing return json_loads(rep.tex...
n=True): rep = getattr(self.session, http_method.lower())( f"{self.base_url}/{path}/{resource_id}/{action_name}/", para
ms=params, json=data if send_json else None, data=None if send_json else data, verify=self.verify_ssl ) if rep.status_code == 204: return if return_json: return rep_to_json(rep) check_rep(rep) return rep.content de...
' Walk the new directories list and make sure that permissions are as we would expect ''' if new_directory_list: working_dir = os.path.join(pre_existing_dir, new_directory_list.pop(0)) directory_args['path'] = working_dir changed = module.set_fs_attributes_if_different(directory_arg...
fact_extension = extension[0] if extension else '' if artifact_classifier == artifact.classifier and artifact_extension == artifact.extension: return self._uri_for_artifact(artifact, snap
shotArtifact.xpath("value/text()")[0]) return self._uri_for_artifact(artifact, artifact.version.replace("SNAPSHOT", timestamp + "-" + buildNumber)) return self._uri_for_artifact(artifact, artifact.version) def _uri_for_artifact(self, artifact, version=None): if artifact.is_snapshot() a...
from sqlalchemy import Column, Integer, String, Text, Boolean, ForeignKey from sqlalchemy.orm import relationship from database.main import Base class CreatureTemplateSchema(Base): """ This table holds the information about each creature in the game entry - the unique ID of this creature creature_nam...
e_id - the id of the loot this creature drops (in the loot_table table) gossip - the text this creature says when he is talked to (if applicable) respawnable - whether this creature will respawn on different g
ame starts. Ex: Some special creatures should not be killed more than once Example: entry, creature name, type, level, hp, mana, armor, min_dmg, max_dmg, quest_relation_ID, loot_table,ID, gossip, respawnable 1, Zimbab, "monster" 1, 10, 10, 50, 2, 4 ...
import sys, datetime import elasticsearch INDEX = 'cli' DOC_TYPE = 'cli' def create_elasticsearch_index(es): """es should be an elasticsearch.Elasticsearch instance""" es.indices.create(index = INDEX, ignore = 400) # ignore already existing index es.indices.put_mapping(index = INDEX, doc_type = DOC_TYPE, ...
tor": { "type" : "string",
"index" : "not_analyzed" }, "authors": { "type" : "string", "index" : "not_analyzed" }, "license": { "type" : "string", "index" : "not_analyzed" }, ...
from cobra.model.aaa import User, UserDomain from createLocalUser import input_key_args as input_local_user from createMo import * def input_key_args(msg='\nPlease Specify User Domain:'): print msg return input_raw_input("User Domain Name", required=True) def add_user_domain(parent_mo, user_domain): ""...
ription='User Domain') super(AddSecurityDomain, self).delete_mo() def main
_function(self): self.check_if_mo_exist('uni/userext/user-', self.local_user, User, 'User') add_user_domain(self.mo, self.user_domain) if __name__ == '__main__': user_domain = AddSecurityDomain()
#! /usr/bin/python import base64 import sys f = open(sys.argv[1], "r") items = [] for line in f.readlines(): if len(line.strip()) == 0: continue if line
[0] == "{": items.append(base64.b64encode(line.strip())) else: items.append(line.strip()) pri
nt ".".join(items)
#!/usr/bin/env python # # test_doctests.py - test runner for COT doctests # # July 2016, Glenn F. Matthews # Copyright (c) 2016-2017 the COT project developers. # See the COPYRIGHT.txt file at the top-level directory of this distribution # and at https://github.com/glennmatthews/cot/bl
ob/master/COPYRIGHT.txt. # # This file is part of the Common OVF Tool (COT) proje
ct. # It is subject to the license terms in the LICENSE.txt file found in the # top-level directory of this distribution and at # https://github.com/glennmatthews/cot/blob/master/LICENSE.txt. No part # of COT, including this file, may be copied, modified, propagated, or # distributed except according to the terms conta...
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions describe...
-------------------- # Does something after some specified time interval: #------------------------------------------------------------------------------- def do_after ( interval,
callable, *args, **kw_args ): """ Does something after some specified time interval. """ DoLaterTimer( interval, callable, args, kw_args )
# # ident/geoio.py # # Copyright (C) 2011 Damien Churchill <damoxc@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # Thi...
@hook def connect(self, connection): country = self.gi.country_code_by_addr(connection.remote_ip)
connection.notes['geoip_country'] = country
version. # # Arx Libertatis is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public Lice...
range(ftsHeader.nb_anchors): anchor = FAST_ANCHOR_DATA.from_buffer_copy(data, pos) pos += sizeof(FAST_ANCHOR_DATA) if anchor.nb_linked > 0: LinkedAnchorsArrayType
= c_int32 * anchor.nb_linked linked = LinkedAnchorsArrayType.from_buffer_copy(data, pos) pos += sizeof(LinkedAnchorsArrayType) anchors.append( ((anchor.pos.x, anchor.pos.y, anchor.pos.z), linked) ) else: anchors.append( ((anchor.pos.x, anchor....
"""Web dashboard.""" import os import sys import json import aiohttp from discord.ext import commands import util.dynaimport as di from .cog import Cog japronto = di.load('japronto') sanic = di.load('sanic') response = di.load('sanic.response') root_dir = os.path.dirname(os.path.abspath(sys.modules['__main__'].core_fi...
self.logger = self.logger.getChild('web')
self.port = 8085 self.host = '127.0.0.1' self.app = None self.server = None self.server_task = None if bot.user: self.loop.create_task(self.start()) def __unload(self): self.guild_task.cancel() async def on_ready(self): await self.start() ...
lues, it attempts to de-serialize the value. If it fails, then it fallsback to treating the value as a string. >>> C = Cookie.SmartCookie() >>> C["number"] = 7 >>> C["string"] = "seven" >>> C["number"].value 7 >>> C["string"].value 'seven' >>> C.output() 'Set-Cookie: number="I7\\012."\r\nSe...
342', '\343' : '\\343', '\344' : '\\344', '\345' : '\\345', '\3
46' : '\\346', '\347' : '\\347', '\350' : '\\350', '\351' : '\\351', '\352' : '\\352', '\353' : '\\353', '\354' : '\\354', '\355' : '\\355', '\356' : '\\356', '\357' : '\\357', '\360' : '\\360', '\361' : '\\361', '\362' : '\\362', '\363' : '\\363', '\364' : '\\364', '\365' : '\\365', '\36...
""" drslib exceptions """ class Tr
anslationError(Exception):
pass
alues for nodes to be shut d
own. :type ids: Sequence :param by_user: Requesting user. :type by_user: User_ :return: Those Nodes for which shutdown was actually requested. :rtype: list """ nodes = self.get_nodes(by_user, NODE_PERMISSION.EDIT, ids=ids) processed_nodes = [] for ...
= node.get_effective_power_parameters() node_power_type = node.get_effective_power_type() # WAKE_ON_LAN does not support poweroff. if node_power_type != POWER_TYPE.WAKE_ON_LAN: power_off.apply_async( queue=node.work_queue, args=[node_power_type], ...
other available options: ({})".format( options_hr))) elif options == "any" or r in options: answer = r else: await self.bot.send_message( user, cf.warning( ...
imit of responses. Re
quires that <reprompt> is set. Deadline should be of a sane time format, date optional, but timezone abbreviation is strongly recommended (otherwise UTC is assumed). For example: [p]startsurvey everyone channel_name "Question here. Which should be enclosed in double quotes because it includes SPACES" "...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime import applications.discount.models class Migration(migrations.Migration): dependencies = [ ('discount', '0005_auto_20160507_2145'), ] operations = [ migrations.Alter...
3a\u043e\u043d\u0447\u0430\u043d\u0438\u044f \u0430\u043a\u0446\u0438\u0438'), ), migrations.AlterField( model_name='action', name='datetime_start', field=models.DateTimeField(default=datetime.datetime.now, verbose_name='\u0414\u0430\u0442\u0430 \u043d\u0430\u0447\u04...
model_name='action', name='name', field=models.CharField(default=applications.discount.models.default_action_name, max_length=256, verbose_name='\u041d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u0430\u043a\u0446\u0438\u0438'), ), ]
#!/usr/bin/env python3 # # Script for polling N64/GC SI bus devices # # This script uses the serial bridge and pool in loops # for the buttons status. # # It currently supports N64 controllers, N64 mouses & GameCube controllers. # # --Jacques Gagnon <darthcloud@gmail.com> # from bus import Bus from collections import ...
B_AUTH: interface.wavebird_init(device['id']) try: while 1: device = interface.identify() ti
me.sleep(0.02) status = interface.status(device['system']) for field, values in BUTTON[device['system']].items(): for value in values: if value.mask != 0xFF: print("{}{}{} ".format(value.color if getattr(status, field) & value.mask else DGRAY, value.name, END), end=''...