prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
import os, sys, array import numpy as np class BigFile: def __init__(self, datadir): self.nr_of_images, self.ndims = map(int, open(os.path.join(datadir,'shape.txt')).readline().split()) id_file = os.path.join(datadir, "id.txt") self.names = open(id_file).read().strip().split() asse...
name): renamed, vectors = self.read([name]) return vectors[0] def shape(self): return [self.nr_of_images, self.ndims] class StreamFile: def __init__(self, datadir): self.feat_dir
= datadir self.nr_of_images, self.ndims = map(int, open(os.path.join(datadir,'shape.txt')).readline().split()) id_file = os.path.join(datadir, "id.txt") self.names = open(id_file).read().strip().split() assert(len(self.names) == self.nr_of_images) self.name2index = dict(zip(self...
from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_array_almost_equal from scipy.sparse.csgraph import breadth_first_tree, depth_first_tree,\ csgraph_to_dense, csgraph_from_dense def test_graph_breadth_first(): csgraph = np.array([[0, 1, 2, 0,...
st_test = depth_first_tree(csgraph, 0, directed) assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst) def test_graph_breadth_first_trivial_graph(): csgraph = np.array([[0]]) csgraph = csgraph_from_dense(csgraph, null_value=0) bfirst = np.array([[0]]) ...
= breadth_first_tree(csgraph, 0, directed) assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst) def test_graph_depth_first_trivial_graph(): csgraph = np.array([[0]]) csgraph = csgraph_from_dense(csgraph, null_value=0) bfirst = np.array([[0]]) for...
from HG_Code.HG_Test import UnitTest as UT from HG_Code import Model as mo from HG_Code.Visualize import Visualizer from HG_Code.SimManager import sim_manager from HG_Code.Hunger_Grid import hunger_grid from HG_Code.Kat import Kat from HG_Code import hg_settings from HG_Code import Mutate as mu unitTest = UT.Run_Unit_...
to_mut=10, # END MUTATION CHANCE # from_gen = 33, # START GENERATE CHANCE # to_gen = 33, # END GENERATE CHANCE #t_name = 'Default' # TITLE OF TEST # frames = -1 # Defaults to -1 (-1:Don't, 0:Only Last, N:every N) #mo.run_model()...
33, 'Berry World') #mo.run_model(.00,.00,.1,.1, 10, 10, 33, 33, "No Lava") #mo.run_model(.1,.1,0.0,0.0, 10, 10, 33, 33, "No Berries") #mo.run_model(.1,.1,.1,.1,10,10,33,33,"Lava & Berries")
"""Start a tcp gateway.""" import click from mysensors.cli.helper import ( common_gateway_options, handle_msg, run_async_gateway, run_gateway, ) from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway def common_tcp_options(func): """Supply common tcp gateway options.""" func = click.op...
"-p", "--port", default=5003, show_default=True, type=int, help="TCP
port of the connection.", )(func) func = click.option( "-H", "--host", required=True, help="TCP address of the gateway." )(func) return func @click.command(options_metavar="<options>") @common_tcp_options @common_gateway_options def tcp_gateway(**kwargs): """Start a tcp gateway.""" gat...
base=None, # type: TypeVar derived_func=None, # type: str specials=None # type: SpecialSpec ): # type: (...) -> None self.name = name self.__doc__ = doc self.is_derived = isinstance(base, TypeVar) if base: ...
eVar """ Return a derived type variable that has the same vector geometry as this type variable, but with boolean lanes. Scalar types map to `b1`. """ return TypeVar.derived(self, self.ASBOOL) def half_width(self): # type: () -> TypeVar """ Return a d...
e same number of vector lanes as this one, but the lanes are half the width. """ return TypeVar.derived(self, self.HALFWIDTH) def double_width(self): # type: () -> TypeVar """ Return a derived type variable that has the same number of vector lanes as this one...
reverse, astart_point, aend_point) if direction_check == 1: cur2 = con.cursor() st = self._get_steptime(route_id, astart_point, aend_point) sql2 = """select id, TIMESTAMP WITH TIME ZONE '%s' + time '%s' from ride_requests where id = %d and earliest_start_time <= TIMESTAM...
nd_name = self._point_key_info(location_id, end_key) ##convert times tzname = self.get_timezone_name(location_id) check_est = c2r_time_to_datetime(start_date, earliest_start_time, tzname, True) start_time = c2r_time_to_datetime(start_date, earliest_start_time, tzname) lates
t_start_time = c2r_time_to_datetime(start_date, latest_start_time, tzname, False, check_est) ##close all request before this self.close_request(user_number_id, start_point, end_point, False, start_date) ##insert into db cur.execute(self._INSERT_REQUEST_STATEMENT % (user...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import CSV_DEFAULT_SEP = ',' CSV_DEFAULT_LF = '\n' def append_same_length(columns, data): if columns != []: return len(columns) == len(data) return True class DataBuffer(object): def __init__(self, csv_...
tor """ with DataBuffer("data.csv") as data: data.columns = ["a", "b", "c"]
data.append(1, 2.5, 3) data.append(4, 5, 6) data.append(7, 8, 9) if __name__ == '__main__': main_with_context_manager()
})".format(mpc_obs.comment.x, mpc_obs.comment.y, x.value, y.value)) except Exception as ex: loggin...
tion.mag)) except: pass if observation.comment.plate_uncertainty * 5.0 < \ ((observation.ra_r
esidual ** 2 + observation.dec_residual ** 2) ** 0.5): logging.warn("LARGE RESIDUAL ON: {}".format(observation.to_string())) logging.warn("Fit residual unreasonably large.") dra = numpy.array(dra) ddec = numpy.array(ddec) merr_str = "" for filter ...
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../tools')) import files import table import genetics def main(argv): int_mass = table.integer_mass(argv[0]) lines = files.read_lines(argv[1]) leaderboard = [([int_mass[p] for p in peptide], peptide) for peptide in lin...
= int(line
s[2]) print ' '.join(leader[1] for leader in genetics.trim_leaderboard(leaderboard, spectrum, N)) if __name__ == "__main__": main(sys.argv[1:])
from .mdl_user import * from .mdl_club import * from .mdl_event import
* from .mdl_receipt import * from .mdl_budget import * from .mdl_division import * from .mdl_eventsignin import * from .mdl_joinrequ
est import *
# -*- coding: utf-8 -*- # Copyright 2008-2014 Jaap Karssenberg <jaap.karssenberg@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 2 of the License, or # (at your optio...
dir ## (sys.argv[0] should always be correct, even for compiled exe) if os.name == "nt": # See notes in zim/fs.py about encoding expected by abspath ZIM_EXECUTABLE = os.path.abspath( unicode(sys.argv[0], sys.getfilesystemencoding()) ) else: ZIM_EXECUTABLE = unicode( os.path.abspath(sys.argv[0]), sys.getfile...
make this optional later for module use ?) if os.name == "nt" and not os.environ.get('LANG'): # Set locale config for gettext (other platforms have this by default) # Using LANG because it is lowest prio - do not override other params lang, enc = locale.getlocale() os.environ['LANG'] = lang + '.' + enc logging.in...
t symmetric difference, infinite set""" self._helper_test_inifinite_set(self.fncs_list[2]) def test_set_symmetric_difference_infinite_empty(self): """intbitset - set symmetric difference, infinite vs empty""" self._helper_test_infinite_vs_empty(self.fncs_list[2]) def test_set_differenc...
"" for set1 in self.sets + [[]]: tmp_tuple = tuple([(elem, ) for elem in set1]) self.assertEqual(list(self.intbitset(set1)), list(self.intbitset(tmp_tuple))) for set1 in self.sets + [[]]: tmp_tuple = tuple([(elem, ) for elem in set1]) self.assertEqual(self...
True)) def test_marshalling(self): """intbitset - marshalling""" for set1 in self.sets + [[]]: self.assertEqual(self.intbitset(set1), self.intbitset(self.intbitset(set1).fastdump())) for set1 in self.sets + [[]]: self.assertEqual(self.intbitset(set1, trailing_bits=Tr...
import logging import winreg from nativeconfig.configs.base_config import BaseConfig LOG = logging.getLogger('nativeconfig') ERROR_NO_MORE_ITEMS = 259 ERROR_NO_MORE_FILES = 18 def traverse_registry_key(key, sub_key): """ Traverse registry key and yield one by one. @raise WindowsError: If key cannot b...
REGISTRY_PATH) winreg.CloseKey(k) super(RegistryConfig, self).__init__() #{ BaseConfig def get_value_cache_free(self, name): try: with winreg.OpenKey(self.REGISTRY_KEY, self.REGISTRY_PATH) as app_key: try: value, value_type =
winreg.QueryValueEx(app_key, name) if not value_type == winreg.REG_SZ: raise ValueError("value must be a REG_SZ") return value except OSError: pass except: self.LOG.exception("Unable to get \"%s\" f...
se. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See t...
run() function returns new credentials. The new credentials are also stored in the Storage argument, which updates the file associated with the Storage object. It presumes it is run from a command-line application and supports the following flags: --auth_host_nam
e: Host name to use when running a local web server to handle redirects during OAuth authorization. (default: 'localhost') --auth_host_port: Port to use when running a local web server to handle redirects during OAuth authorization.; repeat this option to specify a list of values (def...
import os import subprocess from pymongo import MongoClient from flask import Flask, redirect, url_for, request, flash from flask_bootstrap import Bootstrap from flask_mongoengine import MongoEngine from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider...
cret key!' % SECRET_FILE) # Load config config_path = os.getenv('CONFIG_PATH', 'mass_flask_config.config_development.DevelopmentConfig') app.config.from_object(config_path) # Init db db = MongoEngine(app) # Init flask-bootstrap Bootstrap(app) # Init auth system def setup_session_auth(user_loader): app.session_...
oader): app.key_based_provider = KeyBasedAuthProvider(key_loader) auth_manager.register_auth_provider(app.key_based_provider) def unauthorized_callback(): if current_authenticated_entity.is_authenticated: flash('You are not authorized to access this resource!', 'warning') return redirect(u...
this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is...
shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the ...
-- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the docu...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
ef test_response_in_lo
gs(self, m): """ Test that when using SimpleHttpOperator with 'GET', the log contains 'Example Domain' in it """ m.get('http://www.example.com', text='Example.com fake response') operator = SimpleHttpOperator( task_id='test_HTTP_op', method='GET',...
# -*- coding:utf-8 -*- # This code is automatically transpiled by Saklient Translator import six from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.routerplan import RouterPlan from ...util import Util import saklient str = six.text_type # module saklient....
return self._offset(offset) ## 次に取得するリストの上限レコード数を指定します。 # # @param {int} count 上限レコード数 # @return {saklient.cloud.models.model_routerplan.Model_RouterPlan} this def limit(self, count): Util.validate_type(count, "int
") return self._limit(count) ## Web APIのフィルタリング設定を直接指定します。 # # @param {str} key キー # @param {any} value 値 # @param {bool} multiple=False valueに配列を与え、OR条件で完全一致検索する場合にtrueを指定します。通常、valueはスカラ値であいまい検索されます。 # @return {saklient.cloud.models.model_routerplan.Model_RouterPlan} def filt...
from tile_view import * from table import * from game_state import * from circ_button import * class TableView: GREY = (100,100,100) BLACK = (0,0,0) WHITE = (255,255,255) BGCOLOR = (60,60,100) TILE_COLOR = (90, 255, 90) TILE_RADIUS = 30 TABLE_POS = (245, 90) # table : Table # pl1,...
r, TableView.TILE_COLOR))#, lambda btn : print(btn.col, btn.row))) W = surface.get_width() H = surface.get_height() self.pl1_view = PlayerView(pl1, (0,0)) self.pl2_view = PlayerView(pl2, (W-TableView.TILE_RADIUS*2,0)) self.marble_stack = [] self.marble_stack...
(CircleButton(int(W/2-r*3), H-r*2, r, \ TableView.WHITE, str(table.marbles[0]))) self.marble_stack.append(CircleButton(int(W/2), H-r*2, r, \ TableView.GREY, str(table.marbles[1]))) self.marble_stack.append(CircleButton(int(W/2+r*3), H-r*2, r, \ TableView.B...
import flask import MemeRepo.db as db import MemeRepo.funcs as fnc from MemeRepo.config import config def handle(code, uri):
result = db.get_file(uri) if result == None: return flask.render_template("error.html", msg="That file does not exist", code="400"), 400 else: if result['owner'] ==
code: db.delete_file(uri) return 'deleted' else: return flask.render_template("error.html", msg="You do not own that file", code="403"), 403
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
s[CC].vectorize(xi) ko, ki = s[CC].split(k, factor=2) s[CC].unroll(ki) print(tvm.lower(s, [A, B, C], simple_mode=True)) f = tvm.build(s, [A, B, C], "opencl", target_host=target, name="gemm_gpu") t
emp = util.tempdir() path_dso = temp.relpath("gemm_gpu.so") f.export_library(path_dso, ndk.create_shared) # connect to the proxy remote = rpc.connect(proxy_host, proxy_port, key=key) ctx = remote.cl(0) remote.upload(path_dso) f = remote.load_module("gemm_gpu.so") evaluate(f, ctx, N, ti...
import arcpy, os, json, csv from portal import additem, shareItem, generateToken, getUserContent, updateItem, getGroupID, deleteItem, getGroupContent from metadata import metadata from ESRImapservice import ESRImapservice class csvportal(object): def __init__(self, user, password, portal, worksspace, group...
em = additem(self.user, self.token, self.portal, serviceUrl, title=name, summary=meta.purpose, description=descrip, author=author, tags=",".join(meta.tags) ) if "success" in item.keys() and item["success"]: id = item["id"] arcpy.AddMessage( shareItem(id, self.token...
tion( "Error uploading "+ name +" "+ json.dumps(result)) else: arcpy.AddMessage("unsure of success for layer "+ name +" "+ json.dumps(result)) def delLyr(self, name): if name in self.existingIDs.keys(): result = deleteItem(self.existingIDs[name] , self.token, sel...
ValueName=defaultNamedNotOptArg): 'DeleteValue' return self._oleobj_.InvokeTypes(10, LCID, 1, (24, 0), ((8, 1),),ValueName ) def EnumKeys(self, Index=defaultNamedNotOptArg): 'EnumKeys' # Result is a Unicode object return self._oleobj_.InvokeTypes(11, LCID, 1, (8, 0), ((3, 1),),Index ) def EnumValues...
oleobj_.InvokeTypes(12, LCID, 1, (8, 0), ((3, 1),),Index ) def GetBinaryValue(self, ValueName=defaultNamedNotOptArg): 'GetBinaryValue' return self._ApplyTypes_(2, 1, (12, 0), ((8, 1),), u'GetBinaryValue', None,ValueName ) def GetLongValue(self, ValueName=defaultNamedNotOptArg): 'GetlongValue' return s...
' # Result is a Unicode object return self._oleobj_.InvokeTypes(4, LCID, 1, (8, 0), ((8, 1),),ValueName ) # Result is of type ISpeechDataKey def OpenKey(self, SubKeyName=defaultNamedNotOptArg): 'OpenKey' ret = self._oleobj_.InvokeTypes(7, LCID, 1, (9, 0), ((8, 1),),SubKeyName ) if ret is not None: ...
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import NestedSet, get_root_of class SupplierGroup(NestedSet): nsm_parent_field = 'parent_sup...
e(self): if not self.parent_supplier_group: self.parent_supplier_group = get_root_of("Supplier Group") def on_update(self): NestedSet.on_update(self) self.validate_one_root() def on_trash(self): NestedSet.validate_if_child_exists(self) frap
pe.utils.nestedset.update_nsm(self)
# -*- coding: utf-8 -*- """ Created on Wed Dec 9 21:31:53 2015 Create random synthetic velocity profile + linear first guesses @author: alex """ import random import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def savitzky_golay(y, window_size, order, deriv=0, rate=1): r...
ots.append(coordX) Yshots.append(coordY) Zshots.append(coordZ) fo.write(str(coordX)+" "+str(coordY)+" "+str(coordZ)+"\n") # Close opened file fo.close() #Open a file in write mode: fo = open("dataExample/coordStats.txt", "w+") for coordX in coordStatsX: for coordY in coordStatsY...
fo.write(str(coordX)+" "+str(coordY)+" "+str(coordZ)+"\n") # Close opened file fo.close() fig = plt.figure() ax = fig.gca(projection='3d') #Axes3D(fig) ax.hold(True) ax.scatter(Xstats,Ystats,Zstats,zdir='z',s=20,c='b') if (len(coordShotsX) > 3): ax.scatter(Xshots,Yshots,Zshots,zdir='z',s=20,c='r',mark...
def get(self, spec, new=False): """Find a repo that contains the supplied spec's package. Raises UnknownPackageError if not found. """ return self.repo_for_pkg(spec).get(spec) def get_pkg_class(self, pkg_name): """Find a class for the spec's package and return the cla...
(pkg_name).filename_for_package_name(pkg_name) def exists(self, pkg_name): """Whether package with the give name exists in the path's repos
. Note that virtual packages do not "exist". """ return any(repo.exists(pkg_name) for repo in self.repos) def is_virtual(self, pkg_name): """True if the package with this name is virtual, False otherwise.""" return pkg_name in self.provider_index def __contains__(self,...
.path.join(origin_directory,quality_directory, mode_directory,site_directory, camera_directory, filter_directory, field_directory) self.output_d...
) py = int(py) px = int(px) try: self.thumbnail=self.data[px-self.thumbnail_box_size/2:px+self.thumbnail_box_size/2,py-self.thumbnail_box_size/2:py+self.thumbnail_box_size/2] self.logger.info('Thumbnail successfully produce around the good position') ...
cept: self.thumbnail=np.zeros((self.thumbnail_box_size,self.thumbnail_box_size)) self.logger.info('Thumbnail successfully produce around the center of the image') def compute_stats_from_catalog(self,catalog): try: self.sky_level=np.media...
#!/usr/bin/env python #-*- coding:utf-8 -*- # # Copyright (C) 2016 Oladimeji Fayomi, University of Waikato. # # 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/lic
enses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations und...
# Last Modified: 17 August 2016 # Version: 1.0 # Description: Listens to netlink messages and notifies the RheaFlow # application of important netlink messages. import socket from pyroute2 import IPDB import eventlet from datetime import datetime from log import log try: import cPickle as pickle exce...
# -*- coding: utf-8 -*- from django.urls import re_path from django.contrib.auth import views as auth_views from django.utils.translation import gettext_lazy as _ from django.urls import reverse_lazy from . import forms from . import views app_name = "auth" urlpatterns = [ # Sign in / sign out re_path( ...
"public/auth/login.html", authentication_form=forms.AuthenticationForm ), name="login", ), re_path(_(r"^deconnexion/$"), auth_views.LogoutView.as_view(next_page="/"), name="logout"), re_path(_(r"^bienvenue/$"),
views.UserLoginLandingRedirectView.as_view(), name="landing"), # Parameters & personal data re_path( _(r"^donnees-personnelles/$"), views.UserPersonalDataUpdateView.as_view(), name="personal_data", ), re_path(_(r"^parametres/$"), views.UserParametersUpdateView.as_view(), name="pa...
# This stores all the dialogue related stuff import screen class Dialogue(object): """Stores the dialogue tree for an individual NPC""" def __init__(self, npc): super(Dialogue, self).__init__() self.npc = npc self.game = npc.game self.root = None self.currentNode = None def setRootNode(self...
e = choice.responseFunction(self.npc, response) self.game.printDescription(response
, npcName) self.currentNode = nextNode self.runNextNode() class DialogueNode(object): """A single node of the dialogue tree""" def __init__(self): super(DialogueNode, self).__init__() self.choices = [] def addChoice(self, choice, choicePredicate=None, childNode=None): self.choices.append...
import threading __author__ = "Piotr Gawlowicz" __copyright__ = "Copyright (c) 2015, Technische Universitat Berlin" __version__ = "0.1.0" __email__ = "gawlowicz@tkn.
tu-berlin.de" class Timer(object): def __init__(self, handler_): assert callable(handler_) super().__init__() self._handler = handler_ self._event = threading.Event() self._thread
= None def start(self, interval): """interval is in seconds""" if self._thread: self.cancel() self._event.clear() self._thread = threading.Thread(target=self._timer, args=[interval]) self._thread.setDaemon(True) self._thread.start() def cancel(self):...
from flask import Flask from flask import render_template import euclid import queue_constants import ast import redis import t
hreading REDIS_ADDRESS = "localhost" REDIS_PORT = 6379 REDIS_DB = 0 app = Flask(__name__) @app.route("/") def monitor(): queue = redis.StrictRedis(host=REDIS_ADDRESS, port=REDIS_PORT, db=REDIS_DB) nstatus =
[] status = ast.literal_eval(queue.get(queue_constants.NODE_KEY).decode()) for s in status: nstatus.append({"name":s, "status":status[s]["status"]}) return render_template('monitor.html', status=nstatus) if __name__ == "__main__": euclidThread = threading.Thread(target=euclid.main) euclidT...
""" Core ==== AudioSignals ----------
-- .. autoclass:: nussl.core.AudioSignal :members: :autosu
mmary: Masks ----- .. automodule:: nussl.core.masks :members: :autosummary: Constants ------------ .. automodule:: nussl.core.constants :members: :autosummary: External File Zoo ----------------- .. automodule:: nussl.core.efz_utils :members: :autosummary: General utilities ----------------...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: S.H. Version: 0.1 Date: 2015-01-17 Description: Scan ip: 74.125.131.0/24 74.125.131.99-125 74.125.131.201 Only three format above. Read ip form a ip.txt, and scan all port(or a list port). """ import os import io import socket file...
: fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n") elif line.find("/") != -1: list = line[:line.index("/")] ip = [int(a) for a in list.split(".")] for i in range(256): fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n") else: fileTemp.write(li...
("===Scan Staring===") for line in f.readlines(): hostIP = socket.gethostbyname(line) # print(hostIP) # for port in range(65535): portList = [80, 8080] for port in portList: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((hostIP, port)) if result == 0: p...
ting for the normalization terms and scaling), allowing for universal comparison (beyond this software package) Parameters ---------- emp_cov : 2D ndarray (n_features, n_features) Maximum Likelihood Estimator of covariance precision : 2D ndarray (n_features, n_features) The pre...
the data used in fit (including centering). y not used, present for API consistence purpose. Returns ------- res : float The likelihood of the data set with `self.covariance_` as an estimator of its covariance matrix. """ # ...
ariance( X_test - self.location_, assume_centered=True) # compute log likelihood res = log_likelihood(test_cov, self.get_precision()) return res def error_norm(self, comp_cov, norm='frobenius', scaling=True, squared=True): """Computes the Mean Squared...
""" LsVarRun - command ``ls -lnL /var/run`` ======================================= The ``ls -lnL /var/run`` command provides information for the listing of the ``/var/run`` directory. Sample input is shown in the Examples. See ``FileListing`` class for additional information. Sample directory list:: total 20 ...
Examples: >>> "rhnsd.pid" in ls_var_run False >>> "/var/run" in ls_var_run True >>> ls_var_run.dir_entry('/var/run', 'openvpn')['type'] 'd' """ from insights.specs import Specs from .. import FileListing from .. import parser @parser(Specs.ls_var_run)
class LsVarRun(FileListing): """Parses output of ``ls -lnL /var/run`` command.""" pass
e.compile(r"I\(([^)]+)\)") _BOLD = re.compile(r"B\(([^)]+)\)") _MODULE = re.compile(r"M\(([^)]+)\)") _URL = re.compile(r"U\(([^)]+)\)") _CONST = re.compile(r"C\(([^)]+)\)") DEPRECATED = b" (D)" pp = PrettyPrinter() display = Display() def rst_ify(text): ''' convert symbols like I(this is in italics) to valid re...
= defaultdict(dict) # * windows powershell modules have documentation stubs in python docstring # format (they are not executed) so skip the ps1 format files # * One glob level for every module level that we're g
oing to traverse files = ( glob.glob("%s/*.py" % module_dir) + glob.glob("%s/*/*.py" % module_dir) + glob.glob("%s/*/*/*.py" % module_dir) + glob.glob("%s/*/*/*/*.py" % module_dir) ) for module_path in files: # Do not list __init__.py files if module_path.end...
"""tuple sub-class which holds weak references to objects""" import weakref class WeakTuple( tuple ): """tuple sub-class holding weakrefs to items The weak reference tuple is intended to allow you to store references to a list of objects without needing to manage weak references directly. For th...
ef __gt__( self, sequence ): """Compare the tuple to another (>)""" return list(self) > sequence def __le__( self, sequence ): """Compare the tuple to another (<=)""" return list(self) <= sequence def __lt__( self, sequence ): """Compare the tuple to another (<)"...
ist(self) < sequence def __ne__( self, sequence ): """Compare the tuple to another (!=)""" return list(self) != sequence def __repr__( self ): """Return a code-like representation of the weak tuple""" return """%s( %s )"""%( self.__class__.__name__, super(WeakTuple,self).__repr...
list: fields_to_strip += self._exclude_attributes_by_policy( request.context, obj_list[0]) collection = {self._collection: [self._filter_attributes( request.context, obj, fields_to_strip=fields_to_strip) ...
tions.append(reservation) except n_exc.QuotaResourceUnknown as e:
# We don't want to quota this resource LOG.debug(e) def notify(create_result): # Ensure usage trackers for all resources affected by this API # operation are marked as dirty with request.context.session.begin(): # Commit the reservation(s)...
# -*-coding: utf-8 -*- import colander from . import ( SelectInteger, ResourceSchema, BaseForm, BaseSearchForm, ) from ..resources.leads_offers import LeadsOffersResource from ..models.lead_offer import LeadOffer from ..models.currency import Currency from ..models.supplier import Supplier from ..mode...
te_resource( get_auth_employee(self.request) ) ) lead_offer.service_id = self._controls.get('service_id') lead_offer.currency_id = self._controls.get('currency_id') lead
_offer.supplier_id = self._controls.get('supplier_id') lead_offer.price = self._controls.get('price') lead_offer.status = self._controls.get('status') lead_offer.descr = self._controls.get('descr') return lead_offer class LeadOfferSearchForm(BaseSearchForm): _qb = LeadsOffersQueryB...
# -*- coding: utf-8 -*- # Copyright 2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
s and # limitations under the License. from __future__ import absolute_import from behave import given from behave import when from steps.util import create_consumer_group from steps.util import create_random_group_id from steps.util import create_random_topic from steps.util import initialize_kafka_offsets_topi
c from steps.util import produce_example_msg PRODUCED_MSG_COUNT = 82 CONSUMED_MSG_COUNT = 39 @given(u'we have an existing kafka cluster with a topic') def step_impl1(context): context.topic = create_random_topic(1, 1) @given(u'we have a kafka consumer group') def step_impl2(context): context.group = create...
'''This gile will take arguments from the command line, if none are found it will look for a .bot file, if that isn't found it will promt the user for auth tokens :- with this information the masterbot will connect to its own twitch chan
nel and await a !connect command''' #Author MrYevral #check for .bot file in current directory import os import sys def getBotInfo(): if len(sys.argv) > 2: if sys.argv[2] == '-c': newBotFile() else: print "incorrect use of
flags please use -c for creating a bot" '''for file in os.listdir("."): if file.endswith(".bot"): print file'''
#!/usr/bin/python # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
int ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be ' 'deactivated.' % (placement['id'], placement['name'], placement['status'])) print 'Number of placements to be deactivated: %s' % len(placements) # Perform action. result = placement_service.PerformPlacementActi...
d: %s' % result['numChanges'] else: print 'No placements were deactivated.'
# -*- coding: utf-8 *-* from pyglet.window import key from pyglet import clock from . import util, physicalobject from . import resources class Ship(physicalobject.PhysicalObject): """A class for the player""" def __init__(self, thrust_image=None, *args, **kwargs): super().__init__(*args, **kwargs) ...
img=resources.shot_image, batch=self.batch, group=self.group, screensize=self.screensize) self.bullets.add(bullet) def destroy(self): # check invulnerability if self.opacity != 255: return explosion = super().destroy()
self.rotation = -90 self.x = self.screensize[0] / 2 self.y = self.screensize[1] / 2 self.vel = [0, 0] self.set_thrust(False) self.visible = True return explosion def normal_mode(self, dt): self.opacity = 255 def invulnerable(self, time): ...
from django.contrib import admin from freemix.exhibit import models class CanvasAdmin(admin.ModelAdmin): list_display = ('title', 'description') search_fields = ('title', 'description',) admin.site.register(models.Canvas, CanvasAdmin) class ExhibitAdmin(admin.ModelAdmin): list_display = ('slu...
ner__username') admin.site.register(models.Exhibit, ExhibitAdmin) class ThemeA
dmin(admin.ModelAdmin): list_display = ('title', 'description') search_fields = ('title', 'description',) admin.site.register(models.Theme, ThemeAdmin)
import os require
ments = ["numpy", "scipy", "pandas", "matplotlib", "peakutils", "uncertainties", "pyqtgraph"] for package in requirements: os.system("pip install " + package
)
will compare with. | If a string, it can be a single command, | multiple commands separated by commas, or | a filepath location of a file with multiple | commands, each on its own line. @type commands: str or list ...
make to the device. | - 'paramiko' is used for operational commands (to allow | pipes in commands) | - 'scp' is used for copying files |
- 'shell' is used for to send shell commands | - 'root' is used when logging into the device as root, and | wanting to send operational commands | - 'ncclient' is used for the rest (commit, compare_config, | commit_check) @return...
from iliasCorrector import db def _split_ident(ident): data = ident.split('_') matr = int(data[-1]) last = data[0] first = ' '.join(data[1:-2]) return first, last, matr class Exercise(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) p...
rty def student(self): return '{}, {}'.format(self.last_name, self.first_name) @property def matriculation_number(s
elf): return _split_ident(self.student_ident)[2] class File(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) path = db.Column(db.String(256)) submission_id = db.Column(db.Integer, db.ForeignKey('submission.id')) def __repr__(self): return '<F...
import numpy as np tansig = lambda n: 2 / (1 + np.exp(-2 * n)) - 1 sigmoid = lambda n: 1 / (1 + np.exp(-n)) hardlim = lambda n: 1 if n >= 0 else 0 purelin = lambda n: n relu = lambda n: np.fmax(0,
n) square_error = lambda x, y: np.sum(0.5 * (x - y)**2) sig_prime = lambda z: sigmoid(z) * (1 - sigmoid(z)) relu_prime = lambda z: relu(z) * (1 - relu(z)) softmax = lambda n: n
p.exp(n)/np.sum(np.exp(n)) softmax_prime = lambda n: softmax(n) * (1 - softmax(n)) cross_entropy = lambda x, y: -np.dot(x, np.log(y))
imp
ort pytest def test_zero_division(): with pytest.raises(ZeroDivisionError): 1 / 0 def test_recursion_depth(): with pytest.raises(RuntimeError) as excinfo: def f(): f() f() assert 'maximum recursion depth exceeded' in str(
excinfo.value)
from __future__ import unicode_literals from django.db import models from db.models import Bin class C
ollectionEntry(models.Model): bin_obj = models.ForeignKey(Bin, related_name='requested_bins')
fullness = models.IntegerField() date_added = models.DateTimeField(auto_now_add=True)
# -*- coding: utf-8 -*- import unittest from cwr.grammar.factory.config import rule_options __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestConfigOptions(unittest.TestCase): def setUp(self): self._rule = rule_options def test_zero_options(self): ...
self.assertEqual('', result[0]) def test_one_options(self): line = '(option2)' result = self._rule.parseString(line) self.assertEqual(1, len(result)) self.assertEqual('option2', result[0]) def test_two_options(self): line = '(option1, option2)' result =...
self.assertEqual('option1', result[0]) self.assertEqual('option2', result[1])
""" Operations: P - login G - list - list the dir's content G - read - reads a file G - info - infos about a file P - write - writes a file P - mkdir - makes a dir P - copy - to=... P - move - to=... P - delete - DELETE P - logout """ import canister import bottle import os.path import json imp...
files = os.listdir(fpath) listing = [] for name in files: if not hidden and name[0] == '.': continue p = os.path.join(fpath, name) item = { 'name': name, 'type': 'dir' if os.path.isdir(p) else 'file', ...
e(p), 'last_modified': time.ctime(os.path.getmtime(p)) } listing.append( item ) listing.sort(key=lambda x: x['name']) bottle.response.content_type = 'application/json' return json.dumps(listing) else: raise Excep...
""" ------------------------------------------------------------------------- AIOpening - special.py useful functions created: 2017/09/01 in PyCharm (c) 2017 Sven - ducandu GmbH ------------------------------------------------------------------------- """ import numpy as np import tensorflow as tf def we...
# An array of the weights, cumulatively summed. cs = np.cumsum(weights) # Find the index of the first weight over a random value. idx = sum(cs < np.random.rand()) return objects[min(idx, len(objects) - 1)] def to_one_hot(ind, dim): ret = np.zeros(dim) ret[ind] = 1 return ret def to_o...
t def from_one_hot(v): return np.nonzero(v)[0][0] def from_one_hot_batch(v): if len(v) == 0: return [] return np.nonzero(v)[1] def new_tensor(name, n_dim, dtype): return tf.placeholder(dtype=dtype, shape=[None] * n_dim, name=name)
# # LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net> # # LMirror 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 Li
cense, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See 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/>. # # In the LMirror source tree the file COPYIN...
rom tensorflow.python.ops.rnn_cell import DropoutWrapper, RNNCell, LSTMStateTuple from my.tensorflow import exp_mask, flatten from my.tensorflow.nn import linear, softsel, double_linear_logits class SwitchableDropoutWrapper(DropoutWrapper): def __init__(self, cell, is_train, input_keep_prob=1.0, output_ke...
new_state class TreeRNNCell(RNNCell): def __init__(self, cell, input_size, reduce_func): self._cell = cell self._input_size = input_size self._reduce_func = reduce_fu
nc def __call__(self, inputs, state, scope=None): """ :param inputs: [N*B, I + B] :param state: [N*B, d] :param scope: :return: [N*B, d] """ with tf.variable_scope(scope or self.__class__.__name__): d = self.state_size x = t...
pache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissi...
[] for img in self.images.values(): retval += [dict([(k, v) for k, v in img.iteritems() if k in ['id', 'name']])]
return retval #TODO(bcwaldon): implement optional kwargs such as limit, sort_dir def detail(self, context, **kwargs): """Return list of detailed image information.""" return copy.deepcopy(self.images.values()) def get(self, context, image_id, data): metadata = self.show(contex...
"""Internal module for Python 2 backwards compatibility.""" import sys if sys.version_info[0] < 3: from urlparse import parse_qs, urlparse from itertools import imap, izip from string import letters as ascii_letters from Queue import Queue try: from cStringIO import StringIO as BytesIO ...
eys = lambda x: x.iterkeys() itervalues = lambda x: x.itervalues() nativestr = lambda x: \ x if isinstance(x, str) else x.encode('utf-8', 'replace') u = lambda x: x.decode() b = lambda x: x next = lambda x: x.next() byte_to_chr = lambda x: x unichr = unichr xrange = xrange ba...
rse_qs, urlparse from io import BytesIO from string import ascii_letters from queue import Queue iteritems = lambda x: iter(x.items()) iterkeys = lambda x: iter(x.keys()) itervalues = lambda x: iter(x.values()) byte_to_chr = lambda x: chr(x) nativestr = lambda x: \ x if isinstan...
import platform import urllib import subprocess from progressbar import ProgressBar class Downloader(object): WINDOWS_DOWNLOAD_URL = "http://cache.lego.com/downloads/ldd2.0/installer/setupLDD-PC-4_3_8.exe" MAC_DOWNLOAD_URL = "http://cache.lego.com/downloads/ldd2.0/installer/setupLDD-MAC-4_3_8.zip" PB = N...
count * block_size) class Installer(object): @classmetho
d def install(cls): pass
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import mock from nose.tools import ok_ from crontabber.app import CronTabber from socorro.unittest.cron.jobs.base impo...
ort-json-schema' ok_(information[app_name]) ok_(not information[app_name]['last_error']) ok_(information[app_name]['last_success']) key.set_contents_from_string.assert_called_with( CRASH_REPORT_JSON_SCHEMA_AS_STRING
)
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os,re,traceback,sys from waflib import Utils,ansiterm if not os.environ.get('NOSYNC',False): if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__): sys.stdout=ansiterm.AnsiTerm(sys.s...
rom logging.handlers import MemoryHandler logger=logging.getLogger(name) hdlr=MemoryHandler(size,target=to_log) formatter=logging.Formatter('%(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.memhandler=hdlr logger.setLevel(logging.DEBUG) return logger def free_logger(logger): try: for...
ors(col),msg,colors.NORMAL,label,extra={'terminator':sep})
#!/usr/bin/python # # $Id: gen-data-queryperf.py,v 1.1.10.1 2003/05/15 05:07:21 marka Exp $ # # Contributed by Stephane Bortzmeyer <bortzmeyer@nic.fr> # # "A small tool which may be useful with contrib/queryperf. This script # can generate files of queries, both with random names (to test the # behaviour with NXdoma...
+ " [-n number] " + \ "[-p percent-random] [-t TLD]\n") sys.stdout.write(" [-m MAXSIZE] [-f zone-file]\n") try: optlist, args = getopt.getopt(sys.argv[1:], "hp:f:n:t:m:", ["help", "percentrandom=", "zonefile=",
"num=", "tld=", "maxsize="]) for option, value in optlist: if option == "--help" or option == "-h": usage() sys.exit(0) elif option == "--number" or option == "-n": num = int(value) elif option == "--maxsize" or optio...
import numpy as np from gpaw import KohnShamConvergenceError class SCFLoop: """Self-consistent field loop. converged: Do we have a self-consistent solution? """ def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100, fixdensity=False, niter_fixdensity=None...
and density.""" if self.converged:
return True self.eigenstates_error = eigensolver.error if len(self.energies) < 3: self.energy_error = self.max_energy_error else: self.energy_error = np.ptp(self.energies[-3:]) self.density_error = density.mixer.get_charge_sloshing() if self.density_er...
from netfilterqueue import NetfilterQueue from dpkt import ip, icmp, tcp, udp from scapy.all import * import socket def print_and_accept(pkt): data=pkt.get_payload() res = ip.IP(data)
res2 = IP(data) i = ICMP(data) t = TCP(data) u = UDP(data) print "SOURCE IP: %s\tDESTINATION IP: %s" % (socket.inet_ntoa(res.src),socket.inet_ntoa(res.dst)) print res2.show2() resp=srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst='192.168.0.34'),iface="eth0",timeout=2) print resp.dst eth_...
pkt.accept() nfqueue = NetfilterQueue() nfqueue.bind(6, print_and_accept) try: nfqueue.run() except KeyboardInterrupt, ex: print ex
#!/usr/bin/env python import csv # create an empty list that will be filled with the rows of data from the CSV as dictionaries csv_content = [] # open and loop through each line of the csv file to populate our data file with open('aaj1945_DataS1_Egg_shape_by_species_v2.csv') as csv_file: csv_reader = csv.DictRea...
r(csv_file) lineNo = 0 for row in csv_reader: # process each row of the csv fil
e csv_content.append(row) if lineNo < 3: # print out a few lines of data for our inspection print(row) lineNo += 1 # create some empty lists that we will fill with values for each column of data order = [] family = [] species = [] asymmetry = [] ellipticity = [] avgl...
################################################################################ # Copyright 2015 Samuel Gongora Garcia (s.gongora
garcia@gmail.com) # # This program is free software: you can redistribut
e it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied war...
from django.conf.urls import include, url from django.contrib import admin u
rlpatterns = [ url(r'^admin/',
include(admin.site.urls)), url(r'^external/', include('external.urls')), url(r'^dev/', include('dev.urls')), ]
self.uri = None self.rs_uri = None self.version = None self.sessions_enabled = False self.fake_hostname_uri = None self.server_status = None def setup(self): assert not self.initialized self.setup_sync_cx() self.setup_auth_and_uri() self....
ent( host, port, username=db_user, password=db_password, directConnection=True, tlsCAFile=CA_PEM, tlsCertificateKeyFile=CLIENT_PEM, ) )
else: client = connected( pymongo.MongoClient( host, port, username=db_user, password=db_password, directConnection=True, ssl=False, ) ) ...
import os import random import string from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait TEST_APP_URL = os.getenv('TEST_APP_URL') TEST_CLIENT_URL = os.getenv('TEST_CLIENT_URL') E2E_ARGS = os.getenv('E2E_ARGS') TEST_URL = TEST_CLIENT_URL if E2E_ARGS...
'client' else TEST_APP_URL def random_string(length=8): return ''.join(random.choice(string.ascii_letters) for x in range(length)) def register(se
lenium, user): selenium.get(f'{TEST_URL}/register') selenium.implicitly_wait(1) username = selenium.find_element_by_id('username') username.send_keys(user.get('username')) email = selenium.find_element_by_id('email') email.send_keys(user.get('email')) password = selenium.find_element_by_id('...
UL_CATEGORY_LI = '//ul[@class="category"]/li' H2_A_TITLELINK = './h2/a[@class="titlelink"]' SPAN_A_TITLELINK = './span/a[@class="titlelink"]' DIV_BODYFIELD_P = '//div[contains(@class,"bodyfield")]/p' CATEGORY_H2_XPATH = [ UL_CATEGORY_LI, H2_A_TITLELINK ] BODYFIELD_SPAN_XPATH = [ DIV_BODYFIELD_P, SPAN_A_TITLELINK ] ""...
r EOPSS pages) to the xpath needed to extract documents (1st xpath for s
ection, 2nd xpath for document link) """ MASSGOV_DICT = { 'homeland-sec/grants/docs/': [ UL_CATEGORY_LI, './h2/span/a[@class="titlelink"]' ], 'homeland-sec/grants/hs-grant-guidance-and-policies.html': BODYFIELD_SPAN_XPATH, 'home...
ommit(dict_, to_load) if post_load and context.invoke_all_eagers: post_load.add_state(state, False) return instance if mapper.polymorphic_map and not _polymorphic_from and not refresh_state: # if we are doing polymorphic, dispatch to a different _instance() # m...
for key, getter in populators["quick"]: if key not in dict_: dict_[key] = getter(row) # otherwise treat like an "already seen" row for key, populator in populators["existing"]: populator(state, dict_, row) # TODO: allow "existing" populator to know...
h. for key, populator in populators["existing"]: populator(state, dict_, row) # TODO: same path # populator(state, dict_, row, new_path=False) def _populate_partial( context, row, state, dict_, isnew, load_path, unloaded, populators ): if not isnew: to_loa...
# -*- encoding: utf-8 -*- from __future__ import unicode_literals from datetime import ( datetime, timedelta, ) from dateutil.relativedelta import relativedelta from base.tests.model_maker import clean_and_save from booking.models import ( Booking, Category, Location, ) def get_alpe_d_huez(): ...
head <= 0: # Target day already happened this week days_ahead += 7 return d + timedelta(days_ahead) def demo_data(): # set-up some dates today = datetime.today().date() # 1st week last month starting Saturday first_prev_month = today + relativedelta(months=-1, day=1) start_date = next_...
make_booking_in_past(end_date, end_date + timedelta(days=7), 'Meribel') # 1st week this month starting Saturday first_this_month = today + relativedelta(day=1) start_date = next_weekday(first_this_month, 5) make_booking_in_past(start_date, start_date + timedelta(days=3), 'Whistler') # later this mon...
# Rest Imports from rest_framework import status # Local Imports from ava_core.abstract.test_data import AvaCoreTestData from ava_core.integration.integration_ldap.models import LDAPIntegrationAdapter # Implementation class LDAPIntegrationAdapterTestData(AvaCoreTestData): """ Test data for LDAPIntegrationAdap...
integrationadapter_ptr': 'default', 'server': 'standard_char', } modified_ldap_integration_history = { 'ldap_password': 'standard_char', 'salt': 'standard_char', 'dump_dn': 'standard_char', 'ldap_user': 'standard_char', 'ldap_integration_history': '/example/2/', ...
lt': 'standard_char', 'dump_dn': 'standard_char', 'ldap_user': 'standard_char', 'integrationadapter_ptr': 'default', 'server': 'standard_char', } modified_integrationadapter_ptr = { 'ldap_password': 'standard_char', 'salt': 'standard_char', 'dump_dn': 'st...
"""Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"] Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of y...
r]]: store = {} for item in strs: key = ''.join(sorted(item)) if key in store: store[key].append(item) else: store[key] = [item] return store.values() if __name__ == '__main__': cases = [ ( ["eat", "t...
"nat", "tan"], ["bat"] ] ), ] # yapf: disable for case in cases: for S in [Solution]: result = S().groupAnagrams(case[0]) for l in case[1]: for item in l: found = False for ll in result:...
class Content(object): def __init__(self, type_=None, value=None): self._type = None self._value = None if type_ is not None: self.type = type_ if value is
not None: self.value = value @property def type(self): return self._type @type.setter def type(self, value): self._type = value @property def value(self): return self._value @value.setter def value(self, value): self._value = value def...
lf.value is not None: content["value"] = self.value return content
""" Implement the command-line tool interface. """ from __future__ import unicode_literals import argparse import os import sys import diff_cover from diff_cover.diff_reporter import GitDiffReporter from diff_cover.git_diff import GitDiffTool from diff_cover.git_path import GitPathTool from diff_cover.violations_report...
file_handle.close() else: LOGGER.error("Quality tool not recognized: '{0}'".format(tool)) exit(1) if __name__ == "__main__"
: main()
""" Support the OwnTracks platform. For more details about this platfor
m, please refer to the documentation at https://home-assis
tant.io/components/device_tracker.owntracks/ """ import json import logging import threading from collections import defaultdict import homeassistant.components.mqtt as mqtt from homeassistant.const import STATE_HOME from homeassistant.util import convert, slugify DEPENDENCIES = ['mqtt'] REGIONS_ENTERED = defaultdic...
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
ft_choose,right_choose) coin_map = {} def find_max_val_memo(coins,l,r): if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] if (l,r) in coin_map: return coin_map[(l,r)] left_choose = coins[l] + min(find_max_val_memo(coins,l+1,r - 1),find_max_val_memo(coins,...
oins,l,r-2)) max_val = max(left_choose,right_choose) coin_map[(l,r)] = max_val return max_val def find_max_val_bottom_up(coins): coins_len = len(coins) table = [[0] * coins_len for i in range(coins_len + 1)] for gap in range(coins_len): i = 0 for j in range(gap,coins_len): ...
# Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is...
)
request.session.flash( _('Thank you very much for sharing your opinion'), 'info', ) return HTTPFound(location=request.route_path('home')) elif 'cancel' in request.POST: return HTTPFound(location=request.route_path('home')) initial = {} if request.user is n...
# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2019-03-05 14:58 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('database', '0020_daymetda...
veField( model_name='daymetdata', name='id', ), migrations.AddField( model_name='userprofile', name='privateProjectList', field=models.TextField(blank=True), ), migrations.AlterField(
model_name='daymetdata', name='user', field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ters: the notebook parameters to set :type parameters: dict """ supports_lineage = True @apply_defaults def __init__(self, input_nb: Optional[str] = None, output_nb: Optional[str] = None, paramet
ers: Optional[Dict] = None, *args, **kwargs) -> None: super().__init__(*args, **kwargs) if input_nb: self.inlets.append(NoteBook(url=input_nb, parameters=parameters)) if output_nb: self.outlets.append(NoteBook(url=...
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging impor...
tional) """ super(PantsDaemon, self).__
init__(name='pantsd', metadata_base_dir=metadata_base_dir) self._logger = logging.getLogger(__name__) self._build_root = build_root self._work_dir = work_dir self._log_level = log_level self._log_dir = log_dir or os.path.join(work_dir, self.name) self._services = services or () self._socket_...
from ethereum.slogging import get_logger log = get_logger('eth.block_creation') from ethereum.block import Block, BlockHeader from ethereum.common import mk_block_from_prevstate, validate_header, \ verify_execution_results, validate_transaction_tree, \ set_execution_results, add_transactions, post_finalize from...
is None: temp_state = State.from_snapshot(chain.state.to_snapshot(root_only=True
), chain.env) else: temp_state = chain.mk_poststate_of_blockhash(parent.hash) cs = get_consensus_strategy(chain.env.config) # Initialize a block with the given parent and variables blk = mk_block_from_prevstate(chain, temp_state, timestamp, coinbase, extra_data) # Find and set the uncles ...
from django import forms from .models import PassType, Registration class SignupForm(forms.ModelForm): pass_type = forms.ModelChoiceField( queryset=PassType.objects.filter(active=True), widget=forms.widgets.RadioSelect(), ) class Meta: model = Registration fields = ( ...
s constraint ourselves """ email = self.cleaned_data.get("workshop_partner_email") qs = Registration.objects.filter(workshop_partner_email=email).exists() if email and qs: raise forms.ValidationError("Workshop parter already taken.") return email def clean_agree...
turn data def clean(self): cleaned_data = super().clean() email = cleaned_data.get("email") email_repeat = cleaned_data.get("email_repeat") ws_partner_email = cleaned_data.get("workshop_partner_email") if email != email_repeat: raise forms.ValidationError("Ensur...
# -*- coding: utf-8 -*- { 'name': "Better validation for Attendance", 'summary': """ Short (1 phrase/line) summary of the module's purpose, used as subtitle on modules listing or apps.openerp.com""", 'description': """ Long description of module's purpose """, 'author': "J...
/openerp/addons/base/mod
ule/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '8.0.0.1', # any module necessary for this one to work correctly 'depends': ['base','hr_attendance','hr_timesheet_improvement'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'view...
import sys import networkx as nx def main(graphml): g = nx.read_graphml(graphml)
nx.write_graphml(g, graphml) if __name__ == '__main__': main(sys.argv[1])
import numpy as np # Example taken from : http://cs231n.github.io/python-numpy-tutorial/#nump
y x = np.array([[1,2],[3,4]]) print np.sum(x) # Compute sum of all elements; prints "10" print np.sum(x, axis=0) # Compute sum of each
column; prints "[4 6]" print np.sum(x, axis=1) # Compute sum of each row; prints "[3 7]"
# This file is part of pybootchartgui. # pybootchartgui is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pybootchartgui is dis...
geSurface(cairo.FORMAT_ARGB32, w, h), \ lambda sfc: sfc.write_to_png(filename)), "pdf": (lambda w, h: cairo.PDFSurface(filename, w, h), lambda sfc: 0), "svg": (lambda w, h: cairo.S
VGSurface(filename, w, h), lambda sfc: 0) } if options.format is None: fmt = filename.rsplit('.', 1)[1] else: fmt = options.format if not (fmt in handlers): writer.error ("Unknown format '%s'." % fmt) return 10 make_surface, write_surface = handlers[fmt] (w, h)...
#!/usr/bin/env python import httplib try: import simplejson as json except ImportError: import json import os import sys from urlparse import urljoin try: import requests except ImportError: raise ImportError('Missing dependency "requests". Do ``pip install requests``.') try: import yaml except I...
Missing dependency "pyyaml". Do ``pip install pyyaml``.') # ST2 configuration ST2_CONFIG_FILE = './config.yaml' ST2_API_BASE_URL = 'http://localhost:9101/v1' ST2_AUTH_BASE_URL = 'http://localhost:9100' ST2_USERNAME = None ST2_PASSWORD = None
ST2_AUTH_TOKEN = None ST2_AUTH_PATH = 'tokens' ST2_WEBHOOKS_PATH = 'webhooks/st2/' ST2_TRIGGERS_PATH = 'triggertypes/' ST2_TRIGGERTYPE_PACK = 'sensu' ST2_TRIGGERTYPE_NAME = 'event_handler' ST2_TRIGGERTYPE_REF = '.'.join([ST2_TRIGGERTYPE_PACK, ST2_TRIGGERTYPE_NAME]) REGISTERED_WITH_ST2 = False OK_CODES = [httplib.OK...
# Copyright (C) 2012 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...
ITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # vim: tabstop=4 shiftwidth=4 softtabstop=4 import unittest import logging from nose.tools import eq_ from ryu.ofproto.ofproto_common import ...
est_struct_ofp_header(self): eq_(OFP_HEADER_PACK_STR, '!BBHI') eq_(OFP_HEADER_SIZE, 8) def test_define_constants(self): eq_(OFP_TCP_PORT, 6633) eq_(OFP_SSL_PORT, 6633)
tro: hijos = ComposicionFamiliar.objects.filter(persona = obj.productor,familia = '3').count() lista_hijos.append(hijos) hijas = ComposicionFamiliar.objects.filter(persona = obj.productor,familia = '4').count() lista_hijas.append(hijas) sumatoria = hijos + hijas lista_sumatoria.append(sumatoria) result ...
r obj in lista_mapa: if obj['latitud'] != None and obj['longitud'] != None: mapa.append((obj['nombre_
parcela'],obj['latitud'],obj['longitud'])) return render(request, template, locals()) def caracteristicas_parcela(request,template="granos_basicos/monitoreos/caracteristicas_parcela.html"): filtro = _queryset_filtrado(request) productores = filtro.distinct('productor').count() lista_parcela = [] lista_inclinado...
Filter.current().blacklist_ips assert u'1.1.0.0' in cblacklist assert u'1.1.0.1' in cblacklist assert u'1.1.1.0' in cblacklist assert u'1.2.0.0' not in cblacklist class RestrictedCourseTest(CacheIsolationTestCase): """Test RestrictedCourse model. """ ENABLED_CACHES = ['default...
ects.create(course_key=course_id) CountryAccessRule.objects.create( restricted_course=restricted_course1, rule_type=C
ountryAccessRule.WHITELIST_RULE, country=country ) with pytest.raises(IntegrityError): CountryAccessRule.objects.create( restricted_course=restricted_course1, rule_type=CountryAccessRule.BLACKLIST_RULE, country=country ...
import pyaf.Bench.TS_datasets as tsds impor
t tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 7,
transform = "Anscombe", sigma = 0.0, exog_count = 100, ar_order = 0);
#!/usr/bin/python3 #import nltk #import pattern.en from nltk import word_tokenize from nltk import pos_tag from nltk.corpus import wordnet #import nltk.fuf.linearizer from nltk.stem.wordnet import WordNetLemmatizer as wnl from re import sub import string import random from .genderPredictor import genderPredictor #nlt...
nt_list)-1)
print("\nTest index: "+ str(index+1)) #index = int(input("Enter a number between 1 and "+str(len(sent_list))+": "))-1 #print(sent_list[index]) output = e.transform(o_sent, sent_list[index]) print(output) #this would be the post
############################################################################# ## ## Copyright (C) 2015 The Qt Company Ltd. ## Contact: http://www.qt.io/licensing ## ## This file is part of Qt Creator. ## ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance wit...
Public License Usage ## Alternatively, this file may be used under the terms of the GNU Lesser ## General Public License version 2.1 or version 3 as published by the Free ## Software Foundation and appearing in the file LICENSE.LGPLv21 and ## LICENSE.LGPLv3 included in the packaging of this file. Please review the ## ...
icenses/lgpl.html and ## http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ## ## In addition, as a special exception, The Qt Company gives you certain additional ## rights. These rights are described in The Qt Company LGPL Exception ## version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ## ####...
from __future__ import print_function import fileinput from datetime import datetime for line in fileinput.input(): line = line.rstrip() # This condition removes CDX header lines i
f line[0] is ' ': continue # Extract just the timestamp from line timestamp = line.split(' ', 2)[1] # Datetiem format in CDX is 20121125005312 date_object = datetime.strptime(timestamp, '%Y%m%d%H%M%S') # print(date_object.s
trftime('%Y-%m-%d')) print(date_object.strftime('%Y-%m-%d %H:%M:%S'))
from redbreast.core.utils import * import pytest from uliweb import manage, functions import os def test_import(): a = CommonUtils.get_class('redbreast.core.spec.TaskSpec') assert str(a) == "<class 'redbreast.core.spec.task.TaskSpec'>" def test_import_not_exist(): a = CommonUtils.get_class('...
.spec.task.MultiChoiceTask', 'auto_simple_task' : 'redbreast.core.spec.task.AutoSimpleTask', 'auto_join_task' : 'redbreast.core.spec.task.AutoJoinTask', 'auto_choice_task'
: 'redbreast.core.spec.task.AutoChoiceTask', 'auto_split_task' : 'redbreast.core.spec.task.AutoSplitTask', 'auto_multichoice_task' :'redbreast.core.spec.task.AutoMultiChoiceTask', } for spec in maps: a = CommonUtils.get_spec(spec) assert s...
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Cathy Nangini <cnangini@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> #...
nels import read_layout from mne.io import read_raw_fif from mne.utils import slow_test, run_tests_if_main from mne.viz.evoked import _butterfly_onselect,
plot_compare_evokeds from mne.viz.utils import _fake_click # Set our plotters to test mode import matplotlib matplotlib.use('Agg') # for testing don't use X server warnings.simplefilter('always') # enable b/c these tests throw warnings base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') ev...
"""n-body simulator to derive TDV+TTV diagrams of planet-moon configurations. Credit for part of the source is given to https://github.com/akuchling/50-examples/blob/master/gravity.rst Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License """ import numpy import math import matplotlib.pylab as plt...
_jup #semimajor_axis = 1. * AU #[m] semimajor_axis = a_jup stellar_mass = M_sun radius_hill = semimajor_axis * (planet.mass / (3 * (stellar_mass))) ** (1./3) # Define parameters firstmoon = Body() firstmoon.mass = M_gan firstmoon.px = 0.4218 * 10**9 secondmoon = Body() secondmoon.mas
s = M_gan secondmoon.px = 0.48945554 * 10**9 thirdmoon = Body() thirdmoon.mass = M_gan thirdmoon.px = 0.59293316 * 10**9 fourthmoon = Body() fourthmoon.mass = M_gan fourthmoon.px = 0.77696224 * 10**9 fithmoon = Body() fithmoon.mass = M_gan fithmoon.px = 1.23335068 * 10**9 # Calculate start velocities firstmoon.vy ...
import platform import socket import sys from mule_local.JobGeneration import * from mule.JobPlatformResources import * from . import JobPlatformAutodetect import multiprocessing # Underscore defines symbols to be private _job_id = None def _whoami(depth=1): """ String of function name to recycle code ...
ted") content += "\n" return content def jobscript_get_exec_command(jg : JobGeneration): """ Prefix to executable command Returns ------- string multiline text for scripts """ p = jg.parallelizati
on content = """ """+p_gen_script_info(jg)+""" # mpiexec ... would be here without a line break EXEC=\""""+jg.compile.getProgramPath()+"""\" PARAMS=\""""+jg.runtime.getRuntimeOptions()+"""\" echo \"${EXEC} ${PARAMS}\" """ if jg.compile.sweet_mpi == 'enable': content += 'mpiexec -n '+str(p.num_ranks)+' ...