prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/python import sys, os import tornado.ioloop import tornado.web import logging import logging.handlers import re from urllib import unquote import config from vehiclenet import * reload(sys) sys.setdefaultencoding('utf8') def deamon(chdir = False): try: if os.fork() > 0: os._exit(0) except OSError,...
if config.Mode == 'DEBUG': routes.append((r"/log", LogHandler)) application = tornado.web.Application(routes, **settings) if __name__ == "__main__": if '-d' in sys.argv: deamon() logdir = 'logs' if not os.path.exists(logdir): os.make
dirs(logdir) fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' formatter = logging.Formatter(fmt) handler = logging.handlers.TimedRotatingFileHandler( '%s/logging' % logdir, 'M', 20, 360) handler.suffix = '%Y%m%d%H%M%S.log' handler.extMatch = re.compile(r'^\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}') h...
"""映射 集合 ... 高级数据结构类型""" from string import Template val_dict = {1: 'a', 2: 'b', 3: 'c'} print(val_dict) print(val_dict.keys()) print(val_dict.items()) print(val_dict.values()) factory_dict = dict((['x', 1], ['y', 2])) print(factory_dict) ddcit = {}.fromkeys(('x', 'y',
'z'), -24) ddcit.update(val_dict) # 新值覆盖旧值 print(ddcit) print(ddcit.get("m", "no such key ")) print(ddcit.setdefault('x', "new value ")) print(type(ddcit.keys())) for key in ddcit.keys(): s = Template("key is ${key} and value is ${value}") # 不加 key 和 value 就出错了 为什么 print(s.substitute(key=key, value=ddci...
# 键成员关系操作 print(1 in strange_dict) # strange_dict = {var_tuple: 11, 1: 'abcd', var_list: 'acv'} # 语法上没错误,但是 会包 unhashable type: 'list' 错误 所有基于 dict 的操作都会报错误 # 因为 check key 是否 hashable 的合法性 print(strange_dict[var_tuple]) # print(strange_dict[var_list]) # strange_dict.pop(var_list) strange_dict.pop(var_tuple) strange...
# test seasonal.adjust_seasons() options handling # # adjust_seasons() handles a variety of optional arguments. # verify that adjust
_trend() correctly calledfor different option combinations. # # No noise in this test set. # from __future__ import division import numpy as np from seasonal import fit
_trend, adjust_seasons # pylint:disable=import-error from seasonal.sequences import sine # pylint:disable=import-error PERIOD = 25 CYCLES = 4 AMP = 1.0 TREND = AMP / PERIOD LEVEL = 1000.0 SEASONS = sine(AMP, PERIOD, 1) DATA = LEVEL + np.arange(PERIOD * CYCLES) * TREND + np.tile(SEASONS, CYCLES) ZEROS = np.zeros(PERIOD...
i = 1 stringio.write('<iframe name="invisibleiframe" style="display:none;"></iframe>\n') stringio.write("<h3>") stringio.write(os.getcwd()) stringio.write("<br>\n") stringio.write(submission.title) stringio.write("</h3>\n\n") stringio.write('<form action="copydisplaytoclipboard.html" me...
stringio.write('<input type="submit" name="actiontotake" value="Reply with sorry-too-late comment">') stringio.write('<input type="submit" name="actiontotake" value="Skip comment">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">') stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">') stringio.write('<input type="hidden" name="bodyencodedformlcorpus" value="' + b64encode(comment.body.en...
class Solution: # @pa
ram n, an integer # @return an integer def reverseBits(self, n): reverse = 0 r = n for i in range(32): bit = r % 2 reverse += bit << (32-i-1) r = r / 2
return reverse s = Solution() r = s.reverseBits(43261596) print(r)
import unittest from rsync_usb.ChunkLocation import ChunkLocation class ChunkLocationTests(unittest.TestCase): '''Test TargetHashesWriter and TargetHashesReader''' def testProperties(self): pos = ChunkLocation('dummy', 100, 10) self.assertEqual(pos.path, 'dummy') self....
str(pos_b), str(pos_a))) def testNoOverlapBefore(self): pos_a = ChunkLocation('du
mmy', 10, 10) pos_b = ChunkLocation('dummy', 100, 10) self.assertNotOverlaping(pos_a, pos_b) def testNoOverlapAfter(self): pos_a = ChunkLocation('dummy', 1000, 10) pos_b = ChunkLocation('dummy', 100, 10) self.assertNotOverlaping(pos_a, pos_b) def testNoOverlapD...
# (c) 2013, Serge van Ginderachter <serge@vanginderachter.be> # # This file is part of Ansible # # Ansible 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)...
if subkey == subelements[-1]: lastsubkey = True if not subkey in subvalue: if skip_missing: continue else: raise AnsibleError("could not find '%s' key in iterated item '%s'" % (subkey, subvalu...
f skip_missing: continue else: raise AnsibleError("the key %s should point to a dictionary, got '%s'" % (subkey, subvalue[subkey])) else: subvalue = subvalue[subkey] else: # lasts...
#!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2010 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/...
in front of your service to validate that requests are
coming from a trusted component that has handled authenticating the call. If a call comes from an untrusted source, it will redirect it back to be properly authenticated. This is done by sending our a 305 proxy redirect response with the URL for the auth service. The auth service settings are specified in the INI fil...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Client module for connecting to and interacting with SmartyStreets API """ import json import numbers import requests from .data import Address, AddressCollection from .exceptions import SmartyStreetsError, ERROR_CODES def validate_args(f): """ Ensures that...
candidates that may not be deliverable :param logging: boolean to allow SmartyStreets to log requests :param accept_keypair: boolean to toggle default keypair behavior :param truncate_addresses: boolean to silently truncate address lists in excess of the
SmartyStreets maximum rather than raise an error. :param timeout: optional timeout value in seconds for requests. :return: the configured client object """ self.auth_id = auth_id self.auth_token = auth_token self.standardize = standardize self.invalid = inval...
from i3pystatus.playerctl import Pla
yerctl class Spotify(Playerctl): """ Get Spotify info using playerctl. Based on `Playerctl`_ module. """ player_name =
"spotify"
from xblock.fields import Scope class CourseGradingModel(object): """ Basically a DAO and Model combo for CRUD operations pertaining to grading policy. """ # Within this class, allow access to protected members of client classes. # This comes up when accessing kvs data and caches during kvs saves ...
turn model @staticmethod def f
etch_grader(course_location, index): """ Fetch the course's nth grader Returns an empty dict if there's no such grader. """ course_old_location = loc_mapper().translate_locator_to_location(course_location) descriptor = get_modulestore(course_old_location).get_item(course_...
# Copyright 2017 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...
= get_wrapper(_test_function) export_decorator = tf_export.tf_export('nameA', 'nameB') exported_function = export_decorator(decorated_function) self.assertEquals(decorated_function
, exported_function) self.assertEquals(('nameA', 'nameB'), _test_function._tf_api_names) if __name__ == '__main__': test.main()
ol_mode_zone, text='Broad', variable=self.tol_mode, value='broad', command=self.change_tol_mode) # command=lambda: self.event_generate('<<update_all_graphs>>')) self.tol_mode_broad.grid(row=0, column=1, sticky=W) self.tol_mode_stct = Radiobutton( self.tol_...
', command=self.open_horizontal_file) self.open_menu.add_command(label='Vertical...', command=self.open_vertical_file) self.primary_menu.add_cascade(label='Open Data File', menu=self.open_menu) ...
r() self.primary_menu.add_command(label='Load Smoothing Values...', command=self.open_sp, state=DISABLED) self.primary_menu.add_command(label='Save Smoothing Values...', command=self.save_sp...
deque_2), random_sample_size) unique_random_sample_keys = {(a, b + offset) for a, b in random_sample_keys} return [(data_1[k1], data_2[k2]) for k1, k2 in blocked_sample_keys | unique...
ock_learner.learn(dupes, recall=1.0)
self._cached_labels = None self._old_dupes = dupes def candidate_scores(self): if self._cached_labels is None: labels = self.predict(self.candidates) self._cached_labels = numpy.array(labels).reshape(-1, 1) return self._cached_labels def predict(sel...
#!/usr/bin/env python2 from gimpfu import * import time import re def preview (image, delay, loops, force_delay, ignore_hidden, restore_hide): if not image: raise "No image given." layers = image.layers nlayers = len (layers) visible = [] length = [] i = 0 while i < nlayers: ...
f each frame", 100), (PF_INT32, "loops", "The number of times to loop the animation", 1), (PF_BOOL, "force-delay", "Force the default length on every frame", 0), (PF_BOOL, "ignore-hidden", "Ignore currently hidden items", 0), (PF_BOOL, "restore-hide", "Restore the hidden status after pre...
view, menu = "<Image>/Filters/Animation") main()
# coding: utf-8 """ Provides functions for finding and testing for locally `(k, l)`-connected graphs. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)\nDan Schult (dschult@colgate.edu)""" # Copyright (C) 2004-2015 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <sw...
t off the while loop while deleted_some: deleted_some=False for edge in H.edges(): (u,v)=edge ### Get copy of graph needed for this search if low_memory:
verts=set([u,v]) for i in range(k): [verts.update(G.neighbors(w)) for w in verts.copy()] G2=G.subgraph(list(verts)) else: G2=copy.deepcopy(G) ### path=[u,v] cnt=0 accept=0 while ...
) assert connection.session_id == -1 # ################## conn_msg = ConnectMessage( connection ) session_id = conn_msg.prepare( ("root", "root") )\ .send().fetch_response() assert session_id == connection.session_id assert session_id != -1 try: ...
are( (db_name, "admin", "admin", DB_TYPE_GRAPH, "") ).send().fetch_response() assert len(cluster_info) != 0 try: create_class = CommandMessage(connection) cluster = create_class.prepare((QUERY_CMD, "create class my_class " ...
"extends V"))\ .send().fetch_response()[0] except PyOrientCommandException: # class my_class already exists pass # classes are not allowed in record create/update/load rec = { '@my_class': { 'alloggio': 'casa', 'lavoro': 'ufficio', 'vacanza': 'mare...
# -*- coding: utf-8 -*- # Copyright 2017, Digital Reasoning # # 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...
under the License. # from __future__ import unicode_literals cl
ass InvalidFormula(Exception): pass class InvalidFormulaComponent(InvalidFormula): pass
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Download and build the data if it does not exist. from parlai.core.build_data import DownloadableFile import parlai.co...
RCES: downloadable_file.download_file(dpath) # Mark the data as built. build_dat
a.mark_done(dpath, version_string=version)
# -*- coding: UTF-8 -*- from django.conf import settings as dsettings from django.contrib.auth import models as authModels from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.http import HttpResponse, Http404 from django.shortcuts import render, render_to_response, get_object_or_404 from dja...
deration import moderate if not moderate(request, 'trackback', t['title'], url=t['url']): return failure('moderated') content.new_trackback(**t) return success() @render_json def _comment_count(request, content): post = content.post if settings.MICROBLOG_COMMENT == 'comment': impor...
content_type=ContentType.objects.get_for_model(post), object_pk=post.id, is_public=True ) return q.count() else: import httplib2 from urllib import quote h = httplib2.Http() params = { 'forum_api_key': settings.MICROBLOG_COMMENT_DI...
#!/usr/bin/env python import os import numpy as np import math import fnmatch from my_spectrogram import my_specgram from collections import OrderedDict from scipy.io import wavfile import matplotlib.pylab as plt from pylab import rcParams from sklearn.model_selection import train_test_split rcParams['figure.figsize']...
window=np.hanning(NFFT), noverlap=noverlap, cmap='Greys', xextent=None, pad_to=None, sides='default', scale_by_freq=None,
minfreq=freq_min, maxfreq=freq_max) plt.axis(axis) im.axes.axis('tight') im.axes.get_xaxis().set_visible(False) im.axes.get_yaxis().set_visible(False) if plotpath: plt.savefig(plotpath, bbox_inches='tight', transparent=False, pad_inc...
b' not in self.override_flags: self.argparser.add_argument('-b', '--doublequote', dest='doublequote', action='store_true', help='Whether or not double quotes are doubled in the input CSV file.') if 'p' not in self.override_flags: self.argparser.add_argumen...
er def print_column_names(self): """ Pretty-prints the names and indices of all columns to a file-like object (usually sys.stdout). """ if self.args.no_header_row: raise RequiredHeaderError, 'You cannot use --no-header-row with the -n or --names options.' f = se...
zero_based=self.args.zero_based except: zero_based=False rows = CSVKitReader(f, **self.reader_kwargs) column_names = rows.next() for i, c in enumerate(column_names): if not zero_based: i += 1 output.write('%3i: %s\n' % (i, c)) ...
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Sun OS specific tests. These are implicitly run by test_psutil.py.""" import psutil from test_psutil import * class SunOSSpec...
1:] if not lines: raise ValueError('no swap device(s) configured') total = free = 0 for line in lines: line = line.split() t, f = line[-2:] t = t.replace('K', '') f = f.replace('K', '') total += int(int(t) * 1024) ...
self.assertEqual(psutil_swap.used, used) self.assertEqual(psutil_swap.free, free) def test_main(): test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(SunOSSpecificTestCase)) result = unittest.TextTestRunner(verbosity=2).run(test_suite) return result.wasSuccessful() ...
#!/u
sr/bin/env
python # Blink an LED using the RPi.GPIO library. import RPi.GPIO as GPIO from time import sleep # Use GPIO numbering: GPIO.setmode(GPIO.BCM) # Set pin GPIO 14 to be output: GPIO.setup(14, GPIO.OUT) try: while True: GPIO.output(14, GPIO.HIGH) sleep(.5) GPIO.output(14, GPIO.LOW) ...
#!/usr/bin/python3 import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes") def get_registries(): registries = [] directories = os.listdir...
ent: wrong_path = os.path.join(os.path.dirname(__file__), 'error.reg') with open(wrong_path, 'w') as wrong_reg: wrong_reg.write(content) print("Content of parsed registry doesn't match: {}".format(registry_path)) subprocess.call(["meld", registry_path, wrong_path]) s...
ry(registry) print("All {} registry files validated!".format(len(registries)))
from __future__ import print_function from numpy import pi, arange, sin import numpy as np import time from bokeh.browserlib import view from bokeh.document import Document from bokeh.embed import file_html from bokeh.models.glyphs import Circle from bokeh.models import ( Plot, DataRange1d, DatetimeAxis, Colu...
range(len(x)) * 3600000 + time.time() source = ColumnDataSource( data=dict(x=x, y=y, times=times) ) xdr = DataRange1d(sources=[source.columns("times")]) ydr = DataRange1d(sources=[source.columns("y")]) plot = Plot(x_range=xdr, y_range=ydr, min_border=80) circle = Circle(x="times", y="y", fill_color="red", size=...
s(PanTool(), WheelZoomTool()) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "dateaxis.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Date Axis Example")) print("Wrote %s" % filename) view(filename)
import numpy as np from square import Squ
are from constants import SQUARE_SIZE, BOARD_SIZE class ChessboardFrame(): def __init__(self, img): self.img = img def square_at(self, i): y = BOARD_SIZE - ((i / 8) % 8) * SQUARE_SIZE - SQUARE_SIZE x = (i % 8) * SQUARE_SIZE ret
urn Square(i, self.img[y:y+SQUARE_SIZE, x:x+SQUARE_SIZE, :])
cl
ass Solution(object): def removeKdigits(self, num, k): """ :type num: str :type k: int :rtype: str """ stack = [] length = len(num) - k for c in num: while k and stack and stack[-1] > c: stack.pop() k -= 1 ...
or '0'
""" Manage the TVTK scenes. """ # Enthought library imports. from tvtk.pyface.tvtk_scene import TVTKScene from pyface.workbench.api import WorkbenchWindow from traits.api import HasTraits, List, Instance, Property from traits.api import implements, on_trait_change from tvtk.plugins.scene.scene_editor import SceneEdito...
ic trait change handler. """ if isinstance(new, SceneEditor): self.scenes.append(new.scene) return @on_trait_change('window:editor_closing') def _on_editor_closed(self, obj, trait_name, old, new): """ Dynamic trait change handler. """ if isinstance(new, SceneEdito...
elf, obj, trait_name, old, new): """ Dynamic trait change handler. """ if isinstance(new, SceneEditor): self.current_scene = new.scene else: self.current_scene = None return #### EOF ######################################################################
#! /usr/bin/env
python import sys g = {} n = {} f
or line in sys.stdin: (n1, n2, p, q, t, tg, x) = line.strip().split(' ') t = int(t) x = float(x) key = ' '.join((n1,n2,p,q)) if not key in n: n[key] = 0 g[key] = 0 n[key] += t g[key] += x*t for key in n: print key, n[key], g[key]/n[key]
ete>',self.remove_filter) flsb.config(command=self.node_list.yview) flsb.grid(row=r, column=4, sticky='NWS') r += 1 tk.Button(self, text='Clear',command=self.remove_filter).grid( row=r, column=1, sticky='W') tk.Button(self, text='?', command=self.filter_help ...
_build_menu() def _build_menu(self): self.menubar = tk.Menu(self) self.config(menu=self.menubar) view = tk.Menu(self.menubar, tearoff=0) view.add_command(label='Undo', command=self.canvas.undo, accele
rator="Ctrl+Z") self.bind_all("<Control-z>", lambda e: self.canvas.undo()) # Implement accelerator view.add_command(label='Redo', command=self.canvas.redo) view.add_separator() view.add_command(label='Center on node...', command=self.center_on_node) view.add_separator() ...
ory_id)[0]['isthing'] if not is_thing: continue ids_with_ann.append(item['image_id']) ids_with_ann = set(ids_with_ann) valid_inds = [] valid_img_ids = [] for i, img_info in enumerate(self.data_infos): img_id = self.img_ids[...
d(record) pan_json_results = dict(annotations=pred_annotations) return pa
n_json_results def results2json(self, results, outfile_prefix): """Dump the panoptic results to a COCO panoptic style json file. Args: results (dict): Testing results of the dataset. outfile_prefix (str): The filename prefix of the json files. If the prefix ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # ================================================================= # ================================================================= # NOTE: notify message MUST follow these rules: # # - Messages must be wrappered with _() for translation # # - Replacement va...
(_("Stop of virtual machine {instance_name} on host " "{host_name} was successful.")) STOP_ERROR = (_("Stop of virtual machine {instance_name} on host " "{host_name} failed with exception: {error}")) RESTART_SUCCESS = (_("Restart of v
irtual machine {instance_name} on host " "{host_name} was successful.")) RESTART_ERROR = (_("Restart of virtual machine {instance_name} on host " "{host_name} failed with exception: {error}")) LPM_SUCCESS = (_("Migration of virtual machine {instance_name} from host " ...
""" WSGI config for crowd_server project. It exposes the WSGI callable as a module-level variable named ``a
pplication``. Fo
r more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crowd_server.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
# -*- coding: utf-8 -*- # author: Alfred import os import re DB_MODULE_PATTERN = re.compile(r'db2charts_models\.(?P<module>.*)_models') class DB2ChartsRouter(object): def db_for_module(self, module): match = DB_MODULE_PAT
TERN.match(module) if match: return match.groupdict()['module'] return None def db_for_read(self, model, **hints): return self.db_for_module(model.__module__) def db_for_write(self, model, **hints): return self.db_for_module(model.__module__) def allow_migrate(...
n False
rror Occured', 500: 'A Serverside Error Occured Handling the Request.', } # Some Phone Number Detection IS_PHONE_NO = re.compile(r'^\+?(?P<phone>[0-9\s)(+-]+)\s*$') # Priorities class D7SMSPriority(object): """ D7 Networks SMS Message Priority """ LOW = 0 MODERATE = 1 NORMAL = 2 HIGH ...
fy.' self.logger.warning(msg) raise TypeError(msg) return def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): """ Depending on whether we are set to
batch mode or single mode this redirects to the appropriate handling """ # error tracking (used for function return) has_error = False auth = '{user}:{password}'.format( user=self.user, password=self.password) if six.PY3: # Python 3's versio of ...
os from mule_local.JobGeneration import * from mule.JobPlatformResources import * from . import JobPlatformAutodetect def _whoami(depth=1): """ String of function name to recycle code https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html Returns ------- string ...
turn content def jobscript_get_exec_prefix(jg : JobGeneration): """ Prefix before executable Returns ------- string multiline text for scripts """ content = "" content += jg.runtime.get_jobscript_plan_exec_prefix(jg.compile, jg.runtime) content += """ EXEC=\""""+jg...
jobscript_get_exec_command(jg : JobGeneration): """ Prefix to executable command Returns ------- string multiline text for scripts """ p = jg.parallelization mpiexec = "" # # Only use MPI exec if we are allowed to do so # We shouldn't use mpiexec for validation sc...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<lang>[a-z]{2})?$', views.index, name='index'), url(r'^sign/$', views.sig
n, name='sign'), url(r'^c
onfirm/([0-9a-z]{64})/$', views.confirm, name='confirm'), ]
: None, }, 'spEnable': False, 'spParams': { # SP diagnostic output verbosity control; # 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, 'globalInhibition': 1, # Number of cell columns in the cortical region (same numb...
BySubExperiment', 'errorMetric': 'fillInBySubExperiment' } # end of config dictionary # Adjust base config dictionary for any modifications if imported from a # sub-experiment updateConfigFromSubConfig(config) # Compute predictionSteps based on the predictAheadTime and the aggregation # period, which may be permu...
not None: predictionSteps = int(round(aggregationDivide( config['predictAheadTime'], config['aggregationInfo']))) assert (predictionSteps >= 1) config['modelParams']['clParams']['steps'] = str(predictionSteps) # Adjust config by applying ValueGetterBase-derived # futures. NOTE: this MUST be called after ...
se: return self._value() ops.register_tensor_conversion_function( StagedModelVariable, StagedModelVariable._TensorConversionFunction) # pylint: disable=protected-access class StagedVariableGetter(object): """A variable getter through staging buffers on devices. Instead of a caching device, this gett...
as_nan_or_inf_list.append(has_nan_or_inf) if check_inf_nan: return agg_grads, tf.reduce_any(has_nan_or_inf_list) else: return agg_grads, None # The following two functions are copied from # tensorflow/python/eager/backprop.py. We do not directly use them as they are # not exported a
nd subject to change at any time. def flatten_nested_indexed_slices(grad): assert isinstance(grad, ops.IndexedSlices) if isinstance(grad.values, ops.Tensor): return grad else: assert isinstance(grad.values, ops.IndexedSlices) g = flatten_nested_indexed_slices(grad.values) return ops.IndexedSlices(...
# Copyright 2017 AT&T Intellectual Property. All other 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...
, as well as additional request information. """ def __init__(self, project=None, **kwargs): if project: kwargs['tenant'] = project self.project = project super(RequestContext, self).__init__(**kwargs) def to_dict(self): out_dict = super(RequestContext, self).to...
ut_dict @classmethod def from_dict(cls, values): return cls(**values) def get_context(): """A helper method to get a blank context (useful for tests).""" return RequestContext(user_id=None, project_id=None, roles=[], ...
2, blank=True)), ('estudantes_pos', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('bolsistas_pibic', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('bolsistas_ppq', self.gf('django.db.models.fields.IntegerField')(max_length...
'estudantes': ('django.db.models.fields.IntegerField', [], {'max_length': '3'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'multicampia': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'nivel'
: ('django.db.models.fields.CharField', [], {'max_length': '11'}), 'tipo': ('django.db.models.fields.CharField', [], {'max_length': '11'}) }, 'cadastro.docente': { 'Meta': {'object_name': 'Docente'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'Tru...
ams) return estimator def log_and_get_hooks(eval_batch_size): """Convenience function for hook and logger creation.""" # Create hooks that log information about the training and metric values train_hooks = hooks_helper.get_train_hooks( FLAGS.hooks, model_dir=FLAGS.model_dir, batch_size=FLAGS...
epsilon, "match_mlperf": flags_obj.ml_perf, "use_xla_for_gpu": flags_obj.use_xla_for_gpu, "epochs_between_evals": FLAGS.epochs_between_evals, }
def main(_): with logger.benchmark_context(FLAGS), \ mlperf_helper.LOGGER(FLAGS.output_ml_perf_compliance_logging): mlperf_helper.set_ncf_root(os.path.split(os.path.abspath(__file__))[0]) run_ncf(FLAGS) def run_ncf(_): """Run NCF training and eval loop.""" if FLAGS.download_if_missing and not ...
#!/usr/bin/env python # coding:utf-8 vi:et:ts=2 # parabridge persistent settings module. # Copyright 2013 Grigory Petrov # See LICENSE for details. import xmlrpclib import socket import sqlite3 import uuid import info SQL_CREATE = """ CREATE TABLE IF NOT EXISTS task ( guid TEXT UNIQUE, name TEXT UNIQUE, ...
ne: return False mArgs[ 'guid' ] = oRow[ 'guid' ] oRet = oConn.execute( SQL_TASK_DEL_BY_NAME, mArgs ) if
0 == oRet.rowcount: raise Exception( "Consistency error" ) oConn.execute( SQL_INDEX_LAST_DEL, mArgs ) return True finally: self.notifyIfNeeded() def taskList( self ): with sqlite3.connect( info.FILE_CFG ) as oConn: try: oConn.row_factory = sqlite3.Row ...
from bt_proximity import BluetoothRSSI import time import sys import datetime #//////////////////////////////// BT_ADDR = 'xx:xx:xx:xx:xx:xx'#/// Enter your bluetooth address here! #//////////////////////////////// # ----------------------- DO NOT EDIT ANYTHING BELOW THIS LINE --------------------------- # def ...
# initialize array of records count = 0 # initialize count addr = BT_ADDR # assign BT_ADDR num = 10 # amount of records to be recorded while(count < num): ...
r=addr) time_e = time_diff(start_time) # get seconds elapsed record = (btrssi.get_rssi(), time_e) # create record records.append(record) # add record to records array count += 1 time.sleep(.5) # wai...
from Screens.Screen import Screen from Components.ActionMap import ActionMap from Components.Label import Label from Plugins.Plugin import PluginDescriptor def getUpgradeVersion(): import os try: r = os.popen("fpupgrade --version").read() except IOError: return None if r[:16] != "FP update tool v": return No...
self["actions"] = ActionMap(["OkCancelActions"], { "ok": self.ok, "cancel": self.close, }) def ok(self): self.close(4) class SystemMessage(Screen): skin = """ <screen position="150,200" size="450,200" title="System Message" > <widget source="text" position="0,0" size="450,200" font="Regular;20" ha...
5" size="53,53" alphatest="on" /> </screen>""" def __init__(self, session, message): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self["text"] = StaticText(message) self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.ok, }) def ok(self): self...
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 la...
RANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import sys import pwd from django.db import transaction from django.contrib.auth.models import User as DjangoUser from storageadmin.models import User from system im...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include from django.conf.urls import url from django.contrib import admin from django.views.i18n import JavaScriptCatalog from demo.apps.app import application js_info_dict = { 'package...
oolbar’s URLs to the project’s URLconf import debug_toolbar urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls)), ] # In DEBUG mode, serve media files through Django. from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views import static urlpatterns += s...
es_urlpatterns() # Remove leading and trailing slashes so the regex matches. media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += [ url(r'^%s/(?P<path>.*)$' % media_url, static.serve, {'document_root': settings.MEDIA_ROOT}), ]
""" The Netio switch component. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.netio/ """ import logging from collections import namedtuple from datetime import timedelta import voluptuous as vol from homeassistant.core import callback from home...
s']) DEVICES = {} MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) REQ_CONF = [CONF_HOST, CONF_OUTLETS] URL_API_NETIO_EP = '/api/netio/{host}' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.str
ing, vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_OUTLETS): {cv.string: cv.string}, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set ...
#!/usr/bin/env python3.7 from multiprocessing import Process import time import os from printerState import main as printerStateMain from server import main as serverMain from websocket import main as websocketServerMain servicesTemplate = { 'server': { 'name': 'Server', 'run': serverMain, ...
= se
lf.services[serviceName]['process'].is_alive() if(self.services[serviceName]['running']): servicesRunning.append(self.services[serviceName]['name']) else: servicesStopped.append(self.services[serviceName]['name']) if(len(servicesStopped) != 0): ...
nd(OPEN_COMMAND) # epub 열기 def on_post_save(self, view): if not get_setting('auto_save'): return view.run_command(SAVE_COMMAND) # epub 저장 ### ### TextCommand ### class EpubMakerOpenCommand(sublime_plugin.TextCommand): def is_enabled(self): return is_valid_format(self.view.file_name()) def run(self, edit...
ublime-settings') SETTINGS['new_window'] = settings.get('new_window', True) SETTINGS['auto_save'] = settings.get('auto_save', False) SETTINGS['require_confirm_save'] = settings.get('require_confirm_save', False) SETTINGS['overwite_original'] = settings.get('overwite_original', True) SETTINGS['backup_original'] = s...
e) SETTINGS['backup_extension'] = settings.get('backup_extension', 'back') # workpath: 할당된 작업 경로 def create_sublime_project(workpath): if not os.path.exists(workpath): return None else: projectpath = get_sumblime_project_path(workpath) with codecs.open(projectpath, 'w', 'utf-8') as project: project.write(j...
# ========================================================================== # # Copyright NumFOCUS # # 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/...
vector_float_type = itk.VariableLengthVector[itk.F] vector3 = vector_float_type(n_channels) vector4 = vector_float_type(n_channels) assert len(vector
3) == n_channels and len(vector4) == n_channels vector3.Fill(0.5) for idx in range(n_channels): vector4.SetElement(idx, 0.1 * idx) float_sum = vector3 + vector4 print(f'float sum: {float_sum}') tolerance = 1e-6 for idx in range(n_channels): diff = abs(float_sum[idx] - (0.5 + 0.1 * idx)) print(f'float sum...
""" Support for python 2 & 3, ripped pieces from six.py "
"" import sys PY3 = sys.versio
n_info[0] == 3 if PY3: string_types = str, else: string_types = basestring,
# Author: Pontus Laestadius. # Since: 2nd of March, 2017. # Maintai
ned since: 17th of April 2017. from receiver import Receiver print("Version 2.2")
Receiver("172.24.1.1", 9005)
################################################################################ # # # Copyright (C) 2010,2011,2012,2013,2014, 2015,2016 The ESPResSo project # # ...
orientation_z=0, outer_radius=orad, inner_radius=irad, width=2.0, opening_angle=angle, ...
ollow_cone) ################################################################################ # Output the geometry lbf.print_vtk_boundary("{}/boundary.vtk".format(outdir)) ################################################################################
def process(target, other): result = [[] for ch in target] ret = [] for xi, xv
in enumerate(target): for yi, yv in enumerate(other): if xv != yv: result[xi].append(0) elif 0 == xi or 0 == yi: result[xi].append(1) else: result[xi].append(result[xi-1][yi-1]+1) ret.append(max(result[xi])) return r...
# print "POS: ", pos flag = True for other in sub_map: # print l, other[pos] if l <= other[pos]: flag = False break if flag: return l def solve(n, word_list): for (xi, xv) in e...
# -*- coding: utf-8 -*- # # test_enable_multithread.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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...
: nest.SetKernelStatus( { 'local_num_threads': 2 } ) def test_multithread_enable(self): nest.ResetKernel() nest.SetKernelStatus( { 'local_num_threads': 2 } ) # Setting...
iple threads when structural plasticity is enabled should # throw an exception with self.assertRaises(nest.NESTError): nest.EnableStructuralPlasticity() def suite(): test_suite = unittest.makeSuite(TestEnableMultithread, 'test') return test_suite if __name__ == '__main__': un...
from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import xml.etree.ElementTree from xml.etree.cElementTree import ElementTree, Element, SubElement from xml.etree.cElementTree import fromstring, tostring import ...
o") return self.save_xml(self.path) def save_xml(self, path): self.get_tree().write(self.path) def indent_tree(elem, leve
l=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent_tree(elem, level+1) if not elem.tail or not elem.tail.st...
. Usually it is not necessary to read this -- just call GetOptions() which will happily return the default instance. However, it's sometimes useful for efficiency, and also useful inside the protobuf implementation to avoid some bootstrapping issues. """ if _USE_C_DESCRIPTORS: ...
xtensions, options=None, is_extendable=True, extension_ranges=None, oneofs=None, file=None, serialized_start=None, serialized_end=None, syntax=None): # pylint:disable=redefined-builtin """Arguments to __init__() are as described in the description of Descriptor fiel...
nit__( options, 'MessageOptions', name, full_name, file, containing_type, serialized_start=serialized_start, serialized_end=serialized_end) # We have fields in addition to fields_by_name and fields_by_number, # so that:
class
APIConnectionError(Exception): pass class DownloadError(Exce
ption): pass class ProducerAPIError(APIConnectionError): pass class ConsumerAPIError(APIConnectionError): pass
""" A Python interface to the primer3_core executable. TODO: it is not possible to keep a persistent primer3 process using subprocess module - communicate() terminates the input stream and waits for the process to finish Author: Libor Morkovsky 2012 """ # This file is a part of Scrimer. # See LICENSE.t...
PRIMER_OPT_SIZE=18 PRIMER_MIN_SIZE=15 PRIMER_MAX_SIZE=21 PRIMER_MAX_NS_ACCEPTED=1 PRIMER_PRODUCT_SIZE_RANGE=75-100 SEQUENCE_INTERNAL_EXCLUDED_REGION=37,21 """)) default_params = BoulderIO.parse(textwrap.dedent( """ PRIMER
_THERMODYNAMIC_PARAMETERS_PATH=/opt/primer3/bin/primer3_config/ PRIMER_MAX_NS_ACCEPTED=0 PRIMER_EXPLAIN_FLAG=1 """))[0] print "Testing BoulderIO, single record:", record_dp = BoulderIO.deparse(record) record_reparsed = BoulderIO.parse(record_dp) if record == record_reparsed: print ...
import paho.mqtt.client as mqtt import os,binascii import logging import time from enum import Enum from threading import Timer import json import random import math ID_STRING = binascii.hexlify(os.urandom(15)).decode('utf-8')[:4] CLIENT_ID = "robot-emulator-" + ID_STRING BROKER_HOST = "mosquitto" TOPIC_STATUS = "twin...
twins/registration/handshake" class TwinStatus(Enum): NOT_CONNECTED = 1 SEARCHING = 2 SELECTED = 3 CONNECTED = 4 DISCONNECTED = 5 status = TwinStatus.NOT_CONNECTED timer = None def main(): logging.info("Client '%s' is connecting...", CLIENT_ID) # Client(client_id=””, clean_ses
sion=True, userdata=None, protocol=MQTTv311, transport=”tcp”) client = mqtt.Client(CLIENT_ID) client.on_connect = on_connect client.on_message = on_message try: client.connect(BROKER_HOST) logging.info("Client '%s' CONNECTED to '%s'", CLIENT_ID, BROKER_HOST) except Exception as e: ...
import unittest import mock from ...management.resource_servers import ResourceServers class TestResourceServers(unittest.TestCase): def test_init_with_optionals(self): t = ResourceServers(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2)) self.assertEqual(t.client.options.timeo...
k.patch('auth0.v3.management.resource_servers.RestClient') def test_update(self, mock_rc): mock_instance = mock_rc.return_value r = ResourceServers(domain='domain', token='jwttoken') r.update('some_id', {'name': 'TestApi2', 'identifier': 'https://test.com/api2'...
ps://domain/api/v2/resource-servers/some_id', data={'name': 'TestApi2', 'identifier': 'https://test.com/api2'} )
#!/usr/bin/env python # Copyright 2012 Google Inc. All Rights Reserved. """Client actions related to plist files.""" import cStringIO import types from grr.client import actions from grr.client import vfs from grr.lib import plist as plist_lib from grr.lib import rdfvalue from grr.parsers import binplist class ...
def Run(self, args): self.context = args.context self.filter_query = args.query with vfs.VFSOpen(args.pathspec, progress_callba
ck=self.Progress) as fd: data = fd.Read(self.MAX_PLIST_SIZE) plist = binplist.readPlist(cStringIO.StringIO(data)) # Create the query parser parser = plist_lib.PlistFilterParser(self.filter_query).Parse() filter_imp = plist_lib.PlistFilterImplementation matcher = parser.Compile(filte...
atient_relationship, uuid_pk_column from radar.models.logs import log_changes COUNTRIES = OrderedDict([ ('AF', 'Afghanistan'), ('AX', 'Åland Islands'), ('AL', 'Albania'), ('DZ', 'Algeria'), ('AS', 'American Samoa'), ('AD', 'Andorra'), ('AO', 'Angola'), ('AI', 'Anguilla'), ('AQ', 'A...
lands, U.S.'), ('WF', 'Wallis and Futuna'), ('EH', 'Western Sahara'), ('YE', 'Yemen'), ('ZM', 'Zambia'), ('ZW', 'Zimbabwe'), ]) @log_changes class PatientAddress(db.Model, MetaModelMixin): __tablename__ = 'patient_addresses' id = uuid_
pk_column() patient_id = patient_id_column() patient = patient_relationship('patient_addresses') source_group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) source_group = relationship('Group') source_type = Column(String, nullable=False) from_date = Column(Date) to_date = ...
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General ...
, smooth_points, iterations): y_original = y N_data = y.size N = smooth_points N_float = float(N) y = np.empty(N_data + N + N) y[0:N].fill(y_original[0]) y[N:N + N_data] = y_original[0:N_data] y[N + N_data:N_data + N + N].fill(y_original[-1]) y_avg = np.average(y) y_min = np.mi...
#!/usr/bin/env python """ Standaone Rule ============== This is a customer spec, parser and rule and can be run against the local host using the following command:: $ insights-run -p examples.rules.stand_alone or from the examples
/rules directory:: $ ./stand_alone.py """ from __future__ import print_function from collections import namedtuple from insights import get_active_lines, parser, Parser from insights import make_fail, make_pass, rule, run from insights.core.spec_factory import SpecSet, simple_file from insights.parsers.redhat_rel...
yed for rule responses CONTENT = { make_fail: """Too many hosts in /etc/hosts: {{num}}""", make_pass: """Just right""" } class Specs(SpecSet): """ Datasources for collection from local host """ hosts = simple_file("/etc/hosts") @parser(Specs.hosts) class HostParser(Parser): """ Parses the r...
from django.
shortcuts import render from django.template.loader import render_to_string def home(request): context_dict = {} return render(request,'ms2ldaviz/index.html',context_dict) def people(request): context_dict = {} return render(request,'ms2ldaviz/people.html',context_dict) def api(request): conte...
arkdown_str = render_to_string('markdowns/user_guide.md') return render(request, 'markdowns/user_guide.html', {'markdown_str':markdown_str}) def disclaimer(request): markdown_str = render_to_string('markdowns/disclaimer.md') return render(request, 'markdowns/disclaimer.html', {'markdown_str':markdown_str}...
# Speak.activity # A simple front end to the espeak text-to-speech engine on the XO laptop # http://wiki.laptop.org/go/Speak # # Copyright (C) 2008 Joshua Minor # Copyright (C) 2014 Walter Bender # This file is part of Speak.activity # # Parts of Speak.activity are based on code from Measure.activity # Copyright (C) ...
68 -14.65671,6.02702 -30.51431,9.15849 -46.37814,9.15849 -15.86384,0 -31.72144,-3.13147 -46.37815,-9.15849 C 87.257925,210.18832 73.813631,201.27049 62.594594,190.13366 51.375557,178.99684 42.3906,165.64979 36.316616,151.09803"\n' + \ ' style="fill:none;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke...
;stroke-linecap:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />\n' + \ '</svg>\n'
# -*- coding: utf-8 -*- from minheap import minheap class maxheap(minheap): """ Heap class - made of keys and items methods: build_heap, heappush, heappop """ MAX_HEAP = True def __str__(self): return "Max-heap with %s items" % (len(self.heap)) def heapify(self, i): l =...
largest = r if largest != i: self.heap[i], self.heap[largest] = self.heap[largest], self.heap[i] self.heapify(largest) def heappush(self, x): """ Adds a new item x in the heap""" i = len(self.heap) self.heap.append(x) parent = self.parent(i) ...
arent != -1 and self.heap[int(i)] > self.heap[int(parent)]: self.heap[int(i)], self.heap[int(parent)] = self.heap[ int(parent)], self.heap[int(i)] i = parent parent = self.parent(i)
from pygame import Rect from widget import Widget class GridView(Widget): # cell_size (width, height) size of each cell # # Abstract methods: # # num_rows() --> no. of rows # num_cols() --> no. of columns # draw_cell(surface, row, col, rect) # click_cell(row, col, event) def __init__(se...
_size d = 2 * self.margin self.size = (w * ncols + d, h * nrows + d) self.cell_size = cell_size def draw(self, surface): for row in xrange(self.num_rows()): for col in xrange(self.num_cols()): r = self.cell_rect(row, col
) self.draw_cell(surface, row, col, r) def cell_rect(self, row, col): w, h = self.cell_size d = self.margin x = col * w + d y = row * h + d return Rect(x, y, w, h) def draw_cell(self, surface, row, col, rect): pass def mouse_down(self, event): x, y = event.local w, h = self.cell_size W, H...
# -*- coding: utf-8 -*- import logging from chisch.common.retwrapper import RetWrapper import cor
es logger = logging.getLogger('django') def signature_url(request): params_query_dict = request.GET params = {k: v for k, v in params_query_dict.items()} try: url = cores.get_url() excep
t Exception, e: return RetWrapper.wrap_and_return(e) result = {'url': url} return RetWrapper.wrap_and_return(result)
from django.conf.urls import patterns, url from django.views.generic import RedirectView from django.conf import settings from . import views products = r'/products/(?P<product>\w+)' versions = r'/versions/(?P<versions>[;\w\.()]+)' version = r'/versions/(?P<version>[;\w\.()]+)' perm_legacy_redirect = settings.PERMA...
permanent=True )), # redirect deceased Report List URL to Signature report url(r'^report/list$', RedirectView.
as_view( pattern_name='signature:signature_report', query_string=True, permanent=True )), # redirect deceased Daily Crashes URL to Crasher per Day url(r'^daily$', RedirectView.as_view( pattern_name='crashstats:crashes_per_day', query_s...
"""Main
view for geo locator application""" from django.shortcuts import render def index(request): if request.location: location = request.location else: location = None return render(request, "homepage.html", {'lo
cation': location})
# Generated file. Do not edit __author__="drone" from Abs import Abs from And import And from Average import Average from Ceil import Ceil from Cube import Cube from Divide import Divide from Double import Double from Equal import Equal from Even import Even from Floor import Floor from Greaterorequal import Greateror...
rom Half import Half from If import If from Increment import Increment from Lessorequal import Lessorequal from Lessthan import Lessthan from Max import Max from Min import Min from Module import Module from Multiply import Multiply from Negate import Negate from Not import Not from Odd import Odd from One import One f...
Zero __all__ = ['Abs', 'And', 'Average', 'Ceil', 'Cube', 'Divide', 'Double', 'Equal', 'Even', 'Floor', 'Greaterorequal', 'Greaterthan', 'Half', 'If', 'Increment', 'Lessorequal', 'Lessthan', 'Max', 'Min', 'Module', 'Multiply', 'Negate', 'Not', 'Odd', 'One', 'Positive', 'Quadruple', 'Sign', 'Sub', 'Sum', 'Two', 'Zero']...
<commandflush> <status>Pending+Failed</status> <mobile_devices> <mobile_device> <id>1</id> </mobile_device> <mobile_device> <id>2</id> </mobile_device> </mobile_devices> ...
self.jss._url, self._endpoint_path, self.resource_type, self.id_type, str(self._id)]) # pylint: enable=protected-access def save(self): """POST the object to the JSS.""" try: response = self.jss.session.post( self._upload_url, files=self.resource) ...
else: raise MethodNotAllowedError(self.__class__.__name__) if response.status_code == 201: if self.jss.verbose: print("POST: Success") print(response.content) elif response.status_code >= 400: error_handler(PostError, response) ...
from landsc
ape.client.tests.helpers import LandscapeTest from landscape.client.patch import UpgradeManager from landscape.client.upgraders import monitor class TestMonitorUpgraders(LandscapeTest):
def test_monitor_upgrade_manager(self): self.assertEqual(type(monitor.upgrade_manager), UpgradeManager)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ ############################################################################## # Configuration paramete...
t:8080/_ah/stats ############################################################################## # All tricks in this file developed
by Robin Bhattacharyya ############################################################################## import time import os import sys import logging import cPickle import pickle import wsgiref.handlers import datetime path = os.path.dirname(os.path.abspath(__file__)) sys.path = [path]+[p for p in sys.path if not p...
from typing import (Tuple, List) import matplotlib # More info at # http://matplotlib.org/faq/usage_faq.html#what-is-a-backend for details # TODO: use this: https://stackoverflow.com/a/37605654/7851470 matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib.patches import Ellips...
], y=uw_cloud_stars['w_velocity'], x_avg=AVERAGE_POPULATION_VELOCITY_U, y_avg=AVERAGE_POPULATION_VELOCITY_W, x_std=STD_POPULATION_U, y_std=STD_POPULATION_W) draw_subplot(subplot=vw_subplot, xlabel=v_label, ...
d_stars['w_velocity'], x_avg=AVERAGE_POPULATION_VELOCITY_V, y_avg=AVERAGE_POPULATION_VELOCITY_W, x_std=STD_POPULATION_V, y_std=STD_POPULATION_W) figure.subplots_adjust(hspace=spacing) plt.savefig(filename) def draw_subplot(*, ...
#!/usr/bin/python from typing import List, Optional """ 16. 3Sum Closest https://leetcode.com/problems/3sum-closest/ """ def bsearch(nums, left, right, res, i, j, target): while left <= right: midd
le = (left + right) // 2 candidate = nums[i] + nums[j] + nums[middle] if res is No
ne or abs(candidate - target) < abs(res - target): res = candidate if candidate == target: return res elif candidate > target: right = middle - 1 else: left = middle + 1 return res class Solution: def threeSumClosest(self, nums: List[int]...
"""Generate test data for IDTxl network comparison unit and system tests. Generate test data for IDTxl network comparison unit and system tests. Simulate discrete and continous data from three correlated Gaussian data sets. Perform network inference using bivariate/multivariate mutual information (MI)/transfer entropy...
dump(res, open('{0}continuous_results_mte_{1}.p'.format( path, estimator), 'wb')) nw = BivariateTE() for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']: settings['cmi_estimator'] = estimator
res = nw.analyse_network(settings=settings, data=data) pickle.dump(res, open('{0}continuous_results_bte_{1}.p'.format( path, estimator), 'wb')) nw = MultivariateMI() for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']: settings['cmi_estimator'] = estimator res = nw....
import sublime
from . import SblmCmmnFnctns class Spinner: SYMBOLS_ROW = u'←↑→↓' SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' def __init__(self, symbols, view, startStr, endStr): self.symbols = symbols self.length = len(symbols) self.position = 0 self.stopFlag = False self.view = view self.startStr = startStr self.endStr = endStr ...
startStr + self.symbols[self.position % self.length] + self.endStr def start(self): if not self.stopFlag: self.view.set_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER, self.__next__()) sublime.set_timeout(lambda: self.start(), 300) def stop(self): self.view.erase_status(SblmCmmnFnctns.SUBLIME_STATUS_SPIN...
right=u"0cm", text_indent=u"0cm", **{'style:auto-text-indent': u"false"}) doc.insert_style(definition_style, automatic=False) styles['definition'] = definition_style return definition_style def convert_definition_list(node, context): """Convert a list of term/definition pairs to s...
reate a new odf_cell odf_ce
ll = odf_create_cell(cell_type="string", style=cell_style) odf_row.append(odf_cell) # XXX We don't add table:covered-table-cell ! # It's bad but OO can nevertheless load the file morecols = entry.get("morecols") if morecols is not None: mo...
, "MAF", "MDG", "MHL", "MKD", "MLI", "MMR", "MNG", "MAC", "MNP", "MTQ", "MRT", "MSR", "MLT", "MUS", "MDV", "MWI", "MEX", "MYS", "MOZ", "NAM", "NCL", ...
KUW", "LAO", "LAT", "LBA", "LBR", "LCA", "LES", "LIB", "LIE", "LTU", "LUX", "MAD", "MAR", "MAS", "MAW", "MDA", "MDV", "MEX", "MGL",
"MHL", "MKD", "MLI", "MLT", "MNE", "MON", "MOZ", "MRI", "MTN", "MYA", "NAM", "NCA", "NED", "NEP", "NGR", "NIG", "NOR", "NRU", "NZL", "OMA", "PAK", "PAN"...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime import argparse import asyncio def parse_args(): usage = """usage: %prog [options] [hostname]:port ... python3 select_get_poetry3.py port1 port2 port3 ... """ parser = argparse.ArgumentParser(usage) parser.add_argument('port', nargs='+')...
(self.infile.name)) self.infile.write(data) self.transp
ort.write(b'poems') def eof_received(self): print('end of writing') self.infile.close() def main(): addresses = parse_args() eventloop = asyncio.get_event_loop() for address in addresses: host, port = address filename = str(port) + '.txt' infile = open(filenam...
fr
om .design_inputs import *
#!/usr/bin/env python # A bag contains one red disc and one blue disc. In a game of chance a player # takes a disc at rando
m and its colour is noted. After each turn the disc is # returned to the bag, an extra red disc is added, and another disc is # taken at random. # The player... wins if they have taken more blue discs than red discs a # the end of the game. # ------------------------------------------------------------------------ # ...
rob(disc n is blue) = 1/(n + 1) # For n discs, let C_1-C_2-...-C_n be the colors drawn, let i_1,...,i_k be the # indices j such that disk i_j was drawn red. The probability of this event # is (i_1 * ... * i_k)/factorial(n + 1) # We can enumeratively define n_{j,k} to be the aggregate numerator # of all possible draws...
############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Nicolas Bornand # # The licence is in the file __manifest__.py # ########################################...
est_good_client_id(self, oauth_patch): """ Check that if we connect with admin as client_id, access is granted. """ oauth
_patch.return_value = "admin" response = self._send_post({"nothing": "nothing"}) json_result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual( json_result["Message"], "Unknown message type - not processed." )
######################################################################## # # # Anomalous Diffusion # #
# ###########################################
############################# import steps.interface ######################################################################## # Create Model from steps.model import * from steps.geom import * from steps.rng import * from steps.sim import * from steps.saving import * from steps.visual import * import time mdl = Mod...
from PySide.QtCore import * from PySide.QtGui import * from PySide.QtUiTools import * import plugin.databaseConnect as database from datetime import datetime class sendMessageUI(QMainWindow): def __init__(self, id = None, bulk = None, parent = None): QMainWindow.__init__(self,None) self.setMinimum...
dowTitle("Message") self.parent = parent self.id = id self.bulk = bulk self.UIinit() def UIinit(self): loader = QUiLoader() form = loader.load("resources/UI/sendMessage.ui",None) self.setCentralWidget(form) #QPushButton self.send_button = for...
#LineEdit self.to_user = form.findChild(QLineEdit,"to") self.message = form.findChild(QTextEdit,"message") #Connect self.send_button.clicked.connect(self.sendMes) self.close_button.clicked.connect(self.closeWindow) if(self.id != None): self.to_user.setTex...
break = j while prev_break == len(cps) or prev_break != 0 and not cps[prev_break][1]: prev_break -= 1 next_break = min(j + 1, len(cps)) while next_break != len(cps) and not cps[next_break][1]: next_break += 1 break_t...
t::text::prev_{4}{3}_break(cps.begin(), cps.begin() + {0}, cps.end()){5} - cps.begin(), {1}); EXPECT_EQ(boost::text::next_{4}{3}_break(cps.begin() + {1}, cps.end()){5} - cps.begin(), {2}); '''.format(j, prev_break, next_break, prop_, prop_prefix, call_suffix) break_tests += ' }\n\n'
cpp_file = open('{}_break_{:02}.cpp'.format(prop_, i), 'w') cpp_file.write(break_test_form.format(prop_, break_tests, i)) def contains_surrogate(cps): for cp in cps: if int(cp[0], 16) == 0xD800: return True return False def generate_iterator_tests(cps_and_breaks, prop_): ...
#!/usr/bin/env python path="/var/lib/gpu/gpu_locked.txt" import os,sys import as
t import socket def getHost(): return socket.gethostname() def getlocked(): hostname=getHost() #print path fp=open(path, "r") info=fp.read() #print info
d=ast.literal_eval(info) #print len(d) print "%s,nvidia0,%d" % (hostname, (9999 - d['nvidia0']['available_count'])) print "%s,nvidia1,%d" % (hostname, (9999 - d['nvidia1']['available_count'])) print "%s,nvidia2,%d" % (hostname, (9999 - d['nvidia2']['available_count'])) print "%s,nvidia3,%d" % (hostn...
#!/usr/bin/python __author__ = 'anson' import optparse import re import sys from utils.utils_cmd import execute_sys_cmd from lib_monitor.monitor_default_format import nagios_state_to_id class messages_check(): def __init__(self, rex, config, type): self.rex = rex self.config = config self.t...
lf.config) v_protocol = None exit_state = 3 if len(infos) > 0: state = infos[0].split()[0] if state not i
n nagios_state_to_id.keys(): print infos sys.exit(exit_state) exit_state = nagios_state_to_id[state] if nagios_state_to_id[state] > 0: m_protocol = re.search(r'\(\d+ errors in ([^ ]+)\)', infos[0]) v_protocol = m_protocol.group(1) i...
#!/usr/bin/env python2 """ COSMO TECHNICAL TESTSUITE General purpose script to compare two files containing tables Only lines with given table pattern are considered """ # built-in modules import os, sys, string # information __author__ = "Xavier Lapillonne" __maintainer__ = "xavier.lapillonne@meteoswiss.ch" ...
turn False try: for i in range(len(colpattern)): if colpattern[i]: f=float(line[i]) except ValueError: return False return True #----------------------------------- #execute as a script if __name__ == "__main__": if len(sys.argv)==6: cmp_table(sys.argv[1]...
(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4], \ sys.argv[5],sys.argv[6]) elif len(sys.argv)==8: cmp_table(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4], \ sys.argv[5],sys.argv[6],sys.argv[7]) else: print('''USAGE : ./comp_table file1 file2 colpattern minval th...
end([d.name for d in get_child_nodes('Item Group', d.item_group)]) if args_list: cond = "and i.item_group in (%s)" % (', '.join(['%s'] * len(args_list))) return frappe.db.sql(""" select i.name, i.item_code, i.item_name, i.description, i.item_group, i.has_batch_no, i.has_serial_no, i.is_stock_item, i.bran...
disabled = 0 and {cond}""".format(cond=cond), tuple(customer_groups), as_dict=1) or {} def get_customers_address(customers): customer_address = {} i
f isinstance(customers, string_types): customers = [frappe._dict({'name': customers})] for data in customers: address = frappe.db.sql(""" select name, address_line1, address_line2, city, state, email_id, phone, fax, pincode from `tabAddress` where is_primary_address =1 and name in (select parent from `tabDy...
return self._delete_whitespace() prev_prev_index = self._lines.index(self._prev_prev_item) if ( isinstance(self._lines[prev_prev_index - 1], self._Indent) or self.fits_on_current_line(item.size + 1) ): # The default initializer is already the on...
if ( last_space and (not isinstance(item, Atom) or not item.is_colon)
): break else: last_space = None if isinstance(item, self._Space): last_space = item if isinstance(item, (self._LineBreak, self._Indent)): return if not last_space: return self.ad...
e RDS resources take much longer than others to be ready. Check # less aggressively for slow ones to avoid throttling. if time.time() > start_time + 90: check_interval = 20 return resource def create_db_instance(module, conn): subnet = module.params.get('subnet') required_vars ...
'maint_window', 'multi_zone', 'new_instance_name', 'option_group', 'parameter_group', 'password', 'size', 'upgrade'] params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') new_
instance_name = module.params.get('new_instance_name') try: result = conn.modify_db_instance(instance_name, **params) except RDSException as e: module.fail_json(msg=e.message) if params.get('apply_immediately'): if new_instance_name: # Wait until the new instance name is...
alchemy.orm.properties import \\ ColumnProperty,\\
CompositeProperty,\\ RelationshipProperty class MyColumnComparator(ColumnProperty.Comparator): def __eq__(self, other): return self.__claus
e_element__() == other class MyRelationshipComparator(RelationshipProperty.Comparator): def any(self, expression): "define the 'any' operation" # ... class MyCompositeComparator(CompositeProperty.Comparator): def __gt__(self, other): ...
#!/usr/bin/env python import os import shutil import logging from unicode_helper import p __all__ = ["Renamer"] def log(): """Returns the logger for current file """ return logging.getLogger(__name__) def same_partition(f1, f2): """Returns True if both files or directories are on the same partit...
igured to do so if leave_symlink: symlink_file(new_fullpath, self.filena
me) self.filename = new_fullpath
ne) self.redraw(None) def showpopupmenu(self,widget,event): print('button ',event.button) if event.button == 3: m = self.builder.get_object("menufunctions") print(widget, event) m.show_all() m.popup(None,None,None,3,0) def get_time_select...
def data_handler(self, widget, input_dict, callback=None): ''' datahandler(data,srate,wintime,chanlabels,chanlocs) - data = 2D array srate = type(float or int) wintime = type(list or array) of same length as first dimension of da
ta chanlabels = type(list of strings) of same length as second dimension of data chanlocs = shape is 2Xnumber of channels, ie, (2,248) and contains page coordinates for each channel. Position of X and Y is between -.5 and .5 ''' ####!!!!!!! '''...