max_stars_repo_path
string
max_stars_repo_name
string
max_stars_count
int64
id
string
content
string
score
float64
int_score
int64
pypagai/models/model_lstm.py
gcouti/pypagAI
1
7
from keras import Model, Input from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten from keras.optimizers import Adam from pypagai.models.base import KerasModel class SimpleLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') conc = concatenate([story, question],) conc = Reshape((1, int(conc.shape[1])))(conc) conc = Permute((2, 1))(conc) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class EmbedLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Dropout(0.3)(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Dropout(0.3)(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class ConvLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, model_cfg): super().__init__(model_cfg) self._cfg = model_cfg def _create_network_(self): hidden = self._cfg['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Convolution1D(64, 3, padding='same')(eb_story) eb_story = Convolution1D(32, 3, padding='same')(eb_story) eb_story = Convolution1D(16, 3, padding='same')(eb_story) # eb_story = Flatten()(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Convolution1D(64, 3, padding='same')(eb_question) eb_question = Convolution1D(32, 3, padding='same')(eb_question) eb_question = Convolution1D(16, 3, padding='same')(eb_question) # eb_question = Flatten()(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
2.46875
2
Object_detection_image.py
hiperus0988/pyao
1
23
######## Image Object Detection Using Tensorflow-trained Classifier ######### # # Author: <NAME> # Date: 1/15/18 # Description: # This program uses a TensorFlow-trained classifier to perform object detection. # It loads the classifier uses it to perform object detection on an image. # It draws boxes and scores 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 import cv2 import numpy as np import tensorflow as tf import sys # 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 = 'test1.jpg' # Grab path to current working directory CWD_PATH = os.getcwd() # 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 = 6 # 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.GraphDef() with tf.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='') sess = tf.Session(graph=detection_graph) # 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') # 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 image = cv2.imread(PATH_TO_IMAGE) image_expanded = np.expand_dims(image, 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=8, min_score_thresh=0.60) # All the results have been drawn on image. Now display the image. cv2.imshow('Object detector', image) # Press any key to close the image cv2.waitKey(0) # Clean up cv2.destroyAllWindows()
2.90625
3
setup.py
giggslam/python-messengerbot-sdk
23
31
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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 re import sys from setuptools import setup from setuptools.command.test import test as TestCommand __version__ = '' with open('facebookbot/__about__.py', 'r') as fd: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fd: m = reg.match(line) if m: __version__ = m.group(1) break def _requirements(): with open('requirements.txt', 'r') as fd: return [name.strip() for name in fd.readlines()] with open('README.rst', 'r') as fd: long_description = fd.read() setup( name="fbsdk", version=__version__, author="<NAME>", author_email="<EMAIL>", maintainer="<NAME>", maintainer_email="<EMAIL>", url="https://github.com/boompieman/fbsdk", description="Facebook Messaging API SDK for Python", long_description=long_description, license='Apache License 2.0', packages=[ "facebookbot", "facebookbot.models" ], install_requires=_requirements(), classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Topic :: Software Development" ] )
1.34375
1
examples/mouse.py
ginkage/trackball-python
22
47
#!/usr/bin/env python import time import os import math from trackball import TrackBall print("""Trackball: Mouse Use the trackball as a mouse in Raspbian, with right-click when the switch is pressed. Press Ctrl+C to exit! """) trackball = TrackBall(interrupt_pin=4) trackball.set_rgbw(0, 0, 0, 0) # Check for xte (used to control mouse) use_xte = os.system('which xte') == 0 if use_xte == 0: raise RuntimeError("xte not found. Did you sudo apt install xautomation?") while True: up, down, left, right, switch, state = trackball.read() # Send movements and clicks to xte if switch: cmd = 'xte "mouseclick 1"' os.system(cmd) elif right or up or left or down: x = right - left x = math.copysign(x**2, x) y = down - up y = math.copysign(y**2, y) cmd = 'xte "mousermove {} {}"'.format(int(x), int(y)) os.system(cmd) time.sleep(0.0001)
2.53125
3
python/ray/ml/tests/test_torch_trainer.py
mgelbart/ray
22
63
import pytest import torch import ray from ray.ml.predictors.integrations.torch import TorchPredictor from ray.ml.train.integrations.torch import TorchTrainer from ray import train from ray.ml.examples.pytorch.torch_linear_example import train_func as linear_train_func @pytest.fixture def ray_start_4_cpus(): address_info = ray.init(num_cpus=4) yield address_info # The code after the yield will run as teardown code. ray.shutdown() @pytest.mark.parametrize("num_workers", [1, 2]) def test_torch_linear(ray_start_4_cpus, num_workers): def train_func(config): result = linear_train_func(config) assert len(result) == epochs assert result[-1]["loss"] < result[0]["loss"] num_workers = num_workers epochs = 3 scaling_config = {"num_workers": num_workers} config = {"lr": 1e-2, "hidden_size": 1, "batch_size": 4, "epochs": epochs} trainer = TorchTrainer( train_loop_per_worker=train_func, train_loop_config=config, scaling_config=scaling_config, ) trainer.fit() def test_torch_e2e(ray_start_4_cpus): def train_func(): model = torch.nn.Linear(1, 1) train.save_checkpoint(model=model) scaling_config = {"num_workers": 2} trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=scaling_config ) result = trainer.fit() predict_dataset = ray.data.range(3) class TorchScorer: def __init__(self): self.pred = TorchPredictor.from_checkpoint(result.checkpoint) def __call__(self, x): return self.pred.predict(x, dtype=torch.float) predictions = predict_dataset.map_batches( TorchScorer, batch_format="pandas", compute="actors" ) assert predictions.count() == 3 def test_torch_e2e_state_dict(ray_start_4_cpus): def train_func(): model = torch.nn.Linear(1, 1).state_dict() train.save_checkpoint(model=model) scaling_config = {"num_workers": 2} trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=scaling_config ) result = trainer.fit() # If loading from a state dict, a model definition must be passed in. with pytest.raises(ValueError): TorchPredictor.from_checkpoint(result.checkpoint) class TorchScorer: def __init__(self): self.pred = TorchPredictor.from_checkpoint( result.checkpoint, model=torch.nn.Linear(1, 1) ) def __call__(self, x): return self.pred.predict(x, dtype=torch.float) predict_dataset = ray.data.range(3) predictions = predict_dataset.map_batches( TorchScorer, batch_format="pandas", compute="actors" ) assert predictions.count() == 3 if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", "-x", __file__]))
1.976563
2
eoxserver/services/ows/wps/v10/encoders/parameters.py
constantinius/eoxserver_combined
1
79
#------------------------------------------------------------------------------- # # WPS 1.0 parameters' XML encoders # # Project: EOxServer <http://eoxserver.org> # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # #------------------------------------------------------------------------------- # Copyright (C) 2013 EOX IT Services GmbH # # 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 of this Software or works derived from this 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 eoxserver.services.ows.wps.parameters import ( LiteralData, ComplexData, BoundingBoxData, AllowedAny, AllowedEnum, AllowedRange, AllowedRangeCollection, AllowedByReference, ) from eoxserver.services.ows.wps.v10.util import ( OWS, WPS, NIL, ns_ows, ) #------------------------------------------------------------------------------- def encode_input_descr(prm): """ Encode process description input.""" elem = NIL("Input", *_encode_param_common(prm)) elem.attrib["minOccurs"] = ("1", "0")[bool(prm.is_optional)] elem.attrib["maxOccurs"] = "1" if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, True)) elif isinstance(prm, ComplexData): elem.append(_encode_complex(prm, True)) elif isinstance(prm, BoundingBoxData): elem.append(_encode_bbox(prm, True)) return elem def encode_output_descr(prm): """ Encode process description output.""" elem = NIL("Output", *_encode_param_common(prm)) if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, False)) elif isinstance(prm, ComplexData): elem.append(_encode_complex(prm, False)) elif isinstance(prm, BoundingBoxData): elem.append(_encode_bbox(prm, False)) return elem def encode_input_exec(prm): """ Encode common part of the execure response data input.""" return WPS("Input", *_encode_param_common(prm, False)) def encode_output_exec(prm): """ Encode common part of the execure response data output.""" return WPS("Output", *_encode_param_common(prm)) def encode_output_def(outdef): """ Encode the execure response output definition.""" attrib = {} if outdef.uom is not None: attrib['uom'] = outdef.uom if outdef.crs is not None: attrib['crs'] = outdef.crs if outdef.mime_type is not None: attrib['mimeType'] = outdef.mime_type if outdef.encoding is not None: attrib['encoding'] = outdef.encoding if outdef.schema is not None: attrib['schema'] = outdef.schema if outdef.as_reference is not None: attrib['asReference'] = 'true' if outdef.as_reference else 'false' return WPS("Output", *_encode_param_common(outdef, False), **attrib) def _encode_param_common(prm, title_required=True): """ Encode common sub-elements of all XML parameters.""" elist = [OWS("Identifier", prm.identifier)] if prm.title or title_required: elist.append(OWS("Title", prm.title or prm.identifier)) if prm.abstract: elist.append(OWS("Abstract", prm.abstract)) return elist #------------------------------------------------------------------------------- def _encode_literal(prm, is_input): dtype = prm.dtype elem = NIL("LiteralData" if is_input else "LiteralOutput") elem.append(OWS("DataType", dtype.name, **{ ns_ows("reference"): "http://www.w3.org/TR/xmlschema-2/#%s"%dtype.name, })) if prm.uoms: elem.append(NIL("UOMs", NIL("Default", OWS("UOM", prm.uoms[0])), NIL("Supported", *[OWS("UOM", u) for u in prm.uoms]) )) if is_input: elem.append(_encode_allowed_value(prm.allowed_values)) if prm.default is not None: elem.append(NIL("DefaultValue", str(prm.default))) return elem def _encode_allowed_value(avobj): enum, ranges, elist = None, [], [] if isinstance(avobj, AllowedAny): return OWS("AnyValue") elif isinstance(avobj, AllowedByReference): return WPS("ValuesReference", **{ ns_ows("reference"): avobj.url, "valuesForm": avobj.url, }) elif isinstance(avobj, AllowedEnum): enum = avobj elif isinstance(avobj, AllowedRange): ranges = [avobj] elif isinstance(avobj, AllowedRangeCollection): enum, ranges = avobj.enum, avobj.ranges else: raise TypeError("Invalid allowed value object! OBJ=%r"%avobj) dtype = avobj.dtype ddtype = dtype.get_diff_dtype() if enum is not None: elist.extend(OWS("Value", dtype.encode(v)) for v in enum.values) for range_ in ranges: attr, elms = {}, [] if range_.closure != 'closed': attr = {ns_ows("rangeClosure"): range_.closure} if range_.minval is not None: elms.append(OWS("MinimumValue", dtype.encode(range_.minval))) if range_.maxval is not None: elms.append(OWS("MaximumValue", dtype.encode(range_.maxval))) if range_.spacing is not None: elms.append(OWS("Spacing", ddtype.encode(range_.spacing))) elist.append(OWS("Range", *elms, **attr)) return OWS("AllowedValues", *elist) #------------------------------------------------------------------------------- def _encode_complex(prm, is_input): return NIL("ComplexData" if is_input else "ComplexOutput", NIL("Default", _encode_format(prm.default_format)), NIL("Supported", *[_encode_format(f) for f in prm.formats.itervalues()]) ) def _encode_format(frmt): elem = NIL("Format", NIL("MimeType", frmt.mime_type)) if frmt.encoding is not None: elem.append(NIL("Encoding", frmt.encoding)) if frmt.schema is not None: elem.append(NIL("Schema", frmt.schema)) return elem #------------------------------------------------------------------------------- def _encode_bbox(prm, is_input): return NIL("BoundingBoxData" if is_input else "BoundingBoxOutput", NIL("Default", NIL("CRS", prm.encode_crs(prm.default_crs))), NIL("Supported", *[NIL("CRS", prm.encode_crs(crs)) for crs in prm.crss]) )
1.226563
1
Complab assignment.py
peteboi/Python-Scripts
0
87
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def orbit(u): x,y,v_x,v_y = u r=np.hypot(x,y) #r= 1.521e+06 #M,G=1.989e+30,6.7e-11 M,G=20,110 f=G*M/r**3 return np.array([v_x,v_y,-f*x,-f*y]) def RK4(f,u,dt): k1=f(u)*dt k2=f(u+0.5*k1)*dt k3=f(u+0.5*k2)*dt k4=f(u+k3)*dt return u+(k1+2*k2+2*k3+k4)/6 def RK4_int(f,y0,tspan): y=np.zeros([len(tspan),len(y0)]) y[0,:] =y0 for k in range (1,len(tspan)): y[k,:] = RK4(f,y[k-1],tspan[k]-tspan[k-1]) return y dt=0.1 t = np.arange(0,10,dt) y0=np.array([10, 0.0, 10, 10]) sol_rk4=RK4_int(orbit,y0,t) x,y,v_x,v_y = sol_rk4.T plt.grid() plt.plot(x,y) plt.show()
2.296875
2
python_utilities/plotting/util.py
sdaxen/python_utilities
2
111
"""Utility functions for plotting. Author: <NAME> E-mail: <EMAIL>""" from collections import deque import numpy as np def rgb_to_hsv(rgb): """Convert RGB colors to HSV colors.""" r, g, b = tuple(map(float, rgb)) if any([r > 1, g > 1, b > 1]): r /= 255. g /= 255. b /= 255. mmax = max(r, g, b) mmin = min(r, g, b) c = mmax - mmin if (c == 0.): hp = 0. elif (mmax == r): hp = ((g - b) / c) % 6 elif (mmax == g): hp = ((b - r) / c) + 2 elif (mmax == b): hp = ((r - g) / c) + 4 h = 60 * hp v = mmax if (c == 0): s = 0 else: s = c / v return (h, s, v) def hsv_to_rgb(hsv): """Convert HSV colors to RGB colors.""" h, s, v = tuple(map(float, hsv)) c = v * s m = v - c hp = h / 60. x = c * (1. - abs((hp % 2) - 1.)) hp = int(hp) rgb = deque((c + m, x + m, m)) if (hp % 2): rgb.reverse() rgb.rotate((hp - 3) / 2) else: rgb.rotate(hp / 2) return tuple(rgb) def rgb_to_yuv(rgb): """Convert RGB colors to Y'UV colors, useful for comparison.""" rgbv = np.array(rgb).reshape(3, 1) if np.any(rgbv > 1.): rgbv = rgbv / 255. yuv = np.dot(np.array([[ .299, .587, .114], [-.14713, -.28886, .436], [ .615, -.51499, -.10001]], dtype=np.double), rgbv) return list(yuv) def yuv_to_rgb(yuv): """Convert Y'UV colors to RGB colors.""" yuvv = np.array(yuv).reshape(3, 1) rgb = np.dot(np.array([[1., 0., 1.13983], [1., -.39465, -.58060], [1., 2.03211, 0.]], dtype=np.double), yuvv) return list(rgb) def compute_yuv_dist(rgb1, rgb2): """Compute Euclidean Y'UV distance between RGB colors.""" yuv1 = rgb_to_yuv(rgb1) yuv2 = rgb_to_yuv(rgb2) return float(sum((np.array(yuv1) - np.array(yuv2))**2)**.5) def lighten_rgb(rgb, p=0.): """Lighten RGB colors by percentage p of total.""" h, s, v = rgb_to_hsv(rgb) hsv = (h, s, min(1, v + p)) return hsv_to_rgb(hsv)
2.625
3
mypy/server/aststrip.py
mmaryada27/mypy
0
135
"""Strip/reset AST in-place to match state after semantic analysis pass 1. Fine-grained incremental mode reruns semantic analysis (passes 2 and 3) and type checking for *existing* AST nodes (targets) when changes are propagated using fine-grained dependencies. AST nodes attributes are often changed during semantic analysis passes 2 and 3, and running semantic analysis again on those nodes would produce incorrect results, since these passes aren't idempotent. This pass resets AST nodes to reflect the state after semantic analysis pass 1, so that we can rerun semantic analysis. (The above is in contrast to behavior with modules that have source code changes, for which we reparse the entire module and reconstruct a fresh AST. No stripping is required in this case. Both modes of operation should have the same outcome.) Notes: * This is currently pretty fragile, as we must carefully undo whatever changes can be made in semantic analysis passes 2 and 3, including changes to symbol tables. * We reuse existing AST nodes because it makes it relatively straightforward to reprocess only a single target within a module efficiently. If there was a way to parse a single target within a file, in time proportional to the size of the target, we'd rather create fresh AST nodes than strip them. Alas, no such facility exists and building it is non-trivial. * Currently we don't actually reset all changes, but only those known to affect non-idempotent semantic analysis behavior. TODO: It would be more principled and less fragile to reset everything changed in semantic analysis pass 2 and later. * Reprocessing may recreate AST nodes (such as Var nodes, and TypeInfo nodes created with assignment statements) that will get different identities from the original AST. Thus running an AST merge is necessary after stripping, even though some identities are preserved. """ import contextlib from typing import Union, Iterator, Optional from mypy.nodes import ( Node, FuncDef, NameExpr, MemberExpr, RefExpr, MypyFile, FuncItem, ClassDef, AssignmentStmt, ImportFrom, Import, TypeInfo, SymbolTable, Var, CallExpr, Decorator, OverloadedFuncDef, SuperExpr, UNBOUND_IMPORTED, GDEF, MDEF, IndexExpr ) from mypy.traverser import TraverserVisitor def strip_target(node: Union[MypyFile, FuncItem, OverloadedFuncDef]) -> None: """Reset a fine-grained incremental target to state after semantic analysis pass 1. NOTE: Currently we opportunistically only reset changes that are known to otherwise cause trouble. """ visitor = NodeStripVisitor() if isinstance(node, MypyFile): visitor.strip_file_top_level(node) else: node.accept(visitor) class NodeStripVisitor(TraverserVisitor): def __init__(self) -> None: self.type = None # type: Optional[TypeInfo] self.names = None # type: Optional[SymbolTable] self.is_class_body = False # By default, process function definitions. If False, don't -- this is used for # processing module top levels. self.recurse_into_functions = True def strip_file_top_level(self, file_node: MypyFile) -> None: """Strip a module top-level (don't recursive into functions).""" self.names = file_node.names self.recurse_into_functions = False file_node.accept(self) def visit_class_def(self, node: ClassDef) -> None: """Strip class body and type info, but don't strip methods.""" node.info.type_vars = [] node.info.bases = [] node.info.abstract_attributes = [] node.info.mro = [] node.info.add_type_vars() node.info.tuple_type = None node.info.typeddict_type = None node.info._cache = set() node.info._cache_proper = set() node.base_type_exprs.extend(node.removed_base_type_exprs) node.removed_base_type_exprs = [] with self.enter_class(node.info): super().visit_class_def(node) def visit_func_def(self, node: FuncDef) -> None: if not self.recurse_into_functions: return node.expanded = [] node.type = node.unanalyzed_type with self.enter_method(node.info) if node.info else nothing(): super().visit_func_def(node) def visit_decorator(self, node: Decorator) -> None: node.var.type = None for expr in node.decorators: expr.accept(self) if self.recurse_into_functions: node.func.accept(self) def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> None: if not self.recurse_into_functions: return if node.impl: # Revert change made during semantic analysis pass 2. assert node.items[-1] is not node.impl node.items.append(node.impl) super().visit_overloaded_func_def(node) @contextlib.contextmanager def enter_class(self, info: TypeInfo) -> Iterator[None]: # TODO: Update and restore self.names old_type = self.type old_is_class_body = self.is_class_body self.type = info self.is_class_body = True yield self.type = old_type self.is_class_body = old_is_class_body @contextlib.contextmanager def enter_method(self, info: TypeInfo) -> Iterator[None]: # TODO: Update and restore self.names old_type = self.type old_is_class_body = self.is_class_body self.type = info self.is_class_body = False yield self.type = old_type self.is_class_body = old_is_class_body def visit_assignment_stmt(self, node: AssignmentStmt) -> None: node.type = node.unanalyzed_type if self.type and not self.is_class_body: # TODO: Handle multiple assignment if len(node.lvalues) == 1: lvalue = node.lvalues[0] if isinstance(lvalue, MemberExpr) and lvalue.is_new_def: # Remove defined attribute from the class symbol table. If is_new_def is # true for a MemberExpr, we know that it must be an assignment through # self, since only those can define new attributes. del self.type.names[lvalue.name] super().visit_assignment_stmt(node) def visit_import_from(self, node: ImportFrom) -> None: if node.assignments: node.assignments = [] else: if self.names: # Reset entries in the symbol table. This is necessary since # otherwise the semantic analyzer will think that the import # assigns to an existing name instead of defining a new one. for name, as_name in node.names: imported_name = as_name or name symnode = self.names[imported_name] symnode.kind = UNBOUND_IMPORTED symnode.node = None def visit_import(self, node: Import) -> None: if node.assignments: node.assignments = [] else: if self.names: # Reset entries in the symbol table. This is necessary since # otherwise the semantic analyzer will think that the import # assigns to an existing name instead of defining a new one. for name, as_name in node.ids: imported_name = as_name or name initial = imported_name.split('.')[0] symnode = self.names[initial] symnode.kind = UNBOUND_IMPORTED symnode.node = None def visit_name_expr(self, node: NameExpr) -> None: # Global assignments are processed in semantic analysis pass 1, and we # only want to strip changes made in passes 2 or later. if not (node.kind == GDEF and node.is_new_def): # Remove defined attributes so that they can recreated during semantic analysis. if node.kind == MDEF and node.is_new_def: self.strip_class_attr(node.name) self.strip_ref_expr(node) def visit_member_expr(self, node: MemberExpr) -> None: self.strip_ref_expr(node) # These need to cleared for member expressions but not for other RefExprs since # these can change based on changed in a base class. node.is_new_def = False node.is_inferred_def = False if self.is_duplicate_attribute_def(node): # This is marked as an instance variable definition but a base class # defines an attribute with the same name, and we can't have # multiple definitions for an attribute. Defer to the base class # definition. self.strip_class_attr(node.name) node.def_var = None super().visit_member_expr(node) def visit_index_expr(self, node: IndexExpr) -> None: node.analyzed = None # was a type alias super().visit_index_expr(node) def strip_class_attr(self, name: str) -> None: if self.type is not None: del self.type.names[name] def is_duplicate_attribute_def(self, node: MemberExpr) -> bool: if not node.is_inferred_def: return False assert self.type is not None, "Internal error: Member defined outside class" if node.name not in self.type.names: return False return any(info.get(node.name) is not None for info in self.type.mro[1:]) def strip_ref_expr(self, node: RefExpr) -> None: node.kind = None node.node = None node.fullname = None node.is_new_def = False node.is_inferred_def = False def visit_call_expr(self, node: CallExpr) -> None: node.analyzed = None super().visit_call_expr(node) def visit_super_expr(self, node: SuperExpr) -> None: node.info = None super().visit_super_expr(node) # TODO: handle more node types def is_self_member_ref(memberexpr: MemberExpr) -> bool: """Does memberexpr refer to an attribute of self?""" # TODO: Merge with is_self_member_ref in semanal.py. if not isinstance(memberexpr.expr, NameExpr): return False node = memberexpr.expr.node return isinstance(node, Var) and node.is_self @contextlib.contextmanager def nothing() -> Iterator[None]: yield
1.726563
2
src/main/python/taf/foundation/api/ui/aut.py
WesleyPeng/uiXautomation
6
143
# # 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 taf.foundation.utils import ConnectionCache class AUT(object): cache = None current = None def __init__( self, name=None, identifier=None, **kwargs ): if not AUT.cache: AUT.cache = ConnectionCache(identifier) self.id = self.cache.register( self._create_instance(name, **kwargs), identifier ) AUT.current = self @staticmethod def launch(app_location, **kwargs): raise NotImplementedError( 'Launch application' ) def activate(self): if self.id != self.cache.current_key: self.cache.current_key = self.id AUT.current = self def take_screenshot(self): self.activate() return self.get_screenshot_data() def close(self): self.cache.close(self.id) if not self.cache.current: AUT.cache = None AUT.current = None def get_screenshot_data(self): raise NotImplementedError( 'Get screenshot data from AUT' ) def _create_instance(self, name, **kwargs): raise NotImplementedError( 'Create instance of AUT' )
1.234375
1
superneurons/tools/img_val/main.py
Phaeton-lang/baselines
0
159
# Created by ay27 at 17/4/9 import os import matplotlib.pyplot as plt import struct import numpy as np def trans(row): return list(map(lambda x: np.uint8(x), row)) def read_image(filename): with open(filename, mode='rb') as file: n = file.read(8) n = struct.unpack("<Q", n)[0] c = file.read(8) c = struct.unpack("<Q", c)[0] h = file.read(8) h = struct.unpack("<Q", h)[0] w = file.read(8) w = struct.unpack("<Q", w)[0] print(n, c, h, w) for ii in range(n): r = trans(file.read(h*w)) g = trans(file.read(h*w)) b = trans(file.read(h*w)) if ii == 100: break print(file.tell() == os.fstat(file.fileno()).st_size) img = np.array([r,g,b]).transpose(1,0).reshape(h,w,c) print(img.shape) plt.imshow(img) plt.show() def read_label(path, ground_truth=None): with open(path, 'rb') as file: n = file.read(8) n = struct.unpack("<Q", n)[0] c = file.read(8) c = struct.unpack("<Q", c)[0] h = file.read(8) h = struct.unpack("<Q", h)[0] w = file.read(8) w = struct.unpack("<Q", w)[0] print(n, c, h, w) label = [] sets = set() while not (file.tell() == os.fstat(file.fileno()).st_size): ch = file.read(4) num = struct.unpack("<l", ch)[0] label.append(num) sets.add(num) # print(file.tell() == os.fstat(file.fileno()).st_size) print(label) print(len(label)) # print(label[900],label[901], label[902], label[903], label[904]) return label # if ground_truth: # g = [] # with open(ground_truth) as file: # for line in file: # g.append(int(line.split(' ')[1])) # np.testing.assert_array_equal(g, label) if __name__ == '__main__': # read_image('../../data/ilsvrc2012/img.bin') # read_label('../../data/ilsvrc2012/label.bin', '../../data/ilsvrc2012/val.txt') # read_image('../../build/cifar100_train_image.bin') # read_label('../../build/cifar100_train_label.bin') read_image('../../build/val_data_8.bin') for i in range(10): read_label('../../build/val_label_%d.bin' % i) # labels = [] # for i in range(10): # labels.append(read_label('../../build/val_label_%d.bin' % i)) # # ground = [] # with open('../../build/shuffled_list') as file: # ground.append()
2.109375
2
napari/_qt/dialogs/qt_plugin_dialog.py
kne42/napari
0
167
import os import sys from pathlib import Path from typing import Sequence from napari_plugin_engine.dist import standard_metadata from napari_plugin_engine.exceptions import PluginError from qtpy.QtCore import QEvent, QProcess, QProcessEnvironment, QSize, Qt, Slot from qtpy.QtGui import QFont, QMovie from qtpy.QtWidgets import ( QCheckBox, QDialog, QFrame, QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QPushButton, QSizePolicy, QSplitter, QTextEdit, QVBoxLayout, QWidget, ) import napari.resources from ...plugins import plugin_manager from ...plugins.pypi import ( ProjectInfo, iter_napari_plugin_info, normalized_name, ) from ...utils._appdirs import user_plugin_dir, user_site_packages from ...utils.misc import parse_version, running_as_bundled_app from ...utils.translations import trans from ..qthreading import create_worker from ..widgets.qt_eliding_label import ElidingLabel from ..widgets.qt_plugin_sorter import QtPluginSorter from .qt_plugin_report import QtPluginErrReporter # TODO: add error icon and handle pip install errors # TODO: add queue to handle clicks when already processing class Installer: def __init__(self, output_widget: QTextEdit = None): from ...plugins import plugin_manager # create install process self._output_widget = None self.process = QProcess() self.process.setProgram(sys.executable) self.process.setProcessChannelMode(QProcess.MergedChannels) self.process.readyReadStandardOutput.connect(self._on_stdout_ready) # setup process path env = QProcessEnvironment() combined_paths = os.pathsep.join( [user_site_packages(), env.systemEnvironment().value("PYTHONPATH")] ) env.insert("PYTHONPATH", combined_paths) # use path of parent process env.insert( "PATH", QProcessEnvironment.systemEnvironment().value("PATH") ) self.process.setProcessEnvironment(env) self.process.finished.connect(lambda: plugin_manager.discover()) self.process.finished.connect(lambda: plugin_manager.prune()) self.set_output_widget(output_widget) def set_output_widget(self, output_widget: QTextEdit): if output_widget: self._output_widget = output_widget self.process.setParent(output_widget) def _on_stdout_ready(self): if self._output_widget: text = self.process.readAllStandardOutput().data().decode() self._output_widget.append(text) def install(self, pkg_list: Sequence[str]): cmd = ['-m', 'pip', 'install', '--upgrade'] if running_as_bundled_app() and sys.platform.startswith('linux'): cmd += [ '--no-warn-script-location', '--prefix', user_plugin_dir(), ] self.process.setArguments(cmd + list(pkg_list)) if self._output_widget: self._output_widget.clear() self.process.start() def uninstall(self, pkg_list: Sequence[str]): args = ['-m', 'pip', 'uninstall', '-y'] self.process.setArguments(args + list(pkg_list)) if self._output_widget: self._output_widget.clear() self.process.start() for pkg in pkg_list: plugin_manager.unregister(pkg) class PluginListItem(QFrame): def __init__( self, package_name: str, version: str = '', url: str = '', summary: str = '', author: str = '', license: str = "UNKNOWN", *, plugin_name: str = None, parent: QWidget = None, enabled: bool = True, ): super().__init__(parent) self.setup_ui(enabled) if plugin_name: self.plugin_name.setText(plugin_name) self.package_name.setText(f"{package_name} {version}") self.summary.setText(summary) self.package_author.setText(author) self.action_button.setText(trans._("uninstall")) self.action_button.setObjectName("remove_button") self.enabled_checkbox.setChecked(enabled) if PluginError.get(plugin_name=plugin_name): def _show_error(): rep = QtPluginErrReporter( parent=self._get_dialog(), initial_plugin=plugin_name ) rep.setWindowFlags(Qt.Sheet) close = QPushButton(trans._("close"), rep) rep.layout.addWidget(close) rep.plugin_combo.hide() close.clicked.connect(rep.close) rep.open() self.error_indicator.clicked.connect(_show_error) self.error_indicator.show() self.summary.setIndent(18) else: self.summary.setIndent(38) else: self.plugin_name.setText(package_name) self.package_name.setText(version) self.summary.setText(summary) self.package_author.setText(author) self.action_button.setText(trans._("install")) self.enabled_checkbox.hide() def _get_dialog(self) -> QDialog: p = self.parent() while not isinstance(p, QDialog) and p.parent(): p = p.parent() return p def setup_ui(self, enabled=True): self.v_lay = QVBoxLayout(self) self.v_lay.setContentsMargins(-1, 6, -1, 6) self.v_lay.setSpacing(0) self.row1 = QHBoxLayout() self.row1.setSpacing(6) self.enabled_checkbox = QCheckBox(self) self.enabled_checkbox.setChecked(enabled) self.enabled_checkbox.stateChanged.connect(self._on_enabled_checkbox) self.enabled_checkbox.setToolTip(trans._("enable/disable")) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.enabled_checkbox.sizePolicy().hasHeightForWidth() ) self.enabled_checkbox.setSizePolicy(sizePolicy) self.enabled_checkbox.setMinimumSize(QSize(20, 0)) self.enabled_checkbox.setText("") self.row1.addWidget(self.enabled_checkbox) self.plugin_name = QLabel(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.plugin_name.sizePolicy().hasHeightForWidth() ) self.plugin_name.setSizePolicy(sizePolicy) font15 = QFont() font15.setPointSize(15) self.plugin_name.setFont(font15) self.row1.addWidget(self.plugin_name) self.package_name = QLabel(self) self.package_name.setAlignment( Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter ) self.row1.addWidget(self.package_name) self.action_button = QPushButton(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.action_button.sizePolicy().hasHeightForWidth() ) self.action_button.setSizePolicy(sizePolicy) self.row1.addWidget(self.action_button) self.v_lay.addLayout(self.row1) self.row2 = QHBoxLayout() self.error_indicator = QPushButton() self.error_indicator.setObjectName("warning_icon") self.error_indicator.setCursor(Qt.PointingHandCursor) self.error_indicator.hide() self.row2.addWidget(self.error_indicator) self.row2.setContentsMargins(-1, 4, 0, -1) self.summary = ElidingLabel(parent=self) sizePolicy = QSizePolicy( QSizePolicy.MinimumExpanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.summary.sizePolicy().hasHeightForWidth() ) self.summary.setSizePolicy(sizePolicy) self.summary.setObjectName("small_text") self.row2.addWidget(self.summary) self.package_author = QLabel(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.package_author.sizePolicy().hasHeightForWidth() ) self.package_author.setSizePolicy(sizePolicy) self.package_author.setObjectName("small_text") self.row2.addWidget(self.package_author) self.v_lay.addLayout(self.row2) def _on_enabled_checkbox(self, state: int): """Called with `state` when checkbox is clicked.""" plugin_manager.set_blocked(self.plugin_name.text(), not state) class QPluginList(QListWidget): def __init__(self, parent: QWidget, installer: Installer): super().__init__(parent) self.installer = installer self.setSortingEnabled(True) @Slot(ProjectInfo) def addItem( self, project_info: ProjectInfo, plugin_name=None, enabled=True ): # don't add duplicates if ( self.findItems(project_info.name, Qt.MatchFixedString) and not plugin_name ): return # including summary here for sake of filtering below. searchable_text = project_info.name + " " + project_info.summary item = QListWidgetItem(searchable_text, parent=self) item.version = project_info.version super().addItem(item) widg = PluginListItem( *project_info, parent=self, plugin_name=plugin_name, enabled=enabled, ) method = getattr( self.installer, 'uninstall' if plugin_name else 'install' ) widg.action_button.clicked.connect(lambda: method([project_info.name])) item.setSizeHint(widg.sizeHint()) self.setItemWidget(item, widg) @Slot(ProjectInfo) def tag_outdated(self, project_info: ProjectInfo): for item in self.findItems(project_info.name, Qt.MatchFixedString): current = item.version latest = project_info.version if parse_version(current) >= parse_version(latest): continue if hasattr(item, 'outdated'): # already tagged it continue item.outdated = True widg = self.itemWidget(item) update_btn = QPushButton( trans._("update (v{latest})", latest=latest), widg ) update_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) update_btn.clicked.connect( lambda: self.installer.install([item.text()]) ) widg.row1.insertWidget(3, update_btn) def filter(self, text: str): """Filter items to those containing `text`.""" shown = self.findItems(text, Qt.MatchContains) for i in range(self.count()): item = self.item(i) item.setHidden(item not in shown) class QtPluginDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.installer = Installer() self.setup_ui() self.installer.set_output_widget(self.stdout_text) self.installer.process.started.connect(self._on_installer_start) self.installer.process.finished.connect(self._on_installer_done) self.refresh() def _on_installer_start(self): self.show_status_btn.setChecked(True) self.working_indicator.show() self.process_error_indicator.hide() def _on_installer_done(self, exit_code, exit_status): self.working_indicator.hide() if exit_code: self.process_error_indicator.show() else: self.show_status_btn.setChecked(False) self.refresh() self.plugin_sorter.refresh() def refresh(self): self.installed_list.clear() self.available_list.clear() # fetch installed from ...plugins import plugin_manager plugin_manager.discover() # since they might not be loaded yet already_installed = set() for plugin_name, mod_name, distname in plugin_manager.iter_available(): # not showing these in the plugin dialog if plugin_name in ('napari_plugin_engine',): continue if distname: already_installed.add(distname) meta = standard_metadata(distname) else: meta = {} self.installed_list.addItem( ProjectInfo( normalized_name(distname or ''), meta.get('version', ''), meta.get('url', ''), meta.get('summary', ''), meta.get('author', ''), meta.get('license', ''), ), plugin_name=plugin_name, enabled=plugin_name in plugin_manager.plugins, ) # self.v_splitter.setSizes([70 * self.installed_list.count(), 10, 10]) # fetch available plugins self.worker = create_worker(iter_napari_plugin_info) def _handle_yield(project_info): if project_info.name in already_installed: self.installed_list.tag_outdated(project_info) else: self.available_list.addItem(project_info) self.worker.yielded.connect(_handle_yield) self.worker.finished.connect(self.working_indicator.hide) self.worker.finished.connect(self._update_count_in_label) self.worker.start() def setup_ui(self): self.resize(1080, 640) vlay_1 = QVBoxLayout(self) self.h_splitter = QSplitter(self) vlay_1.addWidget(self.h_splitter) self.h_splitter.setOrientation(Qt.Horizontal) self.v_splitter = QSplitter(self.h_splitter) self.v_splitter.setOrientation(Qt.Vertical) self.v_splitter.setMinimumWidth(500) self.plugin_sorter = QtPluginSorter(parent=self.h_splitter) self.plugin_sorter.layout().setContentsMargins(2, 0, 0, 0) self.plugin_sorter.hide() installed = QWidget(self.v_splitter) lay = QVBoxLayout(installed) lay.setContentsMargins(0, 2, 0, 2) self.installed_label = QLabel(trans._("Installed Plugins")) self.installed_filter = QLineEdit() self.installed_filter.setPlaceholderText("search...") self.installed_filter.setMaximumWidth(350) self.installed_filter.setClearButtonEnabled(True) mid_layout = QHBoxLayout() mid_layout.addWidget(self.installed_label) mid_layout.addWidget(self.installed_filter) mid_layout.addStretch() lay.addLayout(mid_layout) self.installed_list = QPluginList(installed, self.installer) self.installed_filter.textChanged.connect(self.installed_list.filter) lay.addWidget(self.installed_list) uninstalled = QWidget(self.v_splitter) lay = QVBoxLayout(uninstalled) lay.setContentsMargins(0, 2, 0, 2) self.avail_label = QLabel(trans._("Available Plugins")) self.avail_filter = QLineEdit() self.avail_filter.setPlaceholderText("search...") self.avail_filter.setMaximumWidth(350) self.avail_filter.setClearButtonEnabled(True) mid_layout = QHBoxLayout() mid_layout.addWidget(self.avail_label) mid_layout.addWidget(self.avail_filter) mid_layout.addStretch() lay.addLayout(mid_layout) self.available_list = QPluginList(uninstalled, self.installer) self.avail_filter.textChanged.connect(self.available_list.filter) lay.addWidget(self.available_list) self.stdout_text = QTextEdit(self.v_splitter) self.stdout_text.setReadOnly(True) self.stdout_text.setObjectName("pip_install_status") self.stdout_text.hide() buttonBox = QHBoxLayout() self.working_indicator = QLabel(trans._("loading ..."), self) sp = self.working_indicator.sizePolicy() sp.setRetainSizeWhenHidden(True) self.working_indicator.setSizePolicy(sp) self.process_error_indicator = QLabel(self) self.process_error_indicator.setObjectName("error_label") self.process_error_indicator.hide() load_gif = str(Path(napari.resources.__file__).parent / "loading.gif") mov = QMovie(load_gif) mov.setScaledSize(QSize(18, 18)) self.working_indicator.setMovie(mov) mov.start() self.direct_entry_edit = QLineEdit(self) self.direct_entry_edit.installEventFilter(self) self.direct_entry_edit.setPlaceholderText( trans._('install by name/url, or drop file...') ) self.direct_entry_btn = QPushButton(trans._("Install"), self) self.direct_entry_btn.clicked.connect(self._install_packages) self.show_status_btn = QPushButton(trans._("Show Status"), self) self.show_status_btn.setFixedWidth(100) self.show_sorter_btn = QPushButton(trans._("<< Show Sorter"), self) self.close_btn = QPushButton(trans._("Close"), self) self.close_btn.clicked.connect(self.accept) buttonBox.addWidget(self.show_status_btn) buttonBox.addWidget(self.working_indicator) buttonBox.addWidget(self.direct_entry_edit) buttonBox.addWidget(self.direct_entry_btn) buttonBox.addWidget(self.process_error_indicator) buttonBox.addSpacing(60) buttonBox.addWidget(self.show_sorter_btn) buttonBox.addWidget(self.close_btn) buttonBox.setContentsMargins(0, 0, 4, 0) vlay_1.addLayout(buttonBox) self.show_status_btn.setCheckable(True) self.show_status_btn.setChecked(False) self.show_status_btn.toggled.connect(self._toggle_status) self.show_sorter_btn.setCheckable(True) self.show_sorter_btn.setChecked(False) self.show_sorter_btn.toggled.connect(self._toggle_sorter) self.v_splitter.setStretchFactor(1, 2) self.h_splitter.setStretchFactor(0, 2) self.avail_filter.setFocus() def _update_count_in_label(self): count = self.available_list.count() self.avail_label.setText( trans._("Available Plugins ({count})", count=count) ) def eventFilter(self, watched, event): if event.type() == QEvent.DragEnter: # we need to accept this event explicitly to be able # to receive QDropEvents! event.accept() if event.type() == QEvent.Drop: md = event.mimeData() if md.hasUrls(): files = [url.toLocalFile() for url in md.urls()] self.direct_entry_edit.setText(files[0]) return True return super().eventFilter(watched, event) def _toggle_sorter(self, show): if show: self.show_sorter_btn.setText(trans._(">> Hide Sorter")) self.plugin_sorter.show() else: self.show_sorter_btn.setText(trans._("<< Show Sorter")) self.plugin_sorter.hide() def _toggle_status(self, show): if show: self.show_status_btn.setText(trans._("Hide Status")) self.stdout_text.show() else: self.show_status_btn.setText(trans._("Show Status")) self.stdout_text.hide() def _install_packages(self, packages: Sequence[str] = ()): if not packages: _packages = self.direct_entry_edit.text() if os.path.exists(_packages): packages = [_packages] else: packages = _packages.split() self.direct_entry_edit.clear() if packages: self.installer.install(packages) if __name__ == "__main__": from qtpy.QtWidgets import QApplication app = QApplication([]) w = QtPluginDialog() w.show() app.exec_()
1.578125
2
main.py
vkumarma/Complete-Interpreter
0
191
import re import sys class Lexer: def __init__(self, inp_str): self.index = 0 self.s = inp_str def get_char(self): if self.index < len(self.s): var = self.s[self.index] self.index += 1 return var input_file = open(str(sys.argv[1]), 'r') # Open file for reading line = input_file.read() # "if z then while x * 4 - 2 do skip endwhile else x := 7 endif; y := 1" input_string = line.strip("\n") lexer = Lexer(input_string) hashtable = {} tokens_list = [] def token_check(input): if re.fullmatch("if|then|else|endif|while|do|endwhile|skip", input): hashtable[input] = "KEYWORD" tokens_list.append(input) elif re.search("([a-z]|[A-Z])([a-z]|[A-Z]|[0-9])*", input): hashtable[input] = "IDENTIFIER" tokens_list.append(input) elif re.search("[0-9]+", input): hashtable[input] = "NUMBER" tokens_list.append(input) elif re.fullmatch("\+|\-|\*|/|\(|\)|:=|;", input): hashtable[input] = "SYMBOL" tokens_list.append(input) else: hashtable[input] = "ERROR READING" def digit(curr_char, lexer): sub = "" while (curr_char.isdigit()): sub += curr_char curr_char = lexer.get_char() if curr_char == None: break new.append(curr_char) return sub def longest_sub_string(curr_char, lexer): sub = "" while (curr_char.isalpha() or curr_char.isdigit()): sub += curr_char curr_char = lexer.get_char() if curr_char == None: break new.append(curr_char) return sub def symbol(curr_char, lexer): # print(curr_char) sym = curr_char curr_char = lexer.get_char() new.append(curr_char) return sym def assignment(curr_char, lexer): sub = curr_char next_char = lexer.get_char() if next_char == "=": sub += next_char new.append(next_char) return sub new.append(lexer.get_char()) return sub new = [] # keeping track of current char. curr_char = lexer.get_char() while (curr_char != None): while (curr_char == ' ' or curr_char == ''): curr_char = lexer.get_char() if (curr_char.isdigit()): token_check(digit(curr_char, lexer)) curr_char = new.pop() elif (curr_char.isalpha()): token_check(longest_sub_string(curr_char, lexer)) curr_char = new.pop() elif curr_char in "+-/*();": token_check(symbol(curr_char, lexer)) curr_char = new.pop() elif curr_char == ":": token_check(assignment(curr_char, lexer)) curr_char = new.pop() if curr_char == "=": curr_char = lexer.get_char() else: token_check(curr_char) curr_char = lexer.get_char() def tokens(): return hashtable # print(tokens_list) # print(tokens())
2.71875
3
aws-regions.py
groorj/cloud-regions
0
199
import json import logging import os import inspect import urllib import urllib.request from urllib.error import HTTPError # logger logger = logging.getLogger() logger_level = logging.getLevelName(os.environ['LOGGER_LEVEL']) logger.setLevel(logger_level) # validate access def validate_access(event, context): logger.debug("Inside function: [%s]", inspect.currentframe().f_code.co_name) logger.debug("RESTRICTED_ACCESS_ENABLED: [%s]", os.environ['RESTRICTED_ACCESS_ENABLED']) error_message = "You are not allowed, get out!" if os.environ['RESTRICTED_ACCESS_ENABLED'] == 'true': logger.info("Restricted access is enabled") logger.info("Value for header [%s] is: [%s]", os.environ['RESTRICTED_ACCESS_HTTP_HEADER'], event["headers"][os.environ['RESTRICTED_ACCESS_HTTP_HEADER']]) if event["headers"][os.environ['RESTRICTED_ACCESS_HTTP_HEADER']] != os.environ['RESTRICTED_ACCESS_SECRET']: logger.info("Key provided is not valid") logger.debug("Error: [%s]", error_message) http_code = 403 raise ValueError(http_code, error_message) else: logger.info("Key provided is valid") else: logger.info("Restricted access is NOT enabled") # create response def create_response_new(status_code, message_body): logger.debug("Inside function: [%s]", inspect.currentframe().f_code.co_name) return { 'statusCode': str(status_code), 'body': json.dumps(message_body), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, } # download json file def get_json(): logger.debug("Inside function: [%s]", inspect.currentframe().f_code.co_name) try: response = urllib.request.urlopen(os.environ['AWS_REGIONS_JSON_URL']) except HTTPError as err: # catch HTTP error logger.debug("HTTP error: [%s]", err) raise json_data = json.loads(response.read()) return json_data # entry point -> return region info def get_region_info(event, context): logger.debug("Inside function: [%s]", inspect.currentframe().f_code.co_name) return_info_final = {} # validate the access to this resource try: validate_access(event, context) except ValueError as err: return_info_final['request'] = { "request_status": "Fail", "error_message": err.args[1], "http_error_code": err.args[0] } return create_response_new(err.args[0], return_info_final) # get region info region_code = event['pathParameters']['region_code'] logger.debug("region_code: [%s]", region_code) try: json_data = get_json() except HTTPError as err: # http_code = err.code http_code = 500 return_info_final['request'] = { "request_status": "Fail", "error_message": "Error getting Regions information.", "http_error_code": err.code } return create_response_new(http_code, return_info_final) # logger.debug("json_data: [%s]", json_data) # logger.debug("type(json_data): [%s]", type(json_data)) for element in json_data['data']: # logger.debug("code: [%s] && region_code: [%s]", element['code'], region_code) if element['code'] == region_code: logger.info("region_code found") http_code = 200 return_info_final['request'] = { "request_status": "Success" } return_info_final['info'] = json_data['info'] return_info_final['data'] = element break else: logger.info("region_code NOT found") return_info = "Region code NOT found." http_code = 404 return_info_final['request'] = { "request_status": "Fail", "error_message": "Region code NOT found.", "http_error_code": http_code } return create_response_new(http_code, return_info_final) # entry point -> return region info def get_all_regions_info(event, context): logger.debug("Inside function: [%s]", inspect.currentframe().f_code.co_name) return_info_final = {} # validate the access to this resource try: validate_access(event, context) except ValueError as err: return_info_final['request'] = { "request_status": "Fail", "error_message": err.args[1], "http_error_code": err.args[0] } return create_response_new(err.args[0], return_info_final) # get regions info try: json_data = get_json() except HTTPError as err: # http_code = err.code http_code = 500 return_info_final['request'] = { "request_status": "Fail", "error_message": "Error getting Regions information.", "http_error_code": err.code } return create_response_new(http_code, return_info_final) logger.debug("json_data: [%s]", json_data) http_code = 200 return_info_final['request'] = { "request_status": "Success" } return_info_final['info'] = json_data['info'] return_info_final['data'] = json_data['data'] return create_response_new(http_code, return_info_final) # End;
1.796875
2
apps/core/migrations/0001_initial.py
Visualway/Vitary
4
263
# Generated by Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], }, ), ]
0.964844
1
rpython/annotator/annrpython.py
microvm/pypy-mu
0
295
from __future__ import absolute_import import types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator import model as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger("annrpython") class RPythonAnnotator(object): """Block annotator for RPython. See description in doc/translation.txt.""" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator is None: # interface for tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated = {} # set of blocks already seen self.added_blocks = None # see processblock() below self.links_followed = {} # set of links that have ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not to annotate again self.blocked_blocks = {} # set of {blocked_block: (graph, index)} # --- the following information is recorded for debugging --- self.blocked_graphs = {} # set of graphs that have blocked blocks # --- end of debugging information --- self.frozen = False if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = """translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks""".split() ret = self.__dict__.copy() for key, value in ret.items(): if key not in attrs: assert type(value) is dict, ( "%r is not dict. please update %s.__getstate__" % (key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): """Recursively build annotations about the specific entry point.""" assert isinstance(function, types.FunctionType), "fix that!" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and set their type args_s = [self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete() # invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of args # register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): """Return the known type of a control flow graph variable, defaulting to 'object'.""" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return object else: raise TypeError("Variable or Constant instance expected, " "got %r" % (variable,)) def getuserclassdefinitions(self): """Return a list of ClassDefs.""" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): """Register an entry point into block with the given input cells.""" if graph in self.fixed_graphs: # special case for annotating/rtyping in several phases: calling # a graph that has already been rtyped. Safety-check the new # annotations that are passed in, and don't annotate the old # graph -- it's already low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): """Process pending blocks until none is left.""" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make sure that the return variables of all graphs is annotated if self.added_blocks is not None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block, done in self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): """Check that the annotation results are valid""" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): "Gives the SomeValue corresponding to the given Variable or Constant." if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r' % (arg,)) def binding(self, arg): "Gives the SomeValue corresponding to the given Variable or Constant." s_arg = self.annotation(arg) if s_arg is None: raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if s_old is not None: if not s_value.contains(s_old): log.WARNING("%s does not contain %s" % (s_value, s_old)) log.WARNING("%s" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self, msg, pos=None): if pos is None: try: pos = self.bookkeeper.position_key except AttributeError: pos = '?' if pos != '?': pos = self.whereami(pos) log.WARNING("%s/ %s" % (pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of call # points to this func which triggers a reflow whenever the # return block of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence): def callback(): whence(self, graph) else: callback = whence callpositions[callback] = True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value v = graph.getreturnvar() try: return self.binding(v) except KeyError: # the function didn't reach any return statement so far. # (some functions actually never do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks = self.annotated # all of them for block in newblocks: for op in block.operations: if op.opname in ('simple_call', 'call_args'): yield op # some blocks are partially annotated if op.result.annotation is None: break # ignore the unannotated part #___ simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else: graphs = {} for block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self, graph, block): # Important: this is not called recursively. # self.flowin() can only issue calls to self.addpendingblock(). # The analysis of a block can be in three states: # * block not in self.annotated: # never seen the block. # * self.annotated[block] == False: # the input variables of the block have bindings but we # still have to consider all the operations in the block. # * self.annotated[block] == graph-containing-block: # analysis done (at least until we find we must generalize the # input variables). #print '* processblock', block, cells self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: # hack for debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is used by rpython.annlowlevel to # detect which are the new blocks that annotating an additional # small helper creates. if self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells): # Create the initial bindings for the input args of a block. assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells' with each of the block's existing input # variables. oldcells = [self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code to the UnionError e.source = '\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged cells changed, we must redo the analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i = position_key blk = "" if block: at = block.at() if at: blk = " block"+at opid="" if i is not None: opid = " op=%d" % i return repr(graph) + blk + opid def flowin(self, graph, block): try: i = 0 while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e: if e.op is block.raising_op: # this is the case where the last operation of the block will # always raise an exception which is immediately caught by # an exception handler. We then only follow the exceptional # branches. exits = [link for link in block.exits if link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep the name of the call operations in sync # with the flow object space. These are the operations for # which it is fine to always raise an exception. We then # swallow the BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container(). return else: # other cases are problematic (but will hopefully be solved # later by reflowing). Throw the BlockedInference up to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that UnionError is a subclass e.source = gather_error(self, graph, block, i) raise else: # dead code removal: don't follow all exits if the exitswitch # is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link in exits: case = link.exitcase if case is None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, "knowntypedata", {}) else: knowntypedata = {} for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify: # reflow from certain positions when this block is done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else: callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that try to pass impossible values if s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on operations ______ def consider_op(self, op): # let's be careful about avoiding propagated SomeImpossibleValues # to enter an op; the latter can result in violations of the # more general results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom -- in the assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self, operation): """ Return the annotation for all exceptions that `operation` may raise. """ can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): """This exception signals the type inference engine that the situation is currently blocked, and that it should try to progress elsewhere.""" def __init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op self.opindex = opindex def __repr__(self): if not self.break_at: break_at = "?" else: break_at = self.annotator.whereami(self.break_at) return "<BlockedInference break_at %s [%s]>" %(break_at, self.op) __str__ = __repr__
1.828125
2
app/logic/httpcommon/Page.py
imvu/bluesteel
10
311
""" Page object file """ class Page(): """ Page object, it contains information about the pare we are refering, index, items per page, etc. """ page_index = 0 items_per_page = 0 def __init__(self, items_per_page, page_index): """ Creates the page """ self.page_index = int(page_index) self.items_per_page = int(items_per_page)
1.757813
2
app/api/v1/views/auth_views.py
emdeechege/Questionaire-API
0
319
from flask import jsonify, Blueprint, request, json, make_response from werkzeug.security import generate_password_hash, check_password_hash from datetime import datetime from ..utils.validators import Validation from ..models.auth_models import Users v1_auth_blueprint = Blueprint('auth', __name__, url_prefix='/api/v1') USER = Users() VALIDATOR = Validation() @v1_auth_blueprint.route('/signup', methods=['POST']) def signup(): """View that controls creation of new users""" try: data = request.get_json() except: return jsonify({ "status": 400, "message": "Invalid input" }), 400 firstname = data.get('firstname') lastname = data.get('lastname') othername = data.get('othername') email = data.get('email') phone_number = data.get('phone_number') username = data.get('username') is_admin = data.get('is_admin') password = data.get('password') if not firstname or not firstname.split(): return make_response(jsonify({ "status": 400, "message": "Firstname is required" })), 400 if not lastname or not lastname.split(): return make_response(jsonify({ "status": 400, "message": "Lastname is required" })), 400 if not email or not email.split(): return make_response(jsonify({ "status": 400, "message": "Email is required" })), 400 if not phone_number: return make_response(jsonify({ "status": 400, "message": "Phone number is required" })), 400 if not username or not username.split(): return make_response(jsonify({ "status": 400, "message": "Username is required" })), 400 if not password or not password.split(): return make_response(jsonify({ "status": 400, "message": "Password is required" })), 400 if not VALIDATOR.validate_phone_number(phone_number): return jsonify({ "status": 400, "message": "Please input valid phone number" }), 400 if VALIDATOR.validate_password(password): return jsonify({ "status": 400, "message": "Password not valid" }), 400 if not VALIDATOR.validate_email(email): return jsonify({ "status": 400, "message": "Invalid email" }), 400 if VALIDATOR.username_exists(username): return jsonify({ "status": 400, "message": "Username exists" }), 400 if VALIDATOR.email_exists(email): return jsonify({ "status": 400, "message": "Email exists" }), 400 password = generate_password_hash( password, method='pbkdf2:sha256', salt_length=8) res = USER.signup( firstname, lastname, othername, email, phone_number, username, is_admin, password) return jsonify({ "status": 201, "data": [{ "firstname": firstname, "lastname": lastname, "othername": othername, "email": email, "phone_number": phone_number, "username": username, "is_admin": is_admin }] }), 201 @v1_auth_blueprint.route('/login', methods=['POST']) def login(): """ A view to control users login """ try: data = request.get_json() except: return make_response(jsonify({ "status": 400, "message": "Wrong input" })), 400 username = data.get('username') password = data.get('password') if not username: return make_response(jsonify({ "status": 400, "message": "Username is required" })), 400 if not password: return make_response(jsonify({ "status": 400, "message": "Password is required" })), 400 if not VALIDATOR.username_exists(username): return jsonify({ "status": 404, "message": "User does not exist" }), 404 auth_token = user.generate_auth_token(username) return make_response(jsonify({ "status": 200, "message": 'Logged in successfuly', "token": auth_token })), 200
1.859375
2
iap/validate_jwt.py
spitfire55/python-docs-samples
4
327
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. """Sample showing how to validate the Identity-Aware Proxy (IAP) JWT. This code should be used by applications in Google Compute Engine-based environments (such as Google App Engine flexible environment, Google Compute Engine, or Google Container Engine) to provide an extra layer of assurance that a request was authorized by IAP. For applications running in the App Engine standard environment, use App Engine's Users API instead. """ # [START iap_validate_jwt] import jwt import requests def validate_iap_jwt_from_app_engine(iap_jwt, cloud_project_number, cloud_project_id): """Validate a JWT passed to your App Engine app by Identity-Aware Proxy. Args: iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header. cloud_project_number: The project *number* for your Google Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID', or in the Project Info card in Cloud Console. cloud_project_id: The project *ID* for your Google Cloud project. Returns: (user_id, user_email, error_str). """ expected_audience = '/projects/{}/apps/{}'.format( cloud_project_number, cloud_project_id) return _validate_iap_jwt(iap_jwt, expected_audience) def validate_iap_jwt_from_compute_engine(iap_jwt, cloud_project_number, backend_service_id): """Validate an IAP JWT for your (Compute|Container) Engine service. Args: iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header. cloud_project_number: The project *number* for your Google Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID', or in the Project Info card in Cloud Console. backend_service_id: The ID of the backend service used to access the application. See https://cloud.google.com/iap/docs/signed-headers-howto for details on how to get this value. Returns: (user_id, user_email, error_str). """ expected_audience = '/projects/{}/global/backendServices/{}'.format( cloud_project_number, backend_service_id) return _validate_iap_jwt(iap_jwt, expected_audience) def _validate_iap_jwt(iap_jwt, expected_audience): try: key_id = jwt.get_unverified_header(iap_jwt).get('kid') if not key_id: return (None, None, '**ERROR: no key ID**') key = get_iap_key(key_id) decoded_jwt = jwt.decode( iap_jwt, key, algorithms=['ES256'], audience=expected_audience) return (decoded_jwt['sub'], decoded_jwt['email'], '') except (jwt.exceptions.InvalidTokenError, requests.exceptions.RequestException) as e: return (None, None, '**ERROR: JWT validation error {}**'.format(e)) def get_iap_key(key_id): """Retrieves a public key from the list published by Identity-Aware Proxy, re-fetching the key file if necessary. """ key_cache = get_iap_key.key_cache key = key_cache.get(key_id) if not key: # Re-fetch the key file. resp = requests.get( 'https://www.gstatic.com/iap/verify/public_key') if resp.status_code != 200: raise Exception( 'Unable to fetch IAP keys: {} / {} / {}'.format( resp.status_code, resp.headers, resp.text)) key_cache = resp.json() get_iap_key.key_cache = key_cache key = key_cache.get(key_id) if not key: raise Exception('Key {!r} not found'.format(key_id)) return key # Used to cache the Identity-Aware Proxy public keys. This code only # refetches the file when a JWT is signed with a key not present in # this cache. get_iap_key.key_cache = {} # [END iap_validate_jwt]
1.765625
2
projects/eyetracking/gen_adhd_sin.py
nirdslab/streaminghub
0
335
#!/usr/bin/env python3 import glob import os import pandas as pd import dfs SRC_DIR = f"{dfs.get_data_dir()}/adhd_sin_orig" OUT_DIR = f"{dfs.get_data_dir()}/adhd_sin" if __name__ == '__main__': files = glob.glob(f"{SRC_DIR}/*.csv") file_names = list(map(os.path.basename, files)) for file_name in file_names: df: pd.DataFrame = pd.read_csv(f'{SRC_DIR}/{file_name}').set_index('EyeTrackerTimestamp').sort_index()[ ['GazePointX (ADCSpx)', 'GazePointY (ADCSpx)', 'PupilLeft', 'PupilRight']].reset_index() df.columns = ['t', 'x', 'y', 'dl', 'dr'] # fill blanks (order=interpolate(inter)->bfill+ffill(edges))->zerofill df = df.apply(lambda x: x.interpolate().fillna(method="bfill").fillna(method="ffill")).fillna(0) df['x'] = df['x'] / 1920 df['y'] = df['y'] / 1080 df['d'] = (df['dl'] + df['dr']) / 2 # start with t=0, and set unit to ms df['t'] = (df['t'] - df['t'].min()) / 1000 df = df[['t', 'x', 'y', 'd']].round(6).set_index('t') df.to_csv(f'{OUT_DIR}/{file_name}') print(f'Processed: {file_name}')
1.695313
2
Projects/DeepLearningTechniques/MobileNet_v2/tiny_imagenet/data_loader.py
Tim232/Python-Things
2
359
import os import re import numpy as np from Projects.DeepLearningTechniques.MobileNet_v2.tiny_imagenet.constants import * class DataLoader: # todo train/test/validation => (클래스 당 500/50/50) def __init__(self): self.image_width = flags.FLAGS.image_width self.image_height = flags.FLAGS.image_height self.batch_size = flags.FLAGS.batch_size self.data_path = flags.FLAGS.data_path self.img_reg = re.compile('.*\\.jpeg', re.IGNORECASE) self.init_class() self.init_annotation() def init_class(self): self.cls = {} for idx, dir in enumerate(os.listdir(os.path.join(self.data_path, 'train'))): self.cls[dir] = idx def init_annotation(self): self.anno = {} for line in open(os.path.join(self.data_path, 'val', 'val_annotations.txt')): filename, label, *_ = line.split('\t') self.anno[filename] = label def init_train(self): train_x, train_y = [], [] for (path, dirs, files) in os.walk(os.path.join(self.data_path, 'train')): for file in files: if self.img_reg.match(file): train_x.append(os.path.join(path, file)) train_y.append(self.cls[re.match('(.+)\\_\d+\\.jpeg', file, re.IGNORECASE).group(1)]) self.train_len = len(train_y) #todo train data random sort random_sort = np.random.permutation(self.train_len) train_x, train_y = np.asarray(train_x, dtype=np.string_)[random_sort], np.asarray(train_y, dtype=np.int64)[random_sort] #todo (Numpy / List) => Tensor 로 변환 with tf.variable_scope(name_or_scope='data_tensor'): self.train_x = tf.convert_to_tensor(value=train_x, dtype=tf.string, name='train_x') self.train_y = tf.convert_to_tensor(value=train_y, dtype=tf.int64, name='train_y') def init_validation(self): valid_x, valid_y = [], [] for (path, dirs, files) in os.walk(os.path.join(self.data_path, 'val')): for file in files: if self.img_reg.match(file): valid_x.append(os.path.join(path, file)) valid_y.append(self.cls[self.anno[file]]) self.valid_len = len(valid_y) #todo validataion data random sort random_sort = np.random.permutation(self.valid_len) valid_x, valid_y = np.asarray(valid_x, dtype=np.string_)[random_sort], np.asarray(valid_y, dtype=np.int64)[random_sort] #todo (Numpy / List) -> Tensor 로 변환 with tf.variable_scope(name_or_scope='data_tensor'): self.valid_x = tf.convert_to_tensor(value=valid_x, dtype=tf.string, name='valid_x') self.valid_y = tf.convert_to_tensor(value=valid_y, dtype=tf.int64, name='valid_y') def init_test(self): test_x = [] for (path, dirs, files) in os.walk(os.path.join(self.data_path, 'test')): for file in files: test_x.append(os.path.join(path, file)) self.test_len = len(test_x) #todo (Numpy / List) -> Tensor 로 변환 with tf.variable_scope(name_or_scope='data_tensor'): self.test_x = tf.convert_to_tensor(value=test_x, dtype=tf.string, name='test_x') def train_normal(self, x, y): with tf.variable_scope(name_or_scope='train_normal'): x = tf.read_file(filename=x) x = tf.image.decode_png(contents=x, channels=3, name='decode_png') x = tf.divide(tf.cast(x, tf.float32), 255.) x = tf.subtract(x, [0.4921, 0.4833, 0.4484]) x = tf.divide(x, [0.2465, 0.2431, 0.2610]) return x, y def train_random_crop(self, x, y): with tf.variable_scope(name_or_scope='train_random_crop'): x = tf.read_file(filename=x) x = tf.image.decode_png(contents=x, channels=3, name='decode_png') x = tf.pad(x, [[0, 0], [4, 4], [4, 4], [0, 0]], name='padding') # x = tf.image.resize_images(images=x, size=(self.image_height+8, self.image_width+8), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) x = tf.random_crop(value=x, size=(self.image_height, self.image_width, 3)) x = tf.divide(tf.cast(x, tf.float32), 255.) x = tf.subtract(x, [0.4921, 0.4833, 0.4484]) x = tf.divide(x, [0.2465, 0.2431, 0.2610]) return x, y def valid_normal(self, x, y): with tf.variable_scope(name_or_scope='valid_normal'): x = tf.read_file(filename=x) x = tf.image.decode_png(contents=x, channels=3, name='decode_png') x = tf.divide(tf.cast(x, tf.float32), 255.) x = tf.subtract(x, [0.4921, 0.4833, 0.4484]) x = tf.divide(x, [0.2465, 0.2431, 0.2610]) return x, y def test_normal(self, x): with tf.variable_scope(name_or_scope='test_normal'): x = tf.read_file(filename=x) x = tf.image.decode_png(contents=x, channels=3, name='decode_png') x = tf.divide(tf.cast(x, tf.float32), 255.) x = tf.subtract(x, [0.4921, 0.4833, 0.4484]) x = tf.divide(x, [0.2465, 0.2431, 0.2610]) return x def dataset_batch_loader(self, dataset, ref_func, name): with tf.variable_scope(name_or_scope=name): dataset_map = dataset.map(ref_func).batch(self.batch_size) iterator = dataset_map.make_one_shot_iterator() batch_input = iterator.get_next() return batch_input def train_loader(self): with tf.variable_scope('train_loader'): ''' repeat(): 데이터셋이 끝에 도달했을 때 다시 처음부터 수행하게 하는 함수 shuffle(): 데이터셋에 대해 random sort 기능을 수행하는 함수 (괄호안에 값이 전체 데이터 수보다 크면 전체 데이터에 대한 random sort) ''' dataset = tf.data.Dataset.from_tensor_slices((self.train_x, self.train_y)).repeat() normal_batch = self.dataset_batch_loader(dataset, self.train_normal, name='normal_batch') random_crop_batch = self.dataset_batch_loader(dataset, self.train_random_crop, name='random_crop_batch') return normal_batch, random_crop_batch def valid_loader(self): with tf.variable_scope('valid_loader'): dataset = tf.data.Dataset.from_tensor_slices((self.valid_x, self.valid_y)).repeat() normal_batch = self.dataset_batch_loader(dataset, self.valid_normal, name='normal_batch') return normal_batch def test_loader(self): with tf.variable_scope('test_loader'): dataset = tf.data.Dataset.from_tensor_slices(self.test_x).repeat() normal_batch = self.dataset_batch_loader(dataset, self.test_normal, name='normal_batch') return normal_batch
1.960938
2
src/telr/TELR_assembly.py
dominik-handler/TELR
22
391
import sys import os import subprocess import shutil import time import logging from Bio import SeqIO from multiprocessing import Pool import pysam from telr.TELR_utility import mkdir, check_exist, format_time def get_local_contigs( assembler, polisher, contig_dir, vcf_parsed, out, sample_name, bam, raw_reads, thread, presets, polish_iterations, ): """Perform local assembly using reads from parsed VCF file in parallel""" # Prepare reads used for local assembly and polishing sv_reads_dir = os.path.join(out, "sv_reads") try: prep_assembly_inputs( vcf_parsed, out, sample_name, bam, raw_reads, sv_reads_dir, read_type="sv" ) except Exception as e: print(e) print("Prepare local assembly input data failed, exiting...") sys.exit(1) mkdir(contig_dir) k = 0 asm_pa_list = [] with open(vcf_parsed, "r") as input: for line in input: entry = line.replace("\n", "").split("\t") contig_name = "_".join([entry[0], entry[1], entry[2]]) # rename variant reads sv_reads = sv_reads_dir + "/contig" + str(k) sv_reads_rename = sv_reads_dir + "/" + contig_name + ".reads.fa" os.rename(sv_reads, sv_reads_rename) thread_asm = 1 asm_pa = [ sv_reads_rename, contig_dir, contig_name, thread_asm, presets, assembler, polisher, polish_iterations, ] asm_pa_list.append(asm_pa) k = k + 1 # run assembly in parallel logging.info("Perform local assembly of non-reference TE loci...") start_time = time.time() try: pool = Pool(processes=thread) contig_list = pool.map(run_assembly_polishing, asm_pa_list) pool.close() pool.join() except Exception as e: print(e) print("Local assembly failed, exiting...") sys.exit(1) proc_time = time.time() - start_time # merge all contigs assembly_passed_loci = set() merged_contigs = os.path.join(out, sample_name + ".contigs.fa") with open(merged_contigs, "w") as merged_output_handle: for contig in contig_list: if check_exist(contig): contig_name = os.path.basename(contig).replace(".cns.fa", "") assembly_passed_loci.add(contig_name) parsed_contig = os.path.join(contig_dir, contig_name + ".cns.ctg1.fa") with open(contig, "r") as input: records = SeqIO.parse(input, "fasta") for record in records: if record.id == "ctg1" or record.id == "contig_1": record.id = contig_name record.description = "len=" + str(len(record.seq)) SeqIO.write(record, merged_output_handle, "fasta") with open(parsed_contig, "w") as parsed_output_handle: SeqIO.write(record, parsed_output_handle, "fasta") logging.info("Local assembly finished in " + format_time(proc_time)) return merged_contigs, assembly_passed_loci def run_assembly_polishing(args): reads = args[0] asm_dir = args[1] contig_name = args[2] thread = args[3] presets = args[4] assembler = args[5] polisher = args[6] polish_iterations = args[7] # run assembly if assembler == "wtdbg2": asm_cns = run_wtdbg2_assembly(reads, asm_dir, contig_name, thread, presets) else: asm_cns = run_flye_assembly(reads, asm_dir, contig_name, thread, presets) if not check_exist(asm_cns): print("assembly failed") return None # run polishing if polish_iterations > 0: if polisher == "wtdbg2": asm_cns = run_wtdbg2_polishing( asm_cns, reads, thread, polish_iterations, presets ) else: asm_cns = run_flye_polishing( asm_cns, reads, asm_dir, contig_name, thread, polish_iterations, presets ) if check_exist(asm_cns): return asm_cns else: return None def run_flye_polishing( asm_cns, reads, asm_dir, contig_name, thread, polish_iterations, presets ): """Run Flye polishing""" if presets == "pacbio": presets_flye = "--pacbio-raw" else: presets_flye = "--nano-raw" tmp_out_dir = os.path.join(asm_dir, contig_name) mkdir(tmp_out_dir) try: subprocess.call( [ "flye", "--polish-target", asm_cns, presets_flye, reads, "--out-dir", tmp_out_dir, "--thread", str(thread), "--iterations", str(polish_iterations), ] ) except Exception as e: print(e) print("Polishing failed, exiting...") return None # rename contig file polished_contig = os.path.join( tmp_out_dir, "polished_" + str(polish_iterations) + ".fasta" ) if check_exist(polished_contig): os.rename(polished_contig, asm_cns) shutil.rmtree(tmp_out_dir) return asm_cns else: return None def run_wtdbg2_polishing(asm_cns, reads, threads, polish_iterations, presets): """Run wtdbg2 polishing""" if presets == "pacbio": presets_minimap2 = "map-pb" else: presets_minimap2 = "map-ont" # polish consensus threads = str(min(threads, 4)) bam = asm_cns + ".bam" k = 0 while True: # align reads to contigs command = ( "minimap2 -t " + threads + " -ax " + presets_minimap2 + " -r2k " + asm_cns + " " + reads + " | samtools sort -@" + threads + " > " + bam ) try: subprocess.run( command, shell=True, timeout=300, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, ) except subprocess.TimeoutExpired: print("fail to map reads to contig: " + asm_cns) return # run wtpoa-cns to get polished contig cns_tmp = asm_cns + ".tmp" command = ( "samtools view -F0x900 " + bam + " | wtpoa-cns -t " + threads + " -d " + asm_cns + " -i - -fo " + cns_tmp ) try: subprocess.run( command, shell=True, timeout=300, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, ) except subprocess.TimeoutExpired: print("fail to polish contig: " + asm_cns) return if check_exist(cns_tmp): os.rename(cns_tmp, asm_cns) os.remove(bam) else: break k = k + 1 if k >= polish_iterations: break if check_exist(asm_cns): return asm_cns else: print("polishing failed for " + asm_cns + "\n") return None def run_flye_assembly(sv_reads, asm_dir, contig_name, thread, presets): """Run Flye assembly""" if presets == "pacbio": presets_flye = "--pacbio-raw" else: presets_flye = "--nano-raw" tmp_out_dir = os.path.join(asm_dir, contig_name) mkdir(tmp_out_dir) try: subprocess.call( [ "flye", presets_flye, sv_reads, "--out-dir", tmp_out_dir, "--thread", str(thread), "--iterations", "0", ] ) except Exception as e: print(e) print("Assembly failed, exiting...") return # rename contigs contig_path = os.path.join(tmp_out_dir, "assembly.fasta") contig_path_new = os.path.join(asm_dir, contig_name + ".cns.fa") if check_exist(contig_path): os.rename(contig_path, contig_path_new) # remove tmp files shutil.rmtree(tmp_out_dir) return contig_path_new else: print("assembly failed") return None def run_wtdbg2_assembly(sv_reads, asm_dir, contig_name, thread, presets): """Run wtdbg2 assembly""" if presets == "pacbio": presets_wtdbg2 = "rs" else: presets_wtdbg2 = "ont" prefix = sv_reads.replace(".reads.fa", "") try: subprocess.run( [ "wtdbg2", "-x", presets_wtdbg2, "-q", "-AS", "1", "-g", "30k", "-t", str(thread), "-i", sv_reads, "-fo", prefix, ], timeout=300, ) except subprocess.TimeoutExpired: print("fail to build contig layout for contig: " + contig_name) return except Exception as e: print(e) print("wtdbg2 failed, exiting...") return None # derive consensus contig_layout = prefix + ".ctg.lay.gz" if check_exist(contig_layout): cns_thread = str(min(thread, 4)) consensus = prefix + ".cns.fa" try: subprocess.run( [ "wtpoa-cns", "-q", "-t", cns_thread, "-i", contig_layout, "-fo", consensus, ], timeout=300, ) except subprocess.TimeoutExpired: print("fail to assemble contig: " + contig_name) return None if check_exist(consensus): consensus_rename = os.path.join(asm_dir, contig_name + ".cns.fa") os.rename(consensus, consensus_rename) return consensus_rename else: return None def prep_assembly_inputs( vcf_parsed, out, sample_name, bam, raw_reads, reads_dir, read_type="sv" ): """Prepare reads for local assembly""" # logging.info("Prepare reads for local assembly") if read_type == "sv": # TODO: figure out what this does # extract read IDs read_ids = os.path.join(out, sample_name + ".id") with open(vcf_parsed, "r") as input, open(read_ids, "w") as output: for line in input: entry = line.replace("\n", "").split("\t") read_list = entry[8].split(",") for read in read_list: output.write(read + "\n") else: # TODO: think about using this for assembly, filter for cigar reads window = 1000 samfile = pysam.AlignmentFile(bam, "rb") read_ids = os.path.join(out, sample_name + ".id") vcf_parsed_new = vcf_parsed + ".new" with open(vcf_parsed, "r") as input, open(read_ids, "w") as output, open( vcf_parsed_new, "w" ) as VCF: for line in input: entry = line.replace("\n", "").split("\t") # get sniffles read list read_list = entry[8].split(",") reads_sniffles = set(read_list) ins_chr = entry[0] ins_breakpoint = round((int(entry[1]) + int(entry[2])) / 2) start = ins_breakpoint - window end = ins_breakpoint + window reads = set() # coverage = 0 for read in samfile.fetch(ins_chr, start, end): reads.add(read.query_name) for read in reads: output.write(read + "\n") # write out_line = line.replace("\n", "") + "\t" + str(len(reads)) VCF.write(out_line + "\n") vcf_parsed = vcf_parsed_new # generate unique ID list read_ids_unique = read_ids + ".unique" command = "cat " + read_ids + " | sort | uniq" with open(read_ids_unique, "w") as output: subprocess.call(command, stdout=output, shell=True) # filter raw reads using read list subset_fa = os.path.join(out, sample_name + ".subset.fa") command = "seqtk subseq " + raw_reads + " " + read_ids_unique + " | seqtk seq -a" with open(subset_fa, "w") as output: subprocess.call(command, stdout=output, shell=True) # reorder reads subset_fa_reorder = out + "/" + sample_name + ".subset.reorder.fa" extract_reads(subset_fa, read_ids, subset_fa_reorder) # separate reads into multiple files, using csplit mkdir(reads_dir) csplit_prefix = reads_dir + "/contig" m = [] k = 1 with open(vcf_parsed, "r") as input: for line in input: entry = line.replace("\n", "").split("\t") if read_type == "sv": k = k + 2 * (len(entry[8].split(","))) else: k = k + 2 * int(entry[14]) m.append(k) if len(m) == 1: subprocess.call(["cp", subset_fa_reorder, reads_dir + "/contig0"]) elif len(m) == 0: print("No insertion detected, exiting...") else: m = m[:-1] index = " ".join(str(i) for i in m) command = ( "csplit -s -f " + csplit_prefix + " -n 1 " + subset_fa_reorder + " " + index ) subprocess.call(command, shell=True) # remove tmp files os.remove(read_ids) os.remove(read_ids_unique) os.remove(subset_fa) os.remove(subset_fa_reorder) def extract_reads(reads, list, out): """Extract reads from fasta using read ID list""" record_dict = SeqIO.index(reads, "fasta") with open(out, "wb") as output_handle, open(list, "r") as ID: for entry in ID: entry = entry.replace("\n", "") output_handle.write(record_dict.get_raw(entry))
1.554688
2
bcloud-snap/bcloud-3.9.1/bcloud/hasher.py
jiaxiaolei/my_snap_demo
0
399
# Copyright (C) 2014-2015 LiuLang <<EMAIL>> # Use of this source code is governed by GPLv3 license that can be found # in http://www.gnu.org/licenses/gpl-3.0.html import hashlib import os import zlib CHUNK = 2 ** 20 def crc(path): _crc = 0 fh = open(path, 'rb') while True: chunk = fh.read(CHUNK) if not chunk: break _crc = zlib.crc32(chunk, _crc) fh.close() return '%X' % (_crc & 0xFFFFFFFF) def md5(path, start=0, stop=-1): _md5 = hashlib.md5() fh = open(path, 'rb') if start > 0: fh.seek(start) if stop == -1: stop = os.path.getsize(path) pos = start while pos < stop: size = min(CHUNK, stop - pos) chunk = fh.read(size) if not chunk: break pos += len(chunk) _md5.update(chunk) fh.close() return _md5.hexdigest() def sha1(path): _sha1 = hashlib.sha1() fh = open(path, 'rb') while True: chunk = fh.read(CHUNK) if not chunk: break _sha1.update(chunk) fh.close() return _sha1.hexdigest() def sha224(path): _sha224 = hashlib.sha224() fh = open(path, 'rb') while True: chunk = fh.read(CHUNK) if not chunk: break _sha224.update(chunk) fh.close() return _sha224.hexdigest() def sha256(path): _sha256 = hashlib.sha256() fh = open(path, 'rb') while True: chunk = fh.read(CHUNK) if not chunk: break _sha256.update(chunk) fh.close() return _sha256.hexdigest() def sha384(path): _sha384 = hashlib.sha384() fh = open(path, 'rb') while True: chunk = fh.read(CHUNK) if not chunk: break _sha384.update(chunk) fh.close() return _sha384.hexdigest() def sha512(path): _sha512 = hashlib.sha512() fh = open(path, 'rb') while True: chunk = fh.read(CHUNK) if not chunk: break _sha512.update(chunk) fh.close() return _sha512.hexdigest()
1.84375
2
python/re_user.py
seckcoder/lang-learn
1
407
#!/usr/bin/env python #-*- coding=utf-8 -*- # # Copyright 2012 Jike Inc. All Rights Reserved. # Author: <EMAIL> import re from urlparse import urlparse def parse1(): p = re.compile(r"/(?P<uid>\d+)/(?P<mid>\w+)") o = urlparse("http://weibo.com/2827699110/yz62AlEjF") m = p.search(o.path) print m.group('uid') print m.group('mid') def parse2(): exc_type_str = "<type 'exceptions.IndexError'>" parse1()
1.375
1
MAIN/Screens/Settings/category_2/__init__.py
aragubas/fogoso
0
431
#!/usr/bin/python3.7 # Copyright 2020 Aragubas # # 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. # # # -- Imports -- # from ENGINE import APPDATA as reg from ENGINE import UTILS as utils import ENGINE as tge from Fogoso.MAIN import ClassesUtils as gameObjs from Fogoso import MAIN as gameMain import pygame, sys import importlib import time from random import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX = 0 ElementsY = 0 def Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey("/OPTIONS/debug_enabled", bool) if current_val: gameMain.DefaultCnt.Write_RegKey("/OPTIONS/debug_enabled", "False") if not current_val: gameMain.DefaultCnt.Write_RegKey("/OPTIONS/debug_enabled", "True") if OptionsScreen_RandomWindowTitle .ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey("/OPTIONS/random_title", bool) if current_val: gameMain.DefaultCnt.Write_RegKey("/OPTIONS/random_title", "False") if not current_val: gameMain.DefaultCnt.Write_RegKey("/OPTIONS/random_title", "True") if OptionsScreen_NumberFormatting .ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey("/OPTIONS/format_numbers", bool) if current_val: gameMain.DefaultCnt.Write_RegKey("/OPTIONS/format_numbers", "False") if not current_val: gameMain.DefaultCnt.Write_RegKey("/OPTIONS/format_numbers", "True") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, "/PressStart2P.ttf", 14, gameMain.DefaultCnt.Get_RegKey("/strings/settings/debug_mode") + str(gameMain.DefaultCnt.Get_RegKey("/OPTIONS/debug_enabled")), (240, 240, 240), ElementsX + 95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey("/OPTIONS/font_aa")) # -- Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, "/PressStart2P.ttf", 14, gameMain.DefaultCnt.Get_RegKey("/strings/settings/random_title") + str(gameMain.DefaultCnt.Get_RegKey("/OPTIONS/random_title")), (240, 240, 240), ElementsX + 95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey("/OPTIONS/font_aa")) # -- Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, "/PressStart2P.ttf", 14, gameMain.DefaultCnt.Get_RegKey("/strings/settings/number_formatting") + str(gameMain.DefaultCnt.Get_RegKey("/OPTIONS/format_numbers")), (240, 240, 240), ElementsX + 95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey("/OPTIONS/font_aa")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Update(event) OptionsScreen_RandomWindowTitle.Update(event) OptionsScreen_NumberFormatting.Update(event)
1.226563
1
tests/integration/test_cmk_describe.py
oglok/CPU-Manager-for-Kubernetes
0
439
# Copyright (c) 2017 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. from .. import helpers from . import integration def test_cmk_describe_ok(): args = ["describe", "--conf-dir={}".format(helpers.conf_dir("ok"))] assert helpers.execute(integration.cmk(), args) == b"""{ "path": "/cmk/tests/data/config/ok", "pools": { "exclusive": { "cpuLists": { "4,12": { "cpus": "4,12", "tasks": [ 2000 ] }, "5,13": { "cpus": "5,13", "tasks": [ 2001 ] }, "6,14": { "cpus": "6,14", "tasks": [ 2002 ] }, "7,15": { "cpus": "7,15", "tasks": [ 2003 ] } }, "exclusive": true, "name": "exclusive" }, "infra": { "cpuLists": { "0-2,8-10": { "cpus": "0-2,8-10", "tasks": [ 3000, 3001, 3002 ] } }, "exclusive": false, "name": "infra" }, "shared": { "cpuLists": { "3,11": { "cpus": "3,11", "tasks": [ 1000, 1001, 1002, 1003 ] } }, "exclusive": false, "name": "shared" } } } """ def test_cmk_describe_minimal(): args = ["describe", "--conf-dir={}".format(helpers.conf_dir("minimal"))] assert helpers.execute(integration.cmk(), args) == b"""{ "path": "/cmk/tests/data/config/minimal", "pools": { "exclusive": { "cpuLists": { "0": { "cpus": "0", "tasks": [] } }, "exclusive": true, "name": "exclusive" }, "shared": { "cpuLists": { "0": { "cpus": "0", "tasks": [] } }, "exclusive": false, "name": "shared" } } } """
1.289063
1
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/super/super_with_arguments.py
ciskoinch8/vimrc
463
447
class Foo: pass class Bar(Foo): def __init__(self): super(Bar, self).__init__() # [super-with-arguments] class Baz(Foo): def __init__(self): super().__init__() class Qux(Foo): def __init__(self): super(Bar, self).__init__() class NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self): # Using plain `super()` is not valid here, since there's no `__class__` cell found # (Exact exception would be 'RuntimeError: super(): __class__ cell not found') # Instead, we expect to *not* see a warning about `super-with-arguments`. # Explicitly passing `cls`, and `self` to `super()` is what's required. super(cls, self).__init__()
1.539063
2
betterloader/standard_transforms.py
BinItAI/BetterLoader
39
455
import numpy as np from torchvision import transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform): self.transform = transform def __call__(self, sample): x1 = self.transform(sample) x2 = self.transform(sample) return x1, x2
1.398438
1
examples/my_model_test.py
gzpyy/qlib
0
463
#encoding=utf-8 import qlib import pandas as pd import pickle import xgboost as xgb import numpy as np import re from qlib.constant import REG_US from qlib.utils import exists_qlib_data, init_instance_by_config from qlib.workflow import R from qlib.workflow.record_temp import SignalRecord, PortAnaRecord from qlib.utils import flatten_dict from qlib.data import LocalExpressionProvider from qlib.data.ops import Operators, OpsList from qlib.data.base import Feature from pyecharts import options as opts from pyecharts.charts import Kline, Line, Grid from my_data_handler import MyAlphaHandler # model_file = r'.\mlruns\1\d6536b056ba84a74be6b33971f443cf6\artifacts\trained_model' model_file = r'.\mlruns\1\148ef1cd7acd48deac3eadc339ad3008\artifacts\trained_model' with open(model_file, 'rb') as fi: model = pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime("%Y-%m-%d %H:%M:00") raw_data.set_index('time', inplace=True) raw_data["vwap"] = np.nan raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature): def _load_internal(self, instrument, start_index, end_index, freq): print("load", self._name, instrument, start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def my_parse_field(field): if not isinstance(field, str): field = str(field) for pattern, new in [(r"\$(\w+)", rf'MyFeature("\1")'), (r"(\w+\s*)\(", r"Operators.\1(")]: # Features # Operators field = re.sub(pattern, new, field) return field obj = dict() for field in exprs: expression = eval(my_parse_field(field)) series = expression.load('TSLA', "2022-01-02", "2022-02-28", "1min") series = series.astype(np.float32) obj[field] = series data = pd.DataFrame(obj) data.columns = columns view_time_start = '2022-02-11' view_time_end = '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records = pre_data.to_dict("records") cash = 50000 position = {} hold_thresh = 5 score_thresh = 0.001 x_axises, y_axises, mark_points, money = [], [], [], [] for record in records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'], record['high'] ]) if 'hold_cnt' in position: position['hold_cnt'] += 1 if position and (record['open'] >= position['close'] * 1.01 or record['open'] < position['close'] * 0.995 or record['pred_score'] < -score_thresh or position['hold_cnt'] >= hold_thresh): cash += position['amount'] * record['open'] position = {} #print("sell") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color="green") )) elif record['pred_score'] > score_thresh and not position: position = dict(record) position['amount'] = int(cash / position['open']) cash -= position['amount'] * position['open'] # buy #print("buy") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color="yellow") )) cur_money = cash if position: cur_money += position['amount'] * record['close'] money.append(cur_money) if position: cash += position['amount'] * records[-1]['close'] print("cash:", cash) kline_graph = ( Kline() .add_xaxis(x_axises) .add_yaxis( "kline", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title="%s_%s" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_="inside", xaxis_index=[0, 1],)], ) ) kline_line = ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name="cur_money", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left="3%", pos_right="10%", height="50%"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left="3%", pos_right="10%", pos_top="60%", height="30%" ), ) grid_chart.render("kline_markline.html")
1.648438
2
heatsink.py
sww1235/heatsink-calc
1
471
"""Class representations of heatsinks.""" import math from scipy import constants as const from materials import Aluminium_6063 as aluminium class Heatsink: """ A Heatsink. Extended by form factor subclasses """ def __init__(self, material, configuration): """Init material and configuration variables.""" self.material = material self.configuration = configuration class CylindricalAnnularFin(Heatsink): """Extend base heatsink class with a cylindrical annular fin heatsink.""" def __init__(self, material, finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): """ Init remainder of class variables. NOTE: all models are based off of the finSpacing variable NOTE: using the simplified model for calculation efficiency. finSpacing : gap between adjacent fins finRadius : radius of fin minus central support cylinder (alternatively, fin depth) finThickness : thickness of individual fin cylinderDiameter: diameter of support cylinder heatsinkLength : overall axial length of heatsink overall diameter: outside diameter of heatsink including fins. """ self.finSpacing = finSpacing # in meters self.finRadius = finRadius # in meters self.finThickness = finThickness # in meters self.cylinderDiameter = cylinderDiameter # in meters self.numberOfFins = numberofFins self.heatsinkLength = ((self.finThickness * self.numberOfFins) + ((self.numberOfFins - 1) * self.finSpacing)) self.overallDiameter = self.cylinderDiameter + (2 * finRadius) self.ambAirTemp = ambAirTemp # degrees kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp """ NOTE: in order to prevent ridiculously long variable names, all Nusselt Numbers are abbreviated as follows: nn = Nusselt Number nn0 = Nusselt Number 0 (Diffusive Limit) nnOut = Nusselt Number for outer surfaces nnIn = Nusselt Number for inner surfaces nnInT = Nusselt Number for the thin boundry layer of inner surface nnInFD = Nusselt Number for fully developed regime inner surface """ # thermal diffusivity of air at atmospheric pressure at 25C alpha = 22.39 * 10**(-6) # (meters^2) / seconds # Volumetric coefficient of thermal expansion beta = aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp = # TODO kelvin # at atmospheric pressure at 25C kinematicViscosity = 15.52 * 10**(-6) # meter^2/second deltaT = heatsinkSurfaceTemp - ambAirTemp # kelvin hLoD = self.heatsinkLength / self.overallDiameter cDoD = self.cylinderDiameter / self.overallDiameter oneChannelArea = (math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2) / 2) + (self.cylinderDiameter * self.finSpacing))) # area of circumscribed cylinder areaCC = (math.pi * (((self.overallDiameter**2) / 2) + self.overallDiameter * self.heatsinkLength)) # meter^2 # inner surface area of heatsink areaIn = (self.numberOfFins - 1) * oneChannelArea # meter^2 # outer surface area of heatsink areaOut = (math.pi * (((self.overallDiameter**2) / 2) + (self.numberOfFins * self.overallDiameter * self.finThickness))) # meter^2 # overall area of heatsink areaHS = areaIn + areaOut # meter^2 RayleighNbrFinSpacing = ((const.g * beta * deltaT * self.finSpacing**4) / (kinematicViscosity * alpha * self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g * beta * deltaT * self.overallDiameter**3) / (kinematicViscosity * alpha)) if 0.1 <= hLoD <= 8: self.nn0 = ((3.36 + (0.087 * hLoD)) * math.sqrt(areaCC) * (self.finSpacing / areaHS) ) if 0.1 <= (self.finThickness * self.numberOfFins / self.overallDiameter) <= 8: self.nnOut = ((0.499 - (0.026 * math.log(self.finThickness * self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) ) if (0.1 <= cdoD <= 8) and (2.9 * 10**4 <= RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT = ((0.573-(0.184 * cdoD) + (0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323 - (0.0517 * cdoD) + (0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 + (0.0154 * cdoD) - (0.0433 * cdoD**2) + (0.0792 * cdoD**3)) * RayleighNbrFinSpacing) n = 1 self.nnIn = (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n), (-1/n) ) * (areaIn/areaHS) ) self.nn = (self.nnIn + self.nnOut + self.nn0) super(Child, self).__init__(material, self.__name__) """ Nusselt number = (Qconv * b) / (Ahs deltaT k) Qconv = heat flow rate by convection (Watts) b = finSpacing (meters) Ahs = Area of heatsink (meter^2) deltaT = temperature difference between surface temp of heatsink and ambient air temp. k = thermal conductivity of material (Watts / (meter kelvin)) """
2.640625
3
tests/mqtt/test_subscribe.py
smurfix/hbmqtt
0
479
# Copyright (c) 2015 <NAME> # # See the file license.txt for copying permission. import anyio import unittest from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data = b'\x80\x0e\x00\x0a\x00\x03a/b\x01\x00\x03c/d\x02' stream = BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload = SubscribePayload( [ ('a/b', QOS_1), ('c/d', QOS_2) ]) publish = SubscribePacket(variable_header=variable_header, payload=payload) out = publish.to_bytes() self.assertEqual(out, b'\x82\x0e\x00\x0a\x00\x03a/b\x01\x00\x03c/d\x02')
1.578125
2
test/test_aes.py
haruhi-dl/haruhi-dl
32
495
#!/usr/bin/env python from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import base64 # the encrypted data can be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self): self.key = self.iv = [0x20, 0x15] + 14 * [0] self.secret_msg = b'Secret message goes here' def test_encrypt(self): msg = b'message' key = list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data = bytes_to_intlist( b"\x97\x92+\xe5\x0b\xc3\x18\x91ky9m&\xb3\xb5@\xe6'\xc2\x96.\xc8u\x88\xab9-[\x9e|\xf1\xcd" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg) def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted, b"\x97\x92+\xe5\x0b\xc3\x18\x91ky9m&\xb3\xb5@\xe6'\xc2\x96.\xc8u\x88\xab9-[\x9e|\xf1\xcd") def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\x17\x15\x93\xab\x8d\x80V\xcdV\xe0\t\xcdo\xc2\xa5\xd8ksM\r\xe27N\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\x0b\xe6\xa4\xd9z\x0e\xb8\xb9\xd0\xd4i_\x85\x1d\x99\x98_\xe5\x80\xe7.\xbf\xa5\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg) if __name__ == '__main__': unittest.main()
1.75
2
tests/bugs/core_6266_test.py
reevespaul/firebird-qa
0
503
#coding:utf-8 # # id: bugs.core_6266 # title: Deleting records from MON$ATTACHMENTS using ORDER BY clause doesn't close the corresponding attachments # decription: # Old title: Don't close attach while deleting record from MON$ATTACHMENTS using ORDER BY clause. # Confirmed bug on 3.0.6.33271. # Checked on 3.0.6.33272 (SS/CS) - works fine. # 22.04.2020. Checked separately on 4.0.0.1931 SS/CS: all OK. FB 4.0 can also be tested since this build. # # tracker_id: CORE-6266 # min_versions: ['3.0.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [] init_script_1 = """""" db_1 = db_factory(sql_dialect=3, init=init_script_1) # test_script_1 #--- # import os # import sys # import time # import fdb # # ATT_CNT=5 # ATT_DELAY=1 # # os.environ["ISC_USER"] = user_name # os.environ["ISC_PASSWORD"] = <PASSWORD> # # db_conn.close() # # con_list={} # for i in range(0, ATT_CNT): # if i > 0: # time.sleep( ATT_DELAY ) # # c = fdb.connect(dsn = dsn) # a = c.attachment_id # con_list[ i ] = (a, c) # # print('created attachment ', (a,c) ) # # con_admin = con_list[0][1] # # #print(con_admin.firebird_version) # # # this removes ALL connections --> should NOT be used for reproducing ticket issue: # #con_admin.execute_immediate('delete from mon$attachments where mon$attachment_id != current_connection order by mon$timestamp') # # # this removes ALL connections --> should NOT be used for reproducing ticket issue: # #con_admin.execute_immediate('delete from mon$attachments where mon$system_flag is distinct from 1 and mon$attachment_id != current_connection order by mon$timestamp') # # # This DOES NOT remove all attachments (only 'last' in order of timestamp), but # # DELETE statement must NOT contain phrase 'mon$attachment_id != current_connection': # con_admin.execute_immediate('delete from mon$attachments where mon$system_flag is distinct from 1 order by mon$timestamp') # # con_admin.commit() # # cur_admin = con_admin.cursor() # cur_admin.execute('select mon$attachment_id,mon$user from mon$attachments where mon$system_flag is distinct from 1 and mon$attachment_id != current_connection' ) # i=0 # for r in cur_admin: # print( '### ACHTUNG ### STILL ALIVE ATTACHMENT DETECTED: ', r[0], r[1].strip(), '###' ) # i += 1 # print('Number of attachments that remains alive: ',i) # # cur_admin.close() # # #print('Final cleanup before quit from Python.') # # for k,v in sorted( con_list.items() ): # #print('attempt to close attachment ', v[0] ) # try: # v[1].close() # #print('done.') # except Exception as e: # pass # #print('Got exception:', sys.exc_info()[0]) # #print(e[0]) # # #--- #act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ Number of attachments that remains alive: 0 """ @pytest.mark.version('>=3.0') @pytest.mark.xfail def test_1(db_1): pytest.fail("Test not IMPLEMENTED")
1.164063
1
Doc/conf.py
python-doc-tw/cpython-tw
0
519
# # Python documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). import sys, os, time sys.path.append(os.path.abspath('tools/extensions')) # General configuration # --------------------- extensions = ['sphinx.ext.coverage', 'sphinx.ext.doctest', 'pyspecific', 'c_annotations'] # General substitutions. project = 'Python' copyright = '2001-%s, Python Software Foundation' % time.strftime('%Y') # We look for the Include/patchlevel.h file in the current Python source tree # and replace the values accordingly. import patchlevel version, release = patchlevel.get_version_info() # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # By default, highlight as Python 3. highlight_language = 'python3' # Require Sphinx 1.2 for build. needs_sphinx = '1.2' # Ignore any .rst files in the venv/ directory. exclude_patterns = ['venv/*'] # Options for HTML output # ----------------------- # Use our custom theme. html_theme = 'pydoctheme' html_theme_path = ['tools'] html_theme_options = {'collapsiblesidebar': True} # Short title used e.g. for <title> HTML tags. html_short_title = '%s Documentation' % release # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # Path to find HTML templates. templates_path = ['tools/templates'] # Custom sidebar templates, filenames relative to this file. html_sidebars = { 'index': 'indexsidebar.html', } # Additional templates that should be rendered to pages. html_additional_pages = { 'download': 'download.html', 'index': 'indexcontent.html', } # Output an OpenSearch description file. html_use_opensearch = 'https://docs.python.org/' + version # Additional static files. html_static_path = ['tools/static'] # Output file base name for HTML help builder. htmlhelp_basename = 'python' + release.replace('.', '') # Split the index html_split_index = True # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). latex_paper_size = 'a4' # The font size ('10pt', '11pt' or '12pt'). latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). _stdauthor = r'<NAME>\\and the Python development team' latex_documents = [ ('c-api/index', 'c-api.tex', 'The Python/C API', _stdauthor, 'manual'), ('distributing/index', 'distributing.tex', 'Distributing Python Modules', _stdauthor, 'manual'), ('extending/index', 'extending.tex', 'Extending and Embedding Python', _stdauthor, 'manual'), ('installing/index', 'installing.tex', 'Installing Python Modules', _stdauthor, 'manual'), ('library/index', 'library.tex', 'The Python Library Reference', _stdauthor, 'manual'), ('reference/index', 'reference.tex', 'The Python Language Reference', _stdauthor, 'manual'), ('tutorial/index', 'tutorial.tex', 'Python Tutorial', _stdauthor, 'manual'), ('using/index', 'using.tex', 'Python Setup and Usage', _stdauthor, 'manual'), ('faq/index', 'faq.tex', 'Python Frequently Asked Questions', _stdauthor, 'manual'), ('whatsnew/' + version, 'whatsnew.tex', 'What\'s New in Python', '<NAME>', 'howto'), ] # Collect all HOWTOs individually latex_documents.extend(('howto/' + fn[:-4], 'howto-' + fn[:-4] + '.tex', '', _stdauthor, 'howto') for fn in os.listdir('howto') if fn.endswith('.rst') and fn != 'index.rst') # Additional stuff for the LaTeX preamble. latex_preamble = r''' \authoraddress{ \strong{Python Software Foundation}\\ Email: \email{<EMAIL>} } \let\Verbatim=\OriginalVerbatim \let\endVerbatim=\endOriginalVerbatim ''' # Documents to append as an appendix to all manuals. latex_appendices = ['glossary', 'about', 'license', 'copyright'] # Get LaTeX to handle Unicode correctly latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''} # Options for Epub output # ----------------------- epub_author = 'Python Documentation Authors' epub_publisher = 'Python Software Foundation' # Options for the coverage checker # -------------------------------- # The coverage checker will ignore all modules/functions/classes whose names # match any of the following regexes (using re.match). coverage_ignore_modules = [ r'[T|t][k|K]', r'Tix', r'distutils.*', ] coverage_ignore_functions = [ 'test($|_)', ] coverage_ignore_classes = [ ] # Glob patterns for C source files for C API coverage, relative to this directory. coverage_c_path = [ '../Include/*.h', ] # Regexes to find C items in the source files. coverage_c_regexes = { 'cfunction': (r'^PyAPI_FUNC\(.*\)\s+([^_][\w_]+)'), 'data': (r'^PyAPI_DATA\(.*\)\s+([^_][\w_]+)'), 'macro': (r'^#define ([^_][\w_]+)\(.*\)[\s|\\]'), } # The coverage checker will ignore all C items whose names match these regexes # (using re.match) -- the keys must be the same as in coverage_c_regexes. coverage_ignore_c_items = { # 'cfunction': [...] } # Options for the link checker # ---------------------------- # Ignore certain URLs. linkcheck_ignore = [r'https://bugs.python.org/(issue)?\d+', # Ignore PEPs for now, they all have permanent redirects. r'http://www.python.org/dev/peps/pep-\d+'] # Options for extensions # ---------------------- # Relative filename of the reference count data file. refcount_file = 'data/refcounts.dat' # Translation # ----------- gettext_compact = False locale_dirs = ["locale"]
1.289063
1
FakeNewsClassifierWithLSTM.py
pratikasarkar/nlp
0
527
# -*- coding: utf-8 -*- """ Created on Thu Feb 11 13:42:45 2021 @author: ASUS """ import pandas as pd df = pd.read_csv(r'D:\nlp\fake-news-data\train.csv') df = df.dropna() X = df.drop('label',axis = 1) y = df['label'] import tensorflow as tf from tensorflow.keras.layers import Embedding, Dense, LSTM from tensorflow.keras.models import Sequential from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.preprocessing.text import one_hot # Vocabulary size voc_size = 5000 # One Hot Representation messages = X.copy() messages.reset_index(inplace = True) import nltk import re from nltk.corpus import stopwords # Dataset Preprocessing from nltk.stem import PorterStemmer ps = PorterStemmer() corpus = [] for i in range(len(messages)): print(i) review = re.sub('[^a-zA-Z]',' ',messages['title'][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if word not in stopwords.words('english')] review = " ".join(review) corpus.append(review) onehot_repr = [one_hot(words,voc_size) for words in corpus] sent_len = 20 embedded_doc = pad_sequences(onehot_repr,maxlen = sent_len,padding = 'pre') # Creating the model embedding_vector_features = 40 model = Sequential() model.add(Embedding(voc_size,embedding_vector_features,input_length=sent_len)) model.add(LSTM(100)) model.add(Dense(1,activation='sigmoid')) model.compile(loss='binary_crossentropy',optimizer = 'adam',metrics = ['accuracy']) model.summary() import numpy as np X_final = np.array(embedded_doc) y_final = np.array(y) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_final,y_final,test_size = 0.33,random_state = 42) model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=10,batch_size=64) y_pred = model.predict_classes(X_test) from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test,y_pred) acc = accuracy_score(y_test,y_pred)
2.046875
2
tests/test_bugs.py
mmibrah2/OpenQL
0
535
import os import filecmp import unittest import numpy as np from openql import openql as ql from utils import file_compare curdir = os.path.dirname(os.path.realpath(__file__)) output_dir = os.path.join(curdir, 'test_output') class Test_bugs(unittest.TestCase): @classmethod def setUp(self): ql.initialize() ql.set_option('output_dir', output_dir) ql.set_option('use_default_gates', 'yes') ql.set_option('log_level', 'LOG_WARNING') # @unittest.expectedFailure # @unittest.skip def test_typecast(self): sweep_points = [1,2] num_circuits = 1 num_qubits = 2 platf = ql.Platform("starmon", 'cc_light') p = ql.Program('test_bug', platf, num_qubits) p.set_sweep_points(sweep_points) k = ql.Kernel('kernel1', platf, num_qubits) qubit = 1 k.identity(np.int(qubit)) k.identity(np.int32(qubit)) k.identity(np.int64(qubit)) k.identity(np.uint(qubit)) k.identity(np.uint32(qubit)) k.identity(np.uint64(qubit)) # add the kernel to the program p.add_kernel(k) # relates to https://github.com/QE-Lab/OpenQL/issues/171 # various runs of compiles were generating different results or in the best # case strange errors. So multiple (NCOMPILES) runs of compile are executed # to make sure there is no error and output generated in all these runs is same # JvS: more likely, it also had to do with the classical register allocator # depending on stuff like Python's garbage collection to free a register. # The register numbers have to be hardcoded now for that reason. def test_stateful_behavior(self): ql.set_option('optimize', 'no') ql.set_option('scheduler', 'ALAP') platform = ql.Platform("myPlatform", 'cc_light') sweep_points = [1] nqubits = 3 nregs = 3 p = ql.Program("statelessProgram", platform, nqubits, nregs) p.set_sweep_points(sweep_points) k = ql.Kernel("aKernel", platform, nqubits, nregs) k.prepz(0) k.gate('rx180', [0]) k.measure(0) rd = ql.CReg(0) rs1 = ql.CReg(1) rs2 = ql.CReg(2) k.classical(rs1, ql.Operation(3)) k.classical(rs1, ql.Operation(4)) k.classical(rd, ql.Operation(rs1, '+', rs2)) p.add_kernel(k) NCOMPILES=50 QISA_fn = os.path.join(output_dir, p.name+'_last.qasm') for i in range(NCOMPILES): p.compile() self.setUpClass() QISA_fn_i = os.path.join(output_dir, p.name+'_'+str(i)+'_last.qasm') os.rename(QISA_fn,QISA_fn_i) for i in range(NCOMPILES-1): QISA_fn_1 = os.path.join(output_dir, p.name+'_'+str(i)+'_last.qasm') QISA_fn_2 = os.path.join(output_dir, p.name+'_'+str(i+1)+'_last.qasm') self.assertTrue( file_compare(QISA_fn_1, QISA_fn_2)) # Unclear how this test works. # When clear, enable it again. # Now it fails, not clear how to repair, so it is disabled. # def test_empty_infinite_loop(self): # name = 'empty_infinite_loop' # in_fn = 'test_' + name + '.cq' # out_fn = 'test_output/' + name + '_out.cq' # gold_fn = 'golden/' + name + '_out.cq' # ql.initialize() # #ql.set_option('log_level', 'LOG_DEBUG') # ql.compile(in_fn) # self.assertTrue(file_compare(out_fn, gold_fn)) if __name__ == '__main__': unittest.main()
1.65625
2
tests/functional/test_soft_round_inverse.py
tallamjr/NeuralCompression
233
543
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from neuralcompression.functional import soft_round, soft_round_inverse def test_soft_round_inverse(): x = torch.linspace(-2.0, 2.0, 50) torch.testing.assert_close( x, soft_round_inverse(x, alpha=1e-13), ) x = torch.tensor([-1.25, -0.75, 0.75, 1.25]) torch.testing.assert_close( x, soft_round_inverse(soft_round(x, alpha=2.0), alpha=2.0), ) for offset in range(-5, 5): x = torch.linspace(offset + 0.001, offset + 0.999, 100) torch.testing.assert_close( torch.ceil(x) - 0.5, soft_round_inverse(x, alpha=5000.0), atol=0.001, rtol=0.002, )
1.648438
2
src/main/python/rds_log_cat/parser/mysql57.py
Scout24/rds-log-cat
1
551
from rds_log_cat.parser.parser import Parser, LineParserException class Mysql57(Parser): def __init__(self): Parser.__init__(self) def compose_timestamp(self, datetime, timezone): if len(datetime) != 27: raise LineParserException('wrong length of datetime - wrong date is: ' + datetime) if not timezone == 'UTC': raise LineParserException('Only able to parse times in UTC. You gave {}'.format(timezone)) return datetime def parse(self, line): """ parses the fields in line to generate json structure """ expected_min_no_fields = 5 if len(line) < expected_min_no_fields: raise LineParserException('line too short') pid = line[1] log_level = line[2].lstrip("[").rstrip("]") timezone = 'UTC' return { '@timestamp': self.compose_timestamp(line[0], timezone), 'log_level': log_level, 'process_id': int(pid), 'message': ' '.join(map(str, line[3:])) }
1.375
1
venv/lib/python3.6/site-packages/ansible_collections/community/azure/plugins/modules/azure_rm_availabilityset_info.py
usegalaxy-no/usegalaxy
1
575
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_availabilityset_info short_description: Get Azure Availability Set facts description: - Get facts for a specific availability set or all availability sets. options: name: description: - Limit results to a specific availability set. resource_group: description: - The resource group to search for the desired availability set. tags: description: - List of tags to be matched. extends_documentation_fragment: - azure.azcollection.azure author: - <NAME> (@julienstroheker) deprecated: removed_in: '2.0.0' why: The Ansible collection community.azure is deprecated. Use azure.azcollection instead. alternative: Use M(azure.azcollection.azure_rm_availabilityset_info) instead. ''' EXAMPLES = ''' - name: Get facts for one availability set community.azure.azure_rm_availabilityset_info: name: Testing resource_group: myResourceGroup - name: Get facts for all availability sets in a specific resource group community.azure.azure_rm_availabilityset_info: resource_group: myResourceGroup ''' RETURN = ''' azure_availabilityset: description: List of availability sets dicts. returned: always type: complex contains: location: description: - Location where the resource lives. type: str sample: eastus2 name: description: - Resource name. type: str sample: myAvailabilitySet properties: description: - The properties of the resource. type: dict contains: platformFaultDomainCount: description: - Fault Domain count. type: int sample: 3 platformUpdateDomainCount: description: - Update Domain count. type: int sample: 2 virtualMachines: description: - A list of references to all virtualmachines in the availability set. type: list sample: [] sku: description: - Location where the resource lives. type: str sample: Aligned type: description: - Resource type. type: str sample: "Microsoft.Compute/availabilitySets" tags: description: - Resource tags. type: dict sample: { env: sandbox } ''' from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase try: from msrestazure.azure_exceptions import CloudError except Exception: # handled in azure_rm_common pass AZURE_OBJECT_CLASS = 'AvailabilitySet' class AzureRMAvailabilitySetInfo(AzureRMModuleBase): """Utility class to get availability set facts""" def __init__(self): self.module_args = dict( name=dict(type='str'), resource_group=dict(type='str'), tags=dict(type='list') ) self.results = dict( changed=False, ansible_info=dict( azure_availabilitysets=[] ) ) self.name = None self.resource_group = None self.tags = None super(AzureRMAvailabilitySetInfo, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): is_old_facts = self.module._name == 'azure_rm_availabilityset_facts' if is_old_facts: self.module.deprecate("The 'azure_rm_availabilityset_facts' module has been renamed to 'azure_rm_availabilityset_info'", version='3.0.0', collection_name='community.azure') # was 2.13 for key in self.module_args: setattr(self, key, kwargs[key]) if self.name and not self.resource_group: self.fail("Parameter error: resource group required when filtering by name.") if self.name: self.results['ansible_info']['azure_availabilitysets'] = self.get_item() else: self.results['ansible_info']['azure_availabilitysets'] = self.list_items() return self.results def get_item(self): """Get a single availability set""" self.log('Get properties for {0}'.format(self.name)) item = None result = [] try: item = self.compute_client.availability_sets.get(self.resource_group, self.name) except CloudError: pass if item and self.has_tags(item.tags, self.tags): avase = self.serialize_obj(item, AZURE_OBJECT_CLASS) avase['name'] = item.name avase['type'] = item.type avase['sku'] = item.sku.name result = [avase] return result def list_items(self): """Get all availability sets""" self.log('List all availability sets') try: response = self.compute_client.availability_sets.list(self.resource_group) except CloudError as exc: self.fail('Failed to list all items - {0}'.format(str(exc))) results = [] for item in response: if self.has_tags(item.tags, self.tags): avase = self.serialize_obj(item, AZURE_OBJECT_CLASS) avase['name'] = item.name avase['type'] = item.type avase['sku'] = item.sku.name results.append(avase) return results def main(): """Main module execution code path""" AzureRMAvailabilitySetInfo() if __name__ == '__main__': main()
1.28125
1
influxdb_service_sdk/model/container/resource_requirements_pb2.py
easyopsapis/easyops-api-python
5
583
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: resource_requirements.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from influxdb_service_sdk.model.container import resource_list_pb2 as influxdb__service__sdk_dot_model_dot_container_dot_resource__list__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='resource_requirements.proto', package='container', syntax='proto3', serialized_options=_b('ZCgo.easyops.local/contracts/protorepo-models/easyops/model/container'), serialized_pb=_b('\n\x1bresource_requirements.proto\x12\tcontainer\x1a\x38influxdb_service_sdk/model/container/resource_list.proto\"j\n\x14ResourceRequirements\x12\'\n\x06limits\x18\x01 \x01(\x0b\x32\x17.container.ResourceList\x12)\n\x08requests\x18\x02 \x01(\x0b\x32\x17.container.ResourceListBEZCgo.easyops.local/contracts/protorepo-models/easyops/model/containerb\x06proto3') , dependencies=[influxdb__service__sdk_dot_model_dot_container_dot_resource__list__pb2.DESCRIPTOR,]) _RESOURCEREQUIREMENTS = _descriptor.Descriptor( name='ResourceRequirements', full_name='container.ResourceRequirements', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='limits', full_name='container.ResourceRequirements.limits', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='requests', full_name='container.ResourceRequirements.requests', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=100, serialized_end=206, ) _RESOURCEREQUIREMENTS.fields_by_name['limits'].message_type = influxdb__service__sdk_dot_model_dot_container_dot_resource__list__pb2._RESOURCELIST _RESOURCEREQUIREMENTS.fields_by_name['requests'].message_type = influxdb__service__sdk_dot_model_dot_container_dot_resource__list__pb2._RESOURCELIST DESCRIPTOR.message_types_by_name['ResourceRequirements'] = _RESOURCEREQUIREMENTS _sym_db.RegisterFileDescriptor(DESCRIPTOR) ResourceRequirements = _reflection.GeneratedProtocolMessageType('ResourceRequirements', (_message.Message,), { 'DESCRIPTOR' : _RESOURCEREQUIREMENTS, '__module__' : 'resource_requirements_pb2' # @@protoc_insertion_point(class_scope:container.ResourceRequirements) }) _sym_db.RegisterMessage(ResourceRequirements) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
0.902344
1
studies/mixture_feasibility/parsley_benchmark/alcohol_ester/run.py
openforcefield/nistdataselection
3
607
from evaluator import unit from evaluator.backends import QueueWorkerResources from evaluator.backends.dask import DaskLSFBackend from evaluator.client import ConnectionOptions, EvaluatorClient from evaluator.datasets import PhysicalPropertyDataSet from evaluator.forcefield import SmirnoffForceFieldSource from evaluator.server import EvaluatorServer from evaluator.utils import setup_timestamp_logging def main(): setup_timestamp_logging() # Load in the force field force_field_path = "openff-1.0.0.offxml" force_field_source = SmirnoffForceFieldSource.from_path(force_field_path) # Load in the test set. data_set = PhysicalPropertyDataSet.from_json("full_set.json") # Set up a server object to run the calculations using. working_directory = "working_directory" # Set up a backend to run the calculations on. This assume running # on a HPC resources with the LSF queue system installed. queue_resources = QueueWorkerResources( number_of_threads=1, number_of_gpus=1, preferred_gpu_toolkit=QueueWorkerResources.GPUToolkit.CUDA, per_thread_memory_limit=5 * unit.gigabyte, wallclock_time_limit="05:59", ) worker_script_commands = ["conda activate forcebalance", "module load cuda/10.1"] calculation_backend = DaskLSFBackend( minimum_number_of_workers=1, maximum_number_of_workers=50, resources_per_worker=queue_resources, queue_name="gpuqueue", setup_script_commands=worker_script_commands, adaptive_interval="1000ms", ) with calculation_backend: server = EvaluatorServer( calculation_backend=calculation_backend, working_directory=working_directory, port=8004, ) with server: # Request the estimates. client = EvaluatorClient(ConnectionOptions(server_port=8004)) request, _ = client.request_estimate( property_set=data_set, force_field_source=force_field_source, ) # Wait for the results. results, _ = request.results(True, 5) results.json(f"results.json") if __name__ == "__main__": main()
1.414063
1
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card