blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
319a26e285ba0b3dd2ed26cc8707ab62a6c12548
77717d0024c8597fec83600259ea5547abbc183a
/tools/test_robustness.py
478eafb2c6408aeccc059e44ca00556b1f601877
[ "Apache-2.0" ]
permissive
fengyouliang/wheat_detection
0a090ef5eda7f2c5463996f4795f9ce06dd04050
d056123426a1260c29b486cbb8e44a88a0a3c5bc
refs/heads/master
2022-11-17T15:09:29.113493
2020-07-18T13:47:34
2020-07-18T13:47:34
276,532,878
0
0
null
null
null
null
UTF-8
Python
false
false
17,611
py
import argparse import copy import os import os.path as osp import shutil import tempfile import mmcv import torch import torch.distributed as dist from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, load_checkpoint from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from robustness_eval import get_results from mmdet import datasets from mmdet.apis import set_random_seed from mmdet.core import encode_mask_results, eval_map, wrap_fp16_model from mmdet.datasets import build_dataloader, build_dataset from mmdet.models import build_detector def coco_eval_with_return(result_files, result_types, coco, max_dets=(100, 300, 1000)): for res_type in result_types: assert res_type in ['proposal', 'bbox', 'segm', 'keypoints'] if mmcv.is_str(coco): coco = COCO(coco) assert isinstance(coco, COCO) eval_results = {} for res_type in result_types: result_file = result_files[res_type] assert result_file.endswith('.json') coco_dets = coco.loadRes(result_file) img_ids = coco.getImgIds() iou_type = 'bbox' if res_type == 'proposal' else res_type cocoEval = COCOeval(coco, coco_dets, iou_type) cocoEval.params.imgIds = img_ids if res_type == 'proposal': cocoEval.params.useCats = 0 cocoEval.params.maxDets = list(max_dets) cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() if res_type == 'segm' or res_type == 'bbox': metric_names = [ 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'AR1', 'AR10', 'AR100', 'ARs', 'ARm', 'ARl' ] eval_results[res_type] = { metric_names[i]: cocoEval.stats[i] for i in range(len(metric_names)) } else: eval_results[res_type] = cocoEval.stats return eval_results def voc_eval_with_return(result_file, dataset, iou_thr=0.5, logger='print', only_ap=True): det_results = mmcv.load(result_file) annotations = [dataset.get_ann_info(i) for i in range(len(dataset))] if hasattr(dataset, 'year') and dataset.year == 2007: dataset_name = 'voc07' else: dataset_name = dataset.CLASSES mean_ap, eval_results = eval_map( det_results, annotations, scale_ranges=None, iou_thr=iou_thr, dataset=dataset_name, logger=logger) if only_ap: eval_results = [{ 'ap': eval_results[i]['ap'] } for i in range(len(eval_results))] return mean_ap, eval_results def single_gpu_test(model, data_loader, show=False): model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=not show, **data) if show: model.module.show_result(data, result, dataset.img_norm_cfg) # encode mask results if isinstance(result, tuple): bbox_results, mask_results = result encoded_mask_results = encode_mask_results(mask_results) result = bbox_results, encoded_mask_results results.append(result) batch_size = data['img'][0].size(0) for _ in range(batch_size): prog_bar.update() return results def multi_gpu_test(model, data_loader, tmpdir=None): model.eval() results = [] dataset = data_loader.dataset rank, world_size = get_dist_info() if rank == 0: prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) # encode mask results if isinstance(result, tuple): bbox_results, mask_results = result encoded_mask_results = encode_mask_results(mask_results) result = bbox_results, encoded_mask_results results.append(result) results.append(result) if rank == 0: batch_size = data['img'][0].size(0) for _ in range(batch_size * world_size): prog_bar.update() # collect results from all ranks results = collect_results(results, len(dataset), tmpdir) return results def collect_results(result_part, size, tmpdir=None): rank, world_size = get_dist_info() # create a tmp dir if it is not specified if tmpdir is None: MAX_LEN = 512 # 32 is whitespace dir_tensor = torch.full((MAX_LEN, ), 32, dtype=torch.uint8, device='cuda') if rank == 0: tmpdir = tempfile.mkdtemp() tmpdir = torch.tensor( bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda') dir_tensor[:len(tmpdir)] = tmpdir dist.broadcast(dir_tensor, 0) tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip() else: mmcv.mkdir_or_exist(tmpdir) # dump the part result to the dir mmcv.dump(result_part, osp.join(tmpdir, f'part_{rank}.pkl')) dist.barrier() # collect all parts if rank != 0: return None else: # load results of all parts from tmp dir part_list = [] for i in range(world_size): part_file = osp.join(tmpdir, f'part_{i}.pkl') part_list.append(mmcv.load(part_file)) # sort the results ordered_results = [] for res in zip(*part_list): ordered_results.extend(list(res)) # the dataloader may pad some samples ordered_results = ordered_results[:size] # remove tmp dir shutil.rmtree(tmpdir) return ordered_results def parse_args(): parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', help='output result file') parser.add_argument( '--corruptions', type=str, nargs='+', default='benchmark', choices=[ 'all', 'benchmark', 'noise', 'blur', 'weather', 'digital', 'holdout', 'None', 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression', 'speckle_noise', 'gaussian_blur', 'spatter', 'saturate' ], help='corruptions') parser.add_argument( '--severities', type=int, nargs='+', default=[0, 1, 2, 3, 4, 5], help='corruption severity levels') parser.add_argument( '--eval', type=str, nargs='+', choices=['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'], help='eval types') parser.add_argument( '--iou-thr', type=float, default=0.5, help='IoU threshold for pascal voc evaluation') parser.add_argument( '--summaries', type=bool, default=False, help='Print summaries for every corruption and severity') parser.add_argument( '--workers', type=int, default=32, help='workers per gpu') parser.add_argument('--show', action='store_true', help='show results') parser.add_argument('--tmpdir', help='tmp dir for writing some results') parser.add_argument('--seed', type=int, default=None, help='random seed') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) parser.add_argument( '--final-prints', type=str, nargs='+', choices=['P', 'mPC', 'rPC'], default='mPC', help='corruption benchmark metric to print at the end') parser.add_argument( '--final-prints-aggregate', type=str, choices=['all', 'benchmark'], default='benchmark', help='aggregate all results or only those for benchmark corruptions') args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def main(): args = parse_args() assert args.out or args.show, \ ('Please specify at least one operation (save or show the results) ' 'with the argument "--out" or "--show"') if args.out is not None and not args.out.endswith(('.pkl', '.pickle')): raise ValueError('The output file must be a pkl file.') cfg = mmcv.Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None cfg.data.test.test_mode = True if args.workers == 0: args.workers = cfg.data.workers_per_gpu # init distributed env first, since logger depends on the dist info. if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) # set random seeds if args.seed is not None: set_random_seed(args.seed) if 'all' in args.corruptions: corruptions = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression', 'speckle_noise', 'gaussian_blur', 'spatter', 'saturate' ] elif 'benchmark' in args.corruptions: corruptions = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression' ] elif 'noise' in args.corruptions: corruptions = ['gaussian_noise', 'shot_noise', 'impulse_noise'] elif 'blur' in args.corruptions: corruptions = [ 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur' ] elif 'weather' in args.corruptions: corruptions = ['snow', 'frost', 'fog', 'brightness'] elif 'digital' in args.corruptions: corruptions = [ 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression' ] elif 'holdout' in args.corruptions: corruptions = ['speckle_noise', 'gaussian_blur', 'spatter', 'saturate'] elif 'None' in args.corruptions: corruptions = ['None'] args.severities = [0] else: corruptions = args.corruptions rank, _ = get_dist_info() aggregated_results = {} for corr_i, corruption in enumerate(corruptions): aggregated_results[corruption] = {} for sev_i, corruption_severity in enumerate(args.severities): # evaluate severity 0 (= no corruption) only once if corr_i > 0 and corruption_severity == 0: aggregated_results[corruption][0] = \ aggregated_results[corruptions[0]][0] continue test_data_cfg = copy.deepcopy(cfg.data.test) # assign corruption and severity if corruption_severity > 0: corruption_trans = dict( type='Corrupt', corruption=corruption, severity=corruption_severity) # TODO: hard coded "1", we assume that the first step is # loading images, which needs to be fixed in the future test_data_cfg['pipeline'].insert(1, corruption_trans) # print info print(f'\nTesting {corruption} at severity {corruption_severity}') # build the dataloader # TODO: support multiple images per gpu # (only minor changes are needed) dataset = build_dataset(test_data_cfg) data_loader = build_dataloader( dataset, samples_per_gpu=1, workers_per_gpu=args.workers, dist=distributed, shuffle=False) # build the model and load checkpoint model = build_detector( cfg.model, train_cfg=None, test_cfg=cfg.test_cfg) fp16_cfg = cfg.get('fp16', None) if fp16_cfg is not None: wrap_fp16_model(model) checkpoint = load_checkpoint( model, args.checkpoint, map_location='cpu') # old versions did not save class info in checkpoints, # this walkaround is for backward compatibility if 'CLASSES' in checkpoint['meta']: model.CLASSES = checkpoint['meta']['CLASSES'] else: model.CLASSES = dataset.CLASSES if not distributed: model = MMDataParallel(model, device_ids=[0]) outputs = single_gpu_test(model, data_loader, args.show) else: model = MMDistributedDataParallel( model.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False) outputs = multi_gpu_test(model, data_loader, args.tmpdir) if args.out and rank == 0: eval_results_filename = ( osp.splitext(args.out)[0] + '_results' + osp.splitext(args.out)[1]) mmcv.dump(outputs, args.out) eval_types = args.eval if cfg.dataset_type == 'VOCDataset': if eval_types: for eval_type in eval_types: if eval_type == 'bbox': test_dataset = mmcv.runner.obj_from_dict( cfg.data.test, datasets) logger = 'print' if args.summaries else None mean_ap, eval_results = \ voc_eval_with_return( args.out, test_dataset, args.iou_thr, logger) aggregated_results[corruption][ corruption_severity] = eval_results else: print('\nOnly "bbox" evaluation \ is supported for pascal voc') else: if eval_types: print(f'Starting evaluate {" and ".join(eval_types)}') if eval_types == ['proposal_fast']: result_file = args.out else: if not isinstance(outputs[0], dict): result_files = dataset.results2json( outputs, args.out) else: for name in outputs[0]: print(f'\nEvaluating {name}') outputs_ = [out[name] for out in outputs] result_file = args.out + f'.{name}' result_files = dataset.results2json( outputs_, result_file) eval_results = coco_eval_with_return( result_files, eval_types, dataset.coco) aggregated_results[corruption][ corruption_severity] = eval_results else: print('\nNo task was selected for evaluation;' '\nUse --eval to select a task') # save results after each evaluation mmcv.dump(aggregated_results, eval_results_filename) if rank == 0: # print filan results print('\nAggregated results:') prints = args.final_prints aggregate = args.final_prints_aggregate if cfg.dataset_type == 'VOCDataset': get_results( eval_results_filename, dataset='voc', prints=prints, aggregate=aggregate) else: get_results( eval_results_filename, dataset='coco', prints=prints, aggregate=aggregate) if __name__ == '__main__': main()
[ "1654388696@qq.com" ]
1654388696@qq.com
ec96395680b9454b0b1a4e15719186c299b15355
8c4e20343b8e901981f592ec420356dd5c7d3079
/mapproxy/test/helper.py
f5a0d4b4bf35d159e0f2df7121873abfa94f876c
[ "BSD-3-Clause", "Python-2.0", "Bitstream-Vera", "MIT", "ZPL-2.1", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
jukkatolonen/mapproxy
94337ee44b7b47d11d717bcb9d36969d8cb03ce1
e4ad1972858dfbb72d8686c5b59751b4b781fc35
refs/heads/master
2021-02-10T04:00:13.079893
2020-03-05T15:18:16
2020-03-05T15:18:16
244,350,181
0
1
NOASSERTION
2020-03-03T13:48:35
2020-03-02T11:07:43
null
UTF-8
Python
false
false
7,623
py
# This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import tempfile import os import re import sys from glob import glob as globfunc from contextlib import contextmanager from lxml import etree from mapproxy.test import mocker from mapproxy.compat import string_type, PY2 class Mocker(object): """ This is a base class for unit-tests that use ``mocker``. This class follows the xUnit naming conventions for setup and teardown methods. `setup` will initialize a `mocker.Mocker`. The `teardown` method will run ``mocker.verify()``. """ def setup(self): self.mocker = mocker.Mocker() def expect_and_return(self, mock_call, return_val): """ Register a return value for the mock call. :param return_val: The value mock_call should return. """ self.mocker.result(return_val) def expect(self, mock_call): return mocker.expect(mock_call) def replay(self): """ Finish mock-record phase. """ self.mocker.replay() def mock(self, base_cls=None): """ Return a new mock object. :param base_cls: check method signatures of the mock-calls with this base_cls signature (optional) """ if base_cls: return self.mocker.mock(base_cls) return self.mocker.mock() def teardown(self): self.mocker.verify() class TempFiles(object): """ This class is a context manager for temporary files. >>> with TempFiles(n=2, suffix='.png') as tmp: ... for f in tmp: ... assert os.path.exists(f) >>> for f in tmp: ... assert not os.path.exists(f) """ def __init__(self, n=1, suffix='', no_create=False): self.n = n self.suffix = suffix self.no_create = no_create self.tmp_files = [] def __enter__(self): for _ in range(self.n): fd, tmp_file = tempfile.mkstemp(suffix=self.suffix) os.close(fd) self.tmp_files.append(tmp_file) if self.no_create: os.remove(tmp_file) return self.tmp_files def __exit__(self, exc_type, exc_val, exc_tb): for tmp_file in self.tmp_files: if os.path.exists(tmp_file): os.remove(tmp_file) self.tmp_files = [] class TempFile(TempFiles): def __init__(self, suffix='', no_create=False): TempFiles.__init__(self, suffix=suffix, no_create=no_create) def __enter__(self): return TempFiles.__enter__(self)[0] class LogMock(object): log_methods = ('info', 'debug', 'warn', 'error', 'fail') def __init__(self, module, log_name='log'): self.module = module self.orig_logger = None self.logged_msgs = [] def __enter__(self): self.orig_logger = self.module.log self.module.log = self return self def __getattr__(self, name): if name in self.log_methods: def _log(msg): self.logged_msgs.append((name, msg)) return _log raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) def assert_log(self, type, msg): log_type, log_msg = self.logged_msgs.pop(0) assert log_type == type, 'expected %s log message, but was %s' % (type, log_type) assert msg in log_msg.lower(), "expected string '%s' in log message '%s'" % \ (msg, log_msg) def __exit__(self, exc_type, exc_val, exc_tb): self.module.log = self.orig_logger def assert_re(value, regex): """ >>> assert_re('hello', 'l+') >>> assert_re('hello', 'l{3}') Traceback (most recent call last): ... AssertionError: hello ~= l{3} """ match = re.search(regex, value) assert match is not None, '%s ~= %s' % (value, regex) def assert_files_in_dir(dir, expected, glob=None): """ assert that (only) ``expected`` files are in ``dir``. ``filter`` can be a globbing patter, other files are ignored if it is set. """ if glob is not None: files = globfunc(os.path.join(dir, glob)) files = [os.path.basename(f) for f in files] else: files = os.listdir(dir) files.sort() assert sorted(expected) == files def validate_with_dtd(doc, dtd_name, dtd_basedir=None): if dtd_basedir is None: dtd_basedir = os.path.join(os.path.dirname(__file__), 'schemas') dtd_filename = os.path.join(dtd_basedir, dtd_name) with open(dtd_filename, 'rb') as schema: dtd = etree.DTD(schema) if isinstance(doc, (string_type, bytes)): xml = etree.XML(doc) else: xml = doc is_valid = dtd.validate(xml) print(dtd.error_log.filter_from_errors()) return is_valid def validate_with_xsd(doc, xsd_name, xsd_basedir=None): if xsd_basedir is None: xsd_basedir = os.path.join(os.path.dirname(__file__), 'schemas') xsd_filename = os.path.join(xsd_basedir, xsd_name) with open(xsd_filename, 'rb') as schema: xsd = etree.parse(schema) xml_schema = etree.XMLSchema(xsd) if isinstance(doc, (string_type, bytes)): xml = etree.XML(doc) else: xml = doc is_valid = xml_schema.validate(xml) print(xml_schema.error_log.filter_from_errors()) return is_valid class XPathValidator(object): def __init__(self, doc): self.xml = etree.XML(doc) def assert_xpath(self, xpath, expected=None): assert len(self.xml.xpath(xpath)) > 0, xpath + ' does not match anything' if expected is not None: if callable(expected): assert expected(self.xml.xpath(xpath)[0]) else: assert self.xml.xpath(xpath)[0] == expected def xpath(self, xpath): return self.xml.xpath(xpath) def strip_whitespace(data): """ >>> strip_whitespace(' <foo> bar\\n zing\\t1') '<foo>barzing1' """ if isinstance(data, bytes): return re.sub(b'\s+', b'', data) else: return re.sub('\s+', '', data) @contextmanager def capture(bytes=False): if PY2: from StringIO import StringIO else: if bytes: from io import BytesIO as StringIO else: from io import StringIO backup_stdout = sys.stdout backup_stderr = sys.stderr try: sys.stdout = StringIO() sys.stderr = StringIO() yield sys.stdout, sys.stderr except Exception as ex: backup_stdout.write(str(ex)) if bytes: backup_stdout.write(sys.stdout.getvalue().decode('utf-8')) backup_stderr.write(sys.stderr.getvalue().decode('utf-8')) else: backup_stdout.write(sys.stdout.getvalue()) backup_stderr.write(sys.stderr.getvalue()) raise finally: sys.stdout = backup_stdout sys.stderr = backup_stderr
[ "olt@bogosoft.com" ]
olt@bogosoft.com
8fbe0b915a4895d240f0b8f9a530e338488a7fde
be7cdd0c8e55a8fec0d1b226c2ea1664f28636a5
/steps/step39.py
1f3824de4816a17de355a3d6b1cfa5e9647f3311
[ "MIT" ]
permissive
peaceiris/deep-learning-from-scratch-3
8274ba7735dc36a86305bfe3db683423aff2095e
6f05c642cb6d1ee1f25f5b3ed538f1d1d19a4a08
refs/heads/master
2021-03-25T02:19:09.161809
2020-03-13T02:16:18
2020-03-13T02:16:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
564
py
import os, sys; if '__file__' in globals(): sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import numpy as np from dezero import Variable import dezero.functions as F x = Variable(np.array([1, 2, 3, 4, 5, 6])) y = F.sum(x) y.backward() print(y) print(x.grad) x = Variable(np.array([[1, 2, 3], [4, 5, 6]])) y = F.sum(x) y.backward() print(y) print(x.grad) x = Variable(np.array([[1, 2, 3], [4, 5, 6]])) y = F.sum(x, axis=0) y.backward() print(y) print(x.grad) x = Variable(np.random.randn(2, 3, 4, 5)) y = x.sum(keepdims=True) print(y.shape)
[ "koki0702@gmail.com" ]
koki0702@gmail.com
e67818904e5a156fb0c9b8bb42a92efd60ef479d
0421da0c3ba42e4758cb4da4679f3218d4ea733d
/setup_cython.py
4a9d2d872ad922a9379f7f8eecc98ad916038591
[]
no_license
vanife/Mandelbrot_pyCUDA_Cython_Numpy
f252a6773791414468859a77e8ed0d6bd1dc2586
baa164a392078019dffc886981f0107ad3f0fca1
refs/heads/master
2021-01-18T01:54:56.383453
2010-10-29T16:54:44
2010-10-29T16:54:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
310
py
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy ext = Extension("mandel", ["mandelbrot_cython.pyx"], include_dirs = [numpy.get_include()]) setup(ext_modules=[ext], cmdclass = {'build_ext': build_ext})
[ "ian@ianozsvald.com" ]
ian@ianozsvald.com
3b34f72942d5a210ed18059182dee423557a6d20
c855bc4640a54630b62fafd89a20967606a8f14e
/breadth_first_search/200_number_of_islands.py
f01cf9ae63404df6a0a9aa9d380da3c0c64bdc5b
[ "MIT" ]
permissive
asethi-ds/Algorithm-Toolbox
0d8f7e68ebce47810c7dd88df0bb6d911013e1d1
b6c7b2228d8e70e0842e0bad607533a2c8322cf0
refs/heads/master
2021-01-02T15:44:06.833196
2019-08-31T11:32:11
2019-08-31T11:32:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,485
py
class DU(object): def __init__(self, n): self.count = 0 self.parent = [-1] * n self.rank = [0] * n def isLand(self, idx): return self.parent[idx] != -1 def setLand(self, idx): self.parent[idx] = idx # initialize parent to itself self.count += 1 def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] # DO NOT RETURN x def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return if self.rank[xr] < self.rank[yr]: self.parent[xr] = yr # setting parent of ROOT elif self.rank[xr] > self.rank[yr]: self.parent[yr] = xr # setting parent of ROOT else: self.parent[xr] = yr # setting parent of ROOT self.rank[yr] += 1 self.count -= 1 class Solution2: def numIslands(self, grid: 'List[List[str]]') -> 'int': # empty array if not grid or not grid[0]: return 0 nr, nc = len(grid), len(grid[0]) du = DU(nr * nc) for r in range(nr): for c in range(nc): if grid[r][c] == "1": du.setLand(r * nc + c) for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: candr = r + dr candc = c + dc if 0 <= candr < nr and 0 <= candc < nc and du.isLand(candr * nc + candc): du.union(r * nc + c, candr * nc + candc) return du.count # clean solution class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int edge case: [], [[]] """ # use for loop to implicitly handle edge case # nrow = len(grid) # if nrow == 0: return 0 # ncol = len(grid[0]) def bfs(r, c): queue = [(r, c)] steps = [(-1, 0), (0, 1), (1, 0), (0, -1)] # left, up, right, down inBound = lambda r, c: 0 <= r < len(grid) and 0 <= c < len(grid[0]) grid[r][c] = "0" # mark starter node while queue: r, c = queue.pop(0) # pop left for dr, dc in steps: rr, cc = r + dr, c + dc if inBound(rr, cc) and grid[rr][cc] == "1": grid[rr][cc] = "0" # mark before appending, to avoid revisiting queue.append((rr, cc)) nlands = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == "1": nlands += 1 bfs(r, c) return nlands # verbose solution, no code refactoring # class Solution(object): # def numIslands(self, grid): # """ # :type grid: List[List[str]] # :rtype: int # """ # if not grid: # return 0 # nrows = len(grid) # ncols = len(grid[0]) # # n = 0 # for r in range(nrows): # for c in range(ncols): # if grid[r][c] == "1": # n += 1 # # queue = [] # queue.append((r, c)) # while queue: # print(queue) # node = queue.pop(0) # grid[node[0]][node[1]] = "0" # if node[0] - 1 >= 0 and grid[node[0] - 1][node[1]] == '1' and (node[0] - 1, node[1]) not in queue: # queue.append((node[0] - 1, node[1])) # if node[0] + 1 < nrows and grid[node[0] + 1][node[1]] == '1' and (node[0] + 1, node[1]) not in queue: # queue.append((node[0] + 1, node[1])) # if node[1] - 1 >= 0 and grid[node[0]][node[1] - 1] == '1' and (node[0], node[1] - 1) not in queue: # queue.append((node[0], node[1] - 1)) # if node[1] + 1 < ncols and grid[node[0]][node[1] + 1] == '1' and (node[0], node[1] + 1) not in queue: # queue.append((node[0], node[1] + 1)) # # print(n) # return n solver = Solution() solver.numIslands([["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"]])
[ "shawlu@github.com" ]
shawlu@github.com
cfa87a320b1aed769df2a85d3e917fa91cae9bdb
6b70e48ddc38f58a142229bcfb5c4dc5553dfd4f
/tests/year2015/test_day05.py
5cbb7ea5658d39adf0fabe78343051ab4404f93d
[]
no_license
N8Brooks/aoc_py
eaea98db5cdd1c795edae48a46f765e0628b53e8
fab391ac33aa3c9623e8f5d2b9af44693c04bd00
refs/heads/master
2023-02-22T20:07:16.265316
2021-01-27T02:50:47
2021-01-27T02:50:47
326,284,848
0
0
null
null
null
null
UTF-8
Python
false
false
1,240
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ https://adventofcode.com/2015/day/5 """ from unittest import TestCase, main from aoc.year2015.day05 import part1, part2 from data.utils import get_input class TestPart1(TestCase): def test_input(self): self.assertEqual(part1(get_input(2015, 5)), 238) def test_example_1(self): self.assertEqual(part1("ugknbfddgicrmopn"), 1) def test_example_2(self): self.assertEqual(part1("aaa"), 1) def test_example_3(self): self.assertEqual(part1("jchzalrnumimnmhp"), 0) def test_example_4(self): self.assertEqual(part1("haegwjzuvuyypxyu"), 0) def test_example_5(self): self.assertEqual(part1("dvszwmarrgswjxmb"), 0) class TestPart2(TestCase): def test_input(self): self.assertEqual(part2(get_input(2015, 5)), 69) def test_example_1(self): self.assertEqual(part2("qjhvhtzxzqqjkmpb"), 1) def test_example_2(self): self.assertEqual(part2("xxyxx"), 1) def test_example_3(self): self.assertEqual(part2("uurcxstgmygtbstg"), 0) def test_example_4(self): self.assertEqual(part2("ieodomkazucvgmuy"), 0) if __name__ == "__main__": # pragma: no cover main()
[ "natebrooks004@gmail.com" ]
natebrooks004@gmail.com
99017c4177c3a784d610e345e4fbeb33dcbb03b1
78980891d3137810bf3a3c1bb229966b7f49f0dd
/leetcode_projects/leetcode_79/main.py
81c9df7e276c5deb6365ca9f25aa4e317a87f92d
[]
no_license
miniyk2012/leetcode
204927d3aefc9746070c1bf13abde517c6c16dc0
91ca9cd0df3c88fc7ef3c829dacd4d13f6b71ab1
refs/heads/master
2021-06-17T21:50:31.001111
2021-03-10T11:36:23
2021-03-10T11:36:23
185,042,818
1
0
null
null
null
null
UTF-8
Python
false
false
1,586
py
from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))] for i in range(len(board)): for j in range(len(board[i])): if self.dfs_visit(board, i, j, visited, word): return True return False def dfs_visit(self, board, i, j, visited, word): if word == '' or board[i][j] == word: return True if board[i][j] != word[0]: return False visited[i][j] = True if i - 1 >= 0 and not visited[i - 1][j]: if self.dfs_visit(board, i - 1, j, visited, word[1:]): return True if i + 1 < len(board) and not visited[i + 1][j]: if self.dfs_visit(board, i + 1, j, visited, word[1:]): return True if j - 1 >= 0 and not visited[i][j - 1]: if self.dfs_visit(board, i, j - 1, visited, word[1:]): return True if j + 1 < len(board[0]) and not visited[i][j + 1]: if self.dfs_visit(board, i, j + 1, visited, word[1:]): return True visited[i][j] = False return False if __name__ == '__main__': s = Solution() board = [ ['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E'] ] word = "ABCCED" print(s.exist(board, word)) word = "SEE" print(s.exist(board, word)) word = "ABCB" print(s.exist(board, word)) print(s.exist([["a"]], "a"))
[ "yk_ecust_2007@163.com" ]
yk_ecust_2007@163.com
93e98da2888ffdc5e81a842198548cdc41a1f8b7
5fe72bb13baf3649058ebe11aa86ad4fc56c69ed
/hard-gists/8555125/snippet.py
2e295f5380a400a7b3a6254a9c0e1ce26a8c10c3
[ "Apache-2.0" ]
permissive
dockerizeme/dockerizeme
8825fed45ff0ce8fb1dbe34959237e8048900a29
408f3fa3d36542d8fc1236ba1cac804de6f14b0c
refs/heads/master
2022-12-10T09:30:51.029846
2020-09-02T13:34:49
2020-09-02T13:34:49
144,501,661
24
20
Apache-2.0
2022-11-21T12:34:29
2018-08-12T21:21:04
Python
UTF-8
Python
false
false
799
py
#!/usr/bin/env python from gmusicapi import Musicmanager from gmusicapi import Mobileclient import sys import os.path params = sys.argv if len(params) < 2: print "usage:" + sys.argv[0] + " filename [playlist name]" sys.exit() file = params[1] if len(params) == 3: plname = params[2] else: plname = None mm = Musicmanager() api = Mobileclient() mm.login() api.login('GoogleID', 'Password') track = mm.upload(file) track_id = track[0][file] if plname: playlist_id = None playlists = api.get_all_playlists() for playlist in playlists: if plname == playlist['name']: playlist_id = playlist['id'] break if playlist_id == None: playlist_id = api.create_playlist(plname) api.add_songs_to_playlist(playlist_id, track_id)
[ "42325807+dockerizeme@users.noreply.github.com" ]
42325807+dockerizeme@users.noreply.github.com
9712d805806c5ebc08e5a784664f19fa245f635e
0bc0db1edc610c9f08261c777d06cb1be4b7a524
/lgp/pythonSpider/ch6_baseSpider/SpiderMan.py
27fa7cea73087d54c1dc84ca5aae57aee0591090
[]
no_license
danpianji/python3.7
9bc7f9a765ec76d7d4c5fb413dcdada4f9e8f510
f66bc7139f9441583b1043d3da11597987e3fbc0
refs/heads/master
2020-12-28T14:49:41.410708
2019-05-19T10:13:32
2019-05-19T10:13:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,029
py
# -*- coding: UTF-8 -*- import DataOutput import UrlManager import HtmlDownloader import HtmlParser class SpiderMan: def __init__(self): self.manager=UrlManager.UrlManager() self.downloader=HtmlDownloader.HtmlDownloader() self.parser=HtmlParser.HtmlParser() self.output=DataOutput.DataOutput() def crawl(self, root_url): self.manager.add_new_url(root_url) while(self.manager.has_new_url() and self.manager.old_urls_size()<100): try: url = self.manager.get_new_url() html = self.downloader.download(url) new_urls, new_datas = self.parser.parser(url, html) self.manager.add_new_urls(new_urls) self.output.store_data(new_datas) except Exception as e: print ("crawl failed") self.output.output_html() if __name__=="__main__": spider_man=SpiderMan() spider_man.crawl("https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB")
[ "liguangpei1@163.com" ]
liguangpei1@163.com
b477b6935dc4429c088f96e141aecd0facda38c5
ffd14a5749fae8dbf6f284bf54d026fb9f3a79dd
/leetcode/problem407/problem407.py
4f2cf2355186fac460a5149068b2c11555ddbf38
[]
no_license
speciallan/algorithm
2dc307b4bcc4ac0adda97a24059346028f71f412
306927b65320af9f3177d28a6367ea65ea9044d5
refs/heads/master
2020-04-15T21:55:39.874010
2019-07-22T14:05:38
2019-07-22T14:05:38
165,052,274
1
0
null
null
null
null
UTF-8
Python
false
false
1,232
py
def spe(*vars): for var in vars: print(var) exit() class Solution: def trapRainWater(self, heightMap): """ :type heightMap: List[List[int]] :rtype: int """ h, w = len(heightMap), len(heightMap[0]) i, j = 1, 1 while 1 <= i and i <= h-2: while 1 <= j and j <= w-2: self.allAroundAreHigher(heightMap, i, j) def allAroundAreHigher(self, heightMap, i, j): around = [] DIRECTION = [(0, 1), (0, -1), (1, 0), (-1, 0)] # 是否下降 for k in range(len(DIRECTION)): around_h = heightMap[i+DIRECTION[k][0]][j+DIRECTION[k][0]] # 比自己大的加入around数组 if around_h > heightMap[i][j]: around.append(around_h) # 比自己小的往下搜索,继续寻找边界around else: water_line = min(around) print('水位线:', water_line) if __name__ == "__main__": heightMap = [[1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1]] solution = Solution() result = solution.trapRainWater(heightMap) print(result)
[ "350394776@qq.com" ]
350394776@qq.com
55be60bcef1440bdbe2a556d4d6040d48a722fc2
9124e66c8ec04e61537473437a92b53daa32ce20
/linares/app7.py
96108d4cda6858d3f7e424b32b73af8cc2e1953d
[]
no_license
erick1984linares/t10_linares_rojas
28618baccb3472fb8d48b34f5d1107b702c399d0
ba9462b3b881dbd3665907a7a33c4c7d80aa4251
refs/heads/master
2020-12-04T06:38:06.929626
2020-01-10T11:52:29
2020-01-10T11:52:29
231,661,040
0
0
null
null
null
null
UTF-8
Python
false
false
808
py
import libreria def agregartrabajo(): trabajo=libreria.pedir_trabajo("ingrese trabajo:") sueldo=libreria.pedir_numero("ingrese sueldo :", 1500, 4000) contenido=trabajo + "-" + str(sueldo) + "\n" libreria.guardar_datos("info.txt", contenido, "a") print("Datos guardados") def verDatos(): datos = libreria.obtener_datos("info.txt") if ( datos != ""): print(datos) else: print("Archivo sin datos") opc=0 max=3 while(opc != max): print("######## MENU #######") print("1. Agregar trabajo ") print("2. ver Datos") print("3. Salir") print("#####################") opc=libreria.pedir_numero("Ingresar Opcion:", 1, 3) if (opc == 1): agregartrabajo() if (opc == 2): verDatos() #fin_menu print("Fin del programa")
[ "ylinares@unprg.edu.pe" ]
ylinares@unprg.edu.pe
c46b00db0d82519840cf3e18ea0069b174f42ca1
78f3fe4a148c86ce9b80411a3433a49ccfdc02dd
/2017/01/climate-anomaly-20170118/graphic_config.py
239d3e7a57c82ad7aae3803427073bcdc9ec9e73
[]
no_license
nprapps/graphics-archive
54cfc4d4d670aca4d71839d70f23a8bf645c692f
fe92cd061730496cb95c9df8fa624505c3b291f8
refs/heads/master
2023-03-04T11:35:36.413216
2023-02-26T23:26:48
2023-02-26T23:26:48
22,472,848
16
7
null
null
null
null
UTF-8
Python
false
false
305
py
#!/usr/bin/env python import base_filters COPY_GOOGLE_DOC_KEY = '1Cnn0p5LpuF8chCzjUOVQcIO5NBvBpIoLLeDpbBMLP6M' USE_ASSETS = False # Use these variables to override the default cache timeouts for this graphic # DEFAULT_MAX_AGE = 20 # ASSETS_MAX_AGE = 300 JINJA_FILTER_FUNCTIONS = base_filters.FILTERS
[ "ahurt@npr.org" ]
ahurt@npr.org
02fd6948ff472f910b32eda2c39cf98b58009ff4
8323f95ad0083bfe6da57b777a1af078a454bb04
/ssm/version.py
45b058b3d7179dad6109b590f93ac78881bb9e4d
[ "BSD-3-Clause" ]
permissive
sflis/SSM-analysis
600c867b68845850e7af54d02dc4dd344b9f1427
317db8b296fd189832b9344b0429ea6016e35999
refs/heads/master
2020-04-19T10:19:28.810811
2020-01-23T15:41:36
2020-01-23T15:41:36
168,136,746
0
1
BSD-3-Clause
2019-09-27T09:00:48
2019-01-29T10:33:01
Python
UTF-8
Python
false
false
5,922
py
""" Get version identification from git. The update_release_version() function writes the current version to the VERSION file. This function should be called before packaging a release version. Use the get_version() function to get the version string, including the latest commit, from git. If git is not available the VERSION file will be read. Heres an example of such a version string: v0.2.0.post58+git57440dc This code was taken from here: https://github.com/cta-observatory/ctapipe/blob/master/ctapipe/version.py which in turn based it on: https://github.com/aebrahim/python-git-version Combining ideas from http://blogs.nopcode.org/brainstorm/2013/05/20/pragmatic-python-versioning-via-setuptools-and-git-tags/ and Python Versioneer https://github.com/warner/python-versioneer but being much more lightwheight """ from __future__ import print_function from subprocess import check_output, CalledProcessError from os import path, name, devnull, environ, listdir __all__ = ("get_version",) CURRENT_DIRECTORY = path.dirname(path.abspath(__file__)) VFILE = "_version_cache.py" VERSION_FILE = path.join(CURRENT_DIRECTORY, VFILE) GIT_COMMAND = "git" import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) if name == "nt": def find_git_on_windows(): """find the path to the git executable on windows""" # first see if git is in the path try: check_output(["where", "/Q", "git"]) # if this command succeeded, git is in the path return "git" # catch the exception thrown if git was not found except CalledProcessError: pass # There are several locations git.exe may be hiding possible_locations = [] # look in program files for msysgit if "PROGRAMFILES(X86)" in environ: possible_locations.append( "%s/Git/cmd/git.exe" % environ["PROGRAMFILES(X86)"] ) if "PROGRAMFILES" in environ: possible_locations.append("%s/Git/cmd/git.exe" % environ["PROGRAMFILES"]) # look for the github version of git if "LOCALAPPDATA" in environ: github_dir = "%s/GitHub" % environ["LOCALAPPDATA"] if path.isdir(github_dir): for subdir in listdir(github_dir): if not subdir.startswith("PortableGit"): continue possible_locations.append( "%s/%s/bin/git.exe" % (github_dir, subdir) ) for possible_location in possible_locations: if path.isfile(possible_location): return possible_location # git was not found return "git" GIT_COMMAND = find_git_on_windows() def get_git_describe_version(abbrev=7): """return the string output of git desribe""" try: with open(devnull, "w") as fnull: arguments = [GIT_COMMAND, "describe", "--tags", "--abbrev=%d" % abbrev] return ( check_output(arguments, cwd=CURRENT_DIRECTORY, stderr=fnull) .decode("ascii") .strip() ) except (OSError, CalledProcessError): return None def format_git_describe(git_str, pep440=False): """format the result of calling 'git describe' as a python version""" if "-" not in git_str: # currently at a tag formatted_str = git_str else: # formatted as version-N-githash # want to convert to version.postN-githash git_str = git_str.replace("-", ".post", 1) if pep440: # does not allow git hash afterwards formatted_str = git_str.split("-")[0] else: formatted_str = git_str.replace("-g", "+git") # need to remove the "v" to have a proper python version if formatted_str.startswith("v"): formatted_str = formatted_str[1:] return formatted_str def read_release_version(): """Read version information from VERSION file""" try: from ._version_cache import version if len(version) == 0: version = None return version except ImportError: return "unknown" def update_release_version(fpath, pep440=False): """Release versions are stored in a file called VERSION. This method updates the version stored in the file. This function should be called when creating new releases. It is called by setup.py when building a package. pep440: bool When True, this function returns a version string suitable for a release as defined by PEP 440. When False, the githash (if available) will be appended to the version string. """ version = get_version(pep440=pep440) with open(path.join(fpath, VFILE), "w") as outfile: outfile.write("version={}".format(version)) outfile.write("\n") def get_version(pep440=False): """Tracks the version number. pep440: bool When True, this function returns a version string suitable for a release as defined by PEP 440. When False, the githash (if available) will be appended to the version string. The file VERSION holds the version information. If this is not a git repository, then it is reasonable to assume that the version is not being incremented and the version returned will be the release version as read from the file. However, if the script is located within an active git repository, git-describe is used to get the version information. The file VERSION will need to be changed manually. """ raw_git_version = get_git_describe_version() if not raw_git_version: # not a git repository return read_release_version() git_version = format_git_describe(raw_git_version, pep440=pep440) return git_version if __name__ == "__main__": print(get_version())
[ "samuel.d.flis@gmail.com" ]
samuel.d.flis@gmail.com
ee8830814c25c7b4ace1b95ca6d4dcb8eb422d37
43e303f0a00f7854b9405bb2a2a9ecbad18ae0fa
/venv/lib/python3.7/site-packages/py2app/recipes/sip.py
0ab3cb8cbfafc9cbed42e2d549ba3adca0b3d981
[ "MIT" ]
permissive
ykhade/Advent_Of_Code_2019
f64005c6e8872c17468f00eac2b247b6fa77c7f5
375ab43104712c5e1c782e5ea5f04073b5f8916c
refs/heads/master
2023-02-26T03:43:47.668384
2022-06-21T03:31:22
2022-06-21T03:31:22
224,943,590
1
1
MIT
2023-02-08T00:45:15
2019-11-30T01:27:48
Python
UTF-8
Python
false
false
4,408
py
""" Py2app support for project using sip, which basicly means PyQt and wrappers for other Qt-based libraries. This will include all C modules that might be used when you import a package using sip because we have no way to fine-tune this. The problem with SIP is that all inter-module depedencies (for example from PyQt4.Qt to PyQt4.QtCore) are handled in C code and therefore cannot be detected by the python code in py2app). """ import sys import glob import os import pkg_resources class Sip(object): def __init__(self): self.packages = None self.plugin_dir = None def config(self): if self.packages is not None: return self.packages import sipconfig, os try: set except NameError: from sets import Set as set ##old version for PyQt/Qt 3 # cfg = sipconfig.Configuration() # qtdir = cfg.qt_lib_dir ##new version for PyQt 4 from PyQt4 import pyqtconfig cfg = pyqtconfig.Configuration() qtdir = cfg.qt_lib_dir if not os.path.exists(qtdir): # half-broken installation? ignore. raise ImportError # Qt is GHETTO! dyld_library_path = os.environ.get('DYLD_LIBRARY_PATH', '').split(':') if qtdir not in dyld_library_path: dyld_library_path.insert(0, qtdir) os.environ['DYLD_LIBRARY_PATH'] = ':'.join(dyld_library_path) sipdir = os.path.dirname(cfg.pyqt_mod_dir) self.packages = set() self.plugin_dir = os.path.join(cfg.qt_dir, 'plugins') for fn in os.listdir(sipdir): fullpath = os.path.join(sipdir, fn) if os.path.isdir(fullpath): self.packages.add(fn) if fn == 'PyQt4': # PyQt4 has a nested structure, also import # subpackage to ensure everything get seen. for sub in os.listdir(fullpath): if ".py" not in sub: self.packages.add('%s.%s'%(fn, sub.replace(".so",""))) # Causes a python3-related syntax error (metaclass keyword), # and you probably don't need it: #if "PyQt4.uic" in self.packages and sys.version_info.major != 3: # print("WARNING: PyQt uic module found.") # print("avoid python3 metaclass syntax errors by adding 'PyQt4.uic' to your excludes option.") return self.packages def check(self, cmd, mf): try: packages = self.config() except ImportError: return dict() if 'PyQt4.uic' in packages: # PyQt4.uic contains subpackages with python 2 and python 3 # support. Exclude the variant that won't be ussed, this avoids # compilation errors on Python 2 (because some of the Python 3 # code is not valid Python 2 code) if sys.version_info[0] == 2: ref = 'PyQt4.uic.port_v3' else: ref = 'PyQt4.uic.port_v2' # Exclude... mf.lazynodes[ref] = None for pkg in packages: m = mf.findNode(pkg) if m is not None and m.filename is not None: break else: return None mf.import_hook('sip', m) m = mf.findNode('sip') # naive inclusion of ALL sip packages # stupid C modules.. hate hate hate for pkg in packages: try: mf.import_hook(pkg, m) except ImportError as exc: print("WARNING: ImportError in sip recipe ignored: %s"%(exc,)) if mf.findNode('PyQt4') is not None: resources = [pkg_resources.resource_filename('py2app', 'recipes/qt.conf')] for item in cmd.qt_plugins: if '/' not in item: item = item + '/*' if '*' in item: for path in glob.glob(os.path.join(self.plugin_dir, item)): resources.append((os.path.dirname('qt_plugins' + path[len(self.plugin_dir):]), [path])) else: resources.append((os.path.dirname(os.path.join('qt_plugins', item)), os.path.join(self.plugin_dir, item))) return dict(resources=resources) return dict() check = Sip().check
[ "ykhade@nevada.unr.edu" ]
ykhade@nevada.unr.edu
09691989e4f1280519fda2aeb11c1288c5554678
4d89652acca24e0bc653e0b4cb5846ceb5b568e4
/google-cloud-sdk/lib/surface/labelmanager/keys/create.py
84f9e6cb8034b58c702180d29b613d537fa4faec
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
ibssasimon/LyricLingo
410fcec94d2bd3ea75c975c55713f5b8fb913229
0dfc951b270912470b36ce0083afd9d4fe41b10a
refs/heads/master
2021-06-25T10:00:18.215900
2020-01-09T00:35:46
2020-01-09T00:35:46
222,135,399
2
1
null
2021-04-30T20:54:14
2019-11-16T17:32:19
Python
UTF-8
Python
false
false
2,418
py
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. 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. """Create command for the Label Manager - Label Keys CLI.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.labelmanager import service as labelmanager from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.labelmanager import arguments from googlecloudsdk.command_lib.labelmanager import operations @base.Hidden @base.ReleaseTracks(base.ReleaseTrack.ALPHA) class Create(base.Command): r"""Creates a label key resource under the specified label parent. ## EXAMPLES To create a label key with the name env under an organization run: $ gcloud alpha labelmanager keys create env \ --label_parent='organizations/123' --description='description' """ @staticmethod def Args(parser): group = parser.add_argument_group('LabelKey.', required=True) arguments.AddLabelParentArgToParser(group, required=True) arguments.AddDisplayNameArgToParser(group) arguments.AddDescriptionArgToParser(parser) arguments.AddAsyncArgToParser(parser) def Run(self, args): labelkeys_service = labelmanager.LabelKeysService() labelmanager_messages = labelmanager.LabelManagerMessages() display_name = args.DISPLAY_NAME label_parent = args.label_parent description = args.description create_request = labelmanager_messages.LabelKey( displayName=display_name, parent=label_parent, description=description) op = labelkeys_service.Create(create_request) if args.async_: return op else: done_op = operations.WaitForOperation( op, 'Waiting for label [{}] to be created with [{}]'.format( display_name, op.name), service=labelkeys_service) return done_op
[ "ibssasimon@gmail.com" ]
ibssasimon@gmail.com
fd6cdee2e8db28bf843350dbc736a90cb32aec8b
74698be74d244ebbabcb0b3cf17ebed26adfa37c
/official/vision/beta/tasks/semantic_segmentation.py
55d3900245809bad71e8a06126ee2937ff52809b
[ "Apache-2.0" ]
permissive
lfads/models
aa75616fee2476641aa98ca1cbdce7e5d27a9aff
fd700f0cb2e104544c445d9fbf3991d8388ff18a
refs/heads/master
2021-01-25T13:50:55.423010
2021-01-05T18:27:01
2021-01-05T18:27:01
123,619,512
16
9
Apache-2.0
2021-01-05T18:27:02
2018-03-02T19:07:50
Python
UTF-8
Python
false
false
9,364
py
# Lint as: python3 # Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Image segmentation task definition.""" from absl import logging import tensorflow as tf from official.core import base_task from official.core import input_reader from official.core import task_factory from official.vision.beta.configs import semantic_segmentation as exp_cfg from official.vision.beta.dataloaders import segmentation_input from official.vision.beta.evaluation import segmentation_metrics from official.vision.beta.losses import segmentation_losses from official.vision.beta.modeling import factory @task_factory.register_task_cls(exp_cfg.SemanticSegmentationTask) class SemanticSegmentationTask(base_task.Task): """A task for semantic segmentation.""" def build_model(self): """Builds segmentation model.""" input_specs = tf.keras.layers.InputSpec( shape=[None] + self.task_config.model.input_size) l2_weight_decay = self.task_config.losses.l2_weight_decay # Divide weight decay by 2.0 to match the implementation of tf.nn.l2_loss. # (https://www.tensorflow.org/api_docs/python/tf/keras/regularizers/l2) # (https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss) l2_regularizer = (tf.keras.regularizers.l2( l2_weight_decay / 2.0) if l2_weight_decay else None) model = factory.build_segmentation_model( input_specs=input_specs, model_config=self.task_config.model, l2_regularizer=l2_regularizer) return model def initialize(self, model: tf.keras.Model): """Loads pretrained checkpoint.""" if not self.task_config.init_checkpoint: return ckpt_dir_or_file = self.task_config.init_checkpoint if tf.io.gfile.isdir(ckpt_dir_or_file): ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file) # Restoring checkpoint. if 'all' in self.task_config.init_checkpoint_modules: ckpt = tf.train.Checkpoint(**model.checkpoint_items) status = ckpt.restore(ckpt_dir_or_file) status.assert_consumed() else: ckpt_items = {} if 'backbone' in self.task_config.init_checkpoint_modules: ckpt_items.update(backbone=model.backbone) if 'decoder' in self.task_config.init_checkpoint_modules: ckpt_items.update(decoder=model.decoder) ckpt = tf.train.Checkpoint(**ckpt_items) status = ckpt.restore(ckpt_dir_or_file) status.expect_partial().assert_existing_objects_matched() logging.info('Finished loading pretrained checkpoint from %s', ckpt_dir_or_file) def build_inputs(self, params, input_context=None): """Builds classification input.""" ignore_label = self.task_config.losses.ignore_label decoder = segmentation_input.Decoder() parser = segmentation_input.Parser( output_size=params.output_size, train_on_crops=params.train_on_crops, ignore_label=ignore_label, resize_eval_groundtruth=params.resize_eval_groundtruth, groundtruth_padded_size=params.groundtruth_padded_size, aug_scale_min=params.aug_scale_min, aug_scale_max=params.aug_scale_max, aug_rand_hflip=params.aug_rand_hflip, dtype=params.dtype) reader = input_reader.InputReader( params, dataset_fn=tf.data.TFRecordDataset, decoder_fn=decoder.decode, parser_fn=parser.parse_fn(params.is_training)) dataset = reader.read(input_context=input_context) return dataset def build_losses(self, labels, model_outputs, aux_losses=None): """Segmentation loss. Args: labels: labels. model_outputs: Output logits of the classifier. aux_losses: auxiliarly loss tensors, i.e. `losses` in keras.Model. Returns: The total loss tensor. """ loss_params = self._task_config.losses segmentation_loss_fn = segmentation_losses.SegmentationLoss( loss_params.label_smoothing, loss_params.class_weights, loss_params.ignore_label, use_groundtruth_dimension=loss_params.use_groundtruth_dimension, top_k_percent_pixels=loss_params.top_k_percent_pixels) total_loss = segmentation_loss_fn(model_outputs, labels['masks']) if aux_losses: total_loss += tf.add_n(aux_losses) return total_loss def build_metrics(self, training=True): """Gets streaming metrics for training/validation.""" metrics = [] if training: metrics.append(segmentation_metrics.MeanIoU( name='mean_iou', num_classes=self.task_config.model.num_classes, rescale_predictions=False, dtype=tf.float32)) else: self.miou_metric = segmentation_metrics.MeanIoU( name='val_mean_iou', num_classes=self.task_config.model.num_classes, rescale_predictions=not self.task_config.validation_data .resize_eval_groundtruth, dtype=tf.float32) return metrics def train_step(self, inputs, model, optimizer, metrics=None): """Does forward and backward. Args: inputs: a dictionary of input tensors. model: the model, forward pass definition. optimizer: the optimizer for this training step. metrics: a nested structure of metrics objects. Returns: A dictionary of logs. """ features, labels = inputs input_partition_dims = self.task_config.train_input_partition_dims if input_partition_dims: strategy = tf.distribute.get_strategy() features = strategy.experimental_split_to_logical_devices( features, input_partition_dims) num_replicas = tf.distribute.get_strategy().num_replicas_in_sync with tf.GradientTape() as tape: outputs = model(features, training=True) # Casting output layer as float32 is necessary when mixed_precision is # mixed_float16 or mixed_bfloat16 to ensure output is casted as float32. outputs = tf.nest.map_structure( lambda x: tf.cast(x, tf.float32), outputs) # Computes per-replica loss. loss = self.build_losses( model_outputs=outputs, labels=labels, aux_losses=model.losses) # Scales loss as the default gradients allreduce performs sum inside the # optimizer. scaled_loss = loss / num_replicas # For mixed_precision policy, when LossScaleOptimizer is used, loss is # scaled for numerical stability. if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer): scaled_loss = optimizer.get_scaled_loss(scaled_loss) tvars = model.trainable_variables grads = tape.gradient(scaled_loss, tvars) # Scales back gradient before apply_gradients when LossScaleOptimizer is # used. if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer): grads = optimizer.get_unscaled_gradients(grads) optimizer.apply_gradients(list(zip(grads, tvars))) logs = {self.loss: loss} if metrics: self.process_metrics(metrics, labels, outputs) logs.update({m.name: m.result() for m in metrics}) return logs def validation_step(self, inputs, model, metrics=None): """Validatation step. Args: inputs: a dictionary of input tensors. model: the keras.Model. metrics: a nested structure of metrics objects. Returns: A dictionary of logs. """ features, labels = inputs input_partition_dims = self.task_config.eval_input_partition_dims if input_partition_dims: strategy = tf.distribute.get_strategy() features = strategy.experimental_split_to_logical_devices( features, input_partition_dims) outputs = self.inference_step(features, model) outputs = tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), outputs) if self.task_config.validation_data.resize_eval_groundtruth: loss = self.build_losses(model_outputs=outputs, labels=labels, aux_losses=model.losses) else: loss = 0 logs = {self.loss: loss} logs.update({self.miou_metric.name: (labels, outputs)}) if metrics: self.process_metrics(metrics, labels, outputs) logs.update({m.name: m.result() for m in metrics}) return logs def inference_step(self, inputs, model): """Performs the forward step.""" return model(inputs, training=False) def aggregate_logs(self, state=None, step_outputs=None): if state is None: self.miou_metric.reset_states() state = self.miou_metric self.miou_metric.update_state(step_outputs[self.miou_metric.name][0], step_outputs[self.miou_metric.name][1]) return state def reduce_aggregated_logs(self, aggregated_logs): return {self.miou_metric.name: self.miou_metric.result().numpy()}
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
3bcd9aaedf53c7af0773cdd3d311d0726810e8d5
238e46a903cf7fac4f83fa8681094bf3c417d22d
/VTK/vtk_7.1.1_x64_Release/lib/python2.7/site-packages/twisted/runner/topfiles/setup.py
a518a5d15ca8bcb5df74efde6fc8793442fb2a1f
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "BSD-3-Clause" ]
permissive
baojunli/FastCAE
da1277f90e584084d461590a3699b941d8c4030b
a3f99f6402da564df87fcef30674ce5f44379962
refs/heads/master
2023-02-25T20:25:31.815729
2021-02-01T03:17:33
2021-02-01T03:17:33
268,390,180
1
0
BSD-3-Clause
2020-06-01T00:39:31
2020-06-01T00:39:31
null
UTF-8
Python
false
false
1,327
py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. try: from twisted.python.dist import setup, ConditionalExtension as Extension except ImportError: raise SystemExit("twisted.python.dist module not found. Make sure you " "have installed the Twisted core package before " "attempting to install any other Twisted projects.") extensions = [ Extension("twisted.runner.portmap", ["twisted/runner/portmap.c"], condition=lambda builder: builder._check_header("rpc/rpc.h")), ] if __name__ == '__main__': setup( twisted_subproject="runner", # metadata name="Twisted Runner", description="Twisted Runner is a process management library and inetd " "replacement.", author="Twisted Matrix Laboratories", author_email="twisted-python@twistedmatrix.com", maintainer="Andrew Bennetts", url="http://twistedmatrix.com/trac/wiki/TwistedRunner", license="MIT", long_description="""\ Twisted Runner contains code useful for persistent process management with Python and Twisted, and has an almost full replacement for inetd. """, # build stuff conditionalExtensions=extensions, )
[ "l”ibaojunqd@foxmail.com“" ]
l”ibaojunqd@foxmail.com“
4cecb71e22c01f0e61c998a992a6d5fcbfbc0541
eed7b5aa4861086d34e539e7bbfeff4286506692
/src/Game/Results/game_results.py
5ff645ba5e36aadc25cb7288b60a7dc942190796
[]
no_license
dfwarden/DeckBuilding
0be2ccb68fc9a69c8eaa1d8acedeaa7cebef1a31
0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258
refs/heads/master
2021-01-18T09:52:51.880892
2015-02-03T03:21:17
2015-02-03T03:21:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
617
py
class GameResults: """ Represents the results for a game """ def __init__(self, players, game, defaultResultsClass): """ Initialize the Game Results with the results for each player """ self.playerToResultClass = {player:defaultResultsClass for player in players} self.game = game self.playerResults = [] self.update = self.playerToResultClass.update def createPlayerResults(self): self.playerResults = [self.playerToResultClass[player](player, self.game) for player in self.playerToResultClass] self.playerResults.sort()
[ "cloew123@gmail.com" ]
cloew123@gmail.com
461d99183fb1f0ac514de76d2367582ad8224ac6
d2332b8695d27cba4062af1f292067fcb1114e9d
/manage.py
2766ce668123df33323d0c120768f36d18387568
[]
no_license
srksuman/Comment-system-in-Django
611c7986b3bb3cfd0f744fcfab6876b230184dd4
ede8a75d309160a08f26e8bcd0068300cc5d417e
refs/heads/master
2023-06-29T03:01:45.288770
2021-08-07T15:13:31
2021-08-07T15:13:31
393,669,407
13
0
null
null
null
null
UTF-8
Python
false
false
660
py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'post.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
[ "sumanrajkhanal@gmail.com" ]
sumanrajkhanal@gmail.com
8919747792cd04daf9b547144dc5d7dc485fc54d
44064ed79f173ddca96174913910c1610992b7cb
/Second_Processing_app/temboo/Library/Facebook/Actions/Video/WantsToWatch/ReadWantsToWatch.py
13506f3389f7e11ebe6dd0d0b9c0afde812792c2
[]
no_license
dattasaurabh82/Final_thesis
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
8edaea62f5987db026adfffb6b52b59b119f6375
refs/heads/master
2021-01-20T22:25:48.999100
2014-10-14T18:58:00
2014-10-14T18:58:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,656
py
# -*- coding: utf-8 -*- ############################################################################### # # ReadWantsToWatch # Retrieves one or more video wants_to_watch actions. # # Python version 2.6 # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class ReadWantsToWatch(Choreography): def __init__(self, temboo_session): """ Create a new instance of the ReadWantsToWatch Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ Choreography.__init__(self, temboo_session, '/Library/Facebook/Actions/Video/WantsToWatch/ReadWantsToWatch') def new_input_set(self): return ReadWantsToWatchInputSet() def _make_result_set(self, result, path): return ReadWantsToWatchResultSet(result, path) def _make_execution(self, session, exec_id, path): return ReadWantsToWatchChoreographyExecution(session, exec_id, path) class ReadWantsToWatchInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the ReadWantsToWatch Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved from the final step of the OAuth process.) """ InputSet._set_input(self, 'AccessToken', value) def set_ActionID(self, value): """ Set the value of the ActionID input for this Choreo. ((optional, string) The id of an action to retrieve. If an id is not provided, a list of all video wants_to_watch actions will be returned.) """ InputSet._set_input(self, 'ActionID', value) def set_Fields(self, value): """ Set the value of the Fields input for this Choreo. ((optional, string) A comma separated list of fields to return (i.e. id,name).) """ InputSet._set_input(self, 'Fields', value) def set_Limit(self, value): """ Set the value of the Limit input for this Choreo. ((optional, integer) Used to page through results. Limits the number of records returned in the response.) """ InputSet._set_input(self, 'Limit', value) def set_Offset(self, value): """ Set the value of the Offset input for this Choreo. ((optional, integer) Used to page through results. Returns results starting from the specified number.) """ InputSet._set_input(self, 'Offset', value) def set_ProfileID(self, value): """ Set the value of the ProfileID input for this Choreo. ((optional, string) The id of the user's profile. Defaults to "me" indicating the authenticated user.) """ InputSet._set_input(self, 'ProfileID', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.) """ InputSet._set_input(self, 'ResponseFormat', value) class ReadWantsToWatchResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the ReadWantsToWatch Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_HasPrevious(self): """ Retrieve the value for the "HasPrevious" output from this Choreo execution. ((boolean) A boolean flag indicating that a previous page exists.) """ return self._output.get('HasPrevious', None) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Facebook. Corresponds to the ResponseFormat input. Defaults to JSON.) """ return self._output.get('Response', None) def get_HasNext(self): """ Retrieve the value for the "HasNext" output from this Choreo execution. ((boolean) A boolean flag indicating that a next page exists.) """ return self._output.get('HasNext', None) class ReadWantsToWatchChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return ReadWantsToWatchResultSet(response, path)
[ "dattasaurabh82@gmail.com" ]
dattasaurabh82@gmail.com
8ff9c5273da808a4fbe65a14c5947b860c7a317b
6d8a7664b25fbe9c24ca972d310c5934d0d991e8
/FUNÇÃO Largua X Altura = Area.py
787def50df0dea807f540501b89e09db16fbadb4
[]
no_license
LeoGraciano/python
c6d24f438c3735fd97d1e71ea7bfd53d16fc2205
bf447bb42a5fab399a8cae5a5d2f5785f9ed0ebf
refs/heads/master
2022-12-22T11:48:11.757387
2020-09-29T03:24:11
2020-09-29T03:24:11
287,509,893
0
0
null
null
null
null
UTF-8
Python
false
false
236
py
def area(A, B): p = A*B print(f"A área de um terreno de {A}x{B} é de {p}m².") print(f"{'CONTROLE DE TERRENO':^5}") print("-"*30) a = eval(input(" Qual Altura (m): ")) l = eval(input(" Qual Largura (m): ")) area(a, l)
[ "leonardof.graciano@gmail.com" ]
leonardof.graciano@gmail.com
ddf498c24b175949c03e84b4d71872d9fec3d4b6
caa72788fdae6b05c5ce4c132b45fc00d55bb607
/47Tkinter/选择框/5-CheckButton实现选择.py
a71d9f0175c111c1a8aef35537f25a8e81fa7e71
[]
no_license
DamonZCR/PythonStu
dcc2ba49195f5859fd63227fe0f8f78b36ed46df
88fec97e3bccff47ba1c5f521f53a69af6ca2b2d
refs/heads/master
2023-07-05T06:29:53.300920
2021-08-13T12:22:30
2021-08-13T12:22:30
302,256,563
1
0
null
null
null
null
UTF-8
Python
false
false
174
py
from tkinter import * root = Tk() v = IntVar() c = Checkbutton(root, text='测试选中', variable=v) c.pack() l = Label(root, textvariable=v) l.pack(anchor='se') mainloop()
[ "137593938@qq.com" ]
137593938@qq.com
e1aa900a4966a021ea32f0c408e6224675a37033
b3c4edfb5c526768fbe4b46b9ea9805d084c7735
/PyQt561、62、63、64/Ui__mainUI.py
4033ff2f85bf19035d4b6df2ef6590d7964c3b73
[]
no_license
mach8686devops/pyqt5-demo
c7ed79310372c38e232c94694670f7b9b33ed7f8
44072d6ffc8919715bc2da3cf35c6ce88b2e7208
refs/heads/main
2023-04-16T16:50:32.962316
2021-04-29T17:06:47
2021-04-29T17:06:47
362,890,284
0
0
null
null
null
null
UTF-8
Python
false
false
12,457
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'F:\PyQt5\source_code_for_pyqt5_tutorials\PyQt561\_mainUI.ui' # # Created by: PyQt5 UI code generator 5.11.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1256, 570) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("res/logo.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) self.centralWidget = QtWidgets.QWidget(MainWindow) self.centralWidget.setObjectName("centralWidget") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.centralWidget) self.verticalLayout_5.setObjectName("verticalLayout_5") self.splitter = QtWidgets.QSplitter(self.centralWidget) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setOpaqueResize(False) self.splitter.setChildrenCollapsible(False) self.splitter.setObjectName("splitter") self.layoutWidget = QtWidgets.QWidget(self.splitter) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.horizontalLayout_12 = QtWidgets.QHBoxLayout() self.horizontalLayout_12.setObjectName("horizontalLayout_12") self.horizontalLayout_11 = QtWidgets.QHBoxLayout() self.horizontalLayout_11.setSpacing(0) self.horizontalLayout_11.setObjectName("horizontalLayout_11") self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget) self.lineEdit.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit.setClearButtonEnabled(True) self.lineEdit.setObjectName("lineEdit") self.horizontalLayout_11.addWidget(self.lineEdit) self.comboBox = QtWidgets.QComboBox(self.layoutWidget) self.comboBox.setFocusPolicy(QtCore.Qt.ClickFocus) self.comboBox.setObjectName("comboBox") self.horizontalLayout_11.addWidget(self.comboBox) self.horizontalLayout_12.addLayout(self.horizontalLayout_11) self.pushButton_search = QtWidgets.QPushButton(self.layoutWidget) self.pushButton_search.setObjectName("pushButton_search") self.horizontalLayout_12.addWidget(self.pushButton_search) self.verticalLayout_3.addLayout(self.horizontalLayout_12) self.tableView = QtWidgets.QTableView(self.layoutWidget) self.tableView.setObjectName("tableView") self.verticalLayout_3.addWidget(self.tableView) self.layoutWidget1 = QtWidgets.QWidget(self.splitter) self.layoutWidget1.setObjectName("layoutWidget1") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.layoutWidget1) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.verticalLayout_4.setObjectName("verticalLayout_4") self.groupBox = QtWidgets.QGroupBox(self.layoutWidget1) self.groupBox.setObjectName("groupBox") self.horizontalLayout_13 = QtWidgets.QHBoxLayout(self.groupBox) self.horizontalLayout_13.setObjectName("horizontalLayout_13") self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem) self.label = QtWidgets.QLabel(self.groupBox) self.label.setText("") self.label.setPixmap(QtGui.QPixmap("res/book.png")) self.label.setScaledContents(True) self.label.setObjectName("label") self.verticalLayout_2.addWidget(self.label) spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem1) self.horizontalLayout_13.addLayout(self.verticalLayout_2) self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout_9 = QtWidgets.QHBoxLayout() self.horizontalLayout_9.setObjectName("horizontalLayout_9") self.label_5 = QtWidgets.QLabel(self.groupBox) self.label_5.setObjectName("label_5") self.horizontalLayout_9.addWidget(self.label_5) self.label_country = QtWidgets.QLabel(self.groupBox) self.label_country.setText("") self.label_country.setObjectName("label_country") self.horizontalLayout_9.addWidget(self.label_country) self.verticalLayout.addLayout(self.horizontalLayout_9) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label_2 = QtWidgets.QLabel(self.groupBox) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.label_isbn = QtWidgets.QLabel(self.groupBox) self.label_isbn.setText("") self.label_isbn.setObjectName("label_isbn") self.horizontalLayout.addWidget(self.label_isbn) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label_15 = QtWidgets.QLabel(self.groupBox) self.label_15.setObjectName("label_15") self.horizontalLayout_2.addWidget(self.label_15) self.label_bookname = QtWidgets.QLabel(self.groupBox) self.label_bookname.setText("") self.label_bookname.setObjectName("label_bookname") self.horizontalLayout_2.addWidget(self.label_bookname) self.verticalLayout.addLayout(self.horizontalLayout_2) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_4 = QtWidgets.QLabel(self.groupBox) self.label_4.setObjectName("label_4") self.horizontalLayout_3.addWidget(self.label_4) self.label_author = QtWidgets.QLabel(self.groupBox) self.label_author.setText("") self.label_author.setObjectName("label_author") self.horizontalLayout_3.addWidget(self.label_author) self.verticalLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.label_3 = QtWidgets.QLabel(self.groupBox) self.label_3.setObjectName("label_3") self.horizontalLayout_4.addWidget(self.label_3) self.label_classification = QtWidgets.QLabel(self.groupBox) self.label_classification.setText("") self.label_classification.setObjectName("label_classification") self.horizontalLayout_4.addWidget(self.label_classification) self.verticalLayout.addLayout(self.horizontalLayout_4) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.label_6 = QtWidgets.QLabel(self.groupBox) self.label_6.setObjectName("label_6") self.horizontalLayout_5.addWidget(self.label_6) self.label_publisher = QtWidgets.QLabel(self.groupBox) self.label_publisher.setText("") self.label_publisher.setObjectName("label_publisher") self.horizontalLayout_5.addWidget(self.label_publisher) self.verticalLayout.addLayout(self.horizontalLayout_5) self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.label_10 = QtWidgets.QLabel(self.groupBox) self.label_10.setObjectName("label_10") self.horizontalLayout_6.addWidget(self.label_10) self.label_pages = QtWidgets.QLabel(self.groupBox) self.label_pages.setText("") self.label_pages.setObjectName("label_pages") self.horizontalLayout_6.addWidget(self.label_pages) self.verticalLayout.addLayout(self.horizontalLayout_6) self.horizontalLayout_7 = QtWidgets.QHBoxLayout() self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.label_8 = QtWidgets.QLabel(self.groupBox) self.label_8.setObjectName("label_8") self.horizontalLayout_7.addWidget(self.label_8) self.label_pubdate = QtWidgets.QLabel(self.groupBox) self.label_pubdate.setText("") self.label_pubdate.setObjectName("label_pubdate") self.horizontalLayout_7.addWidget(self.label_pubdate) self.verticalLayout.addLayout(self.horizontalLayout_7) self.horizontalLayout_8 = QtWidgets.QHBoxLayout() self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.label_12 = QtWidgets.QLabel(self.groupBox) self.label_12.setObjectName("label_12") self.horizontalLayout_8.addWidget(self.label_12) self.label_price = QtWidgets.QLabel(self.groupBox) self.label_price.setText("") self.label_price.setObjectName("label_price") self.horizontalLayout_8.addWidget(self.label_price) self.verticalLayout.addLayout(self.horizontalLayout_8) self.label_14 = QtWidgets.QLabel(self.groupBox) self.label_14.setObjectName("label_14") self.verticalLayout.addWidget(self.label_14) self.textBrowser = QtWidgets.QTextBrowser(self.groupBox) self.textBrowser.setObjectName("textBrowser") self.verticalLayout.addWidget(self.textBrowser) self.horizontalLayout_13.addLayout(self.verticalLayout) self.verticalLayout_4.addWidget(self.groupBox) self.horizontalLayout_10 = QtWidgets.QHBoxLayout() self.horizontalLayout_10.setObjectName("horizontalLayout_10") self.pushButton_createbook = QtWidgets.QPushButton(self.layoutWidget1) self.pushButton_createbook.setObjectName("pushButton_createbook") self.horizontalLayout_10.addWidget(self.pushButton_createbook) spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_10.addItem(spacerItem2) self.verticalLayout_4.addLayout(self.horizontalLayout_10) self.verticalLayout_5.addWidget(self.splitter) MainWindow.setCentralWidget(self.centralWidget) self.statusBar = QtWidgets.QStatusBar(MainWindow) self.statusBar.setObjectName("statusBar") MainWindow.setStatusBar(self.statusBar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "微信公众号:学点编程吧--极简图书管理Plus")) self.pushButton_search.setText(_translate("MainWindow", "搜索")) self.tableView.setStatusTip(_translate("MainWindow", "双击表格修改数据")) self.groupBox.setTitle(_translate("MainWindow", "更多图书信息")) self.label_5.setText(_translate("MainWindow", "国 家")) self.label_2.setText(_translate("MainWindow", "I S B N")) self.label_15.setText(_translate("MainWindow", "书 名")) self.label_4.setText(_translate("MainWindow", "作 者")) self.label_3.setText(_translate("MainWindow", "图书分类")) self.label_6.setText(_translate("MainWindow", "出版单位")) self.label_10.setText(_translate("MainWindow", "页 数")) self.label_8.setText(_translate("MainWindow", "出版年份")) self.label_12.setText(_translate("MainWindow", "定 价")) self.label_14.setText(_translate("MainWindow", "内容简介")) self.pushButton_createbook.setText(_translate("MainWindow", "新建图书档案...")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
[ "zhangjohn202@gmail.com" ]
zhangjohn202@gmail.com
2fa98fcda422f0478d9bb5fd56f27aca56ee3d68
d8734b5bb65e43dfd5c9af80ffbed7d87803517d
/HW_1/test_main_unittest.py
324b73eaff5bc17d302ea17823b16db0ccee910f
[]
no_license
DariaMikhailovna/technosphere
f012b59c20cd9455e874b09c0debbe4c1ccf3608
f755edee26a3c86b5325a0f90e544a04d138c6ab
refs/heads/main
2023-04-16T03:41:19.958214
2021-05-04T13:29:12
2021-05-04T13:29:12
348,362,972
0
0
null
null
null
null
UTF-8
Python
false
false
4,274
py
import unittest from HW_1.main import Board class BoardTestCase(unittest.TestCase): def setUp(self): board = Board() board.grid = [['0', '0', '0'], ['0', '0', '0'], ['0', '0', '0']] self.full_board = board self.empty_board = Board() self.set_for_insert = [ (1, 2, 'X'), (2, 2, '0'), (1, 1, 'X'), (0, 1, '0'), (2, 0, 'X'), ] self.set_for_column = [ ([['X', '.', '.'], ['X', '.', '.'], ['X', '.', 'X']], 'X', 0, True), ([['X', 'X', '.'], ['.', 'X', '.'], ['.', '0', '.']], 'X', 1, False), ([['0', '.', '.'], ['.', 'X', '.'], ['.', '.', '0']], '0', 2, False), ([['0', '.', '0'], ['.', '.', '0'], ['0', '.', '0']], '0', 2, True), ([['.', '0', '0'], ['.', '0', '.'], ['0', '0', '.']], 'X', 1, False), ] self.set_for_row = [ ([['X', '.', '.'], ['.', 'X', '.'], ['.', '.', 'X']], 'X', 0, False), ([['X', '.', '.'], ['0', 'X', '0'], ['.', '.', 'X']], '0', 1, False), ([['0', '.', '.'], ['.', 'X', '.'], ['0', '0', '0']], '0', 2, True), ([['0', '0', '0'], ['.', '.', '.'], ['0', '.', '.']], '0', 0, True), ([['X', 'X', 'X'], ['.', '0', '.'], ['0', '0', '0']], 'X', 2, False), ([['0', '.', 'X'], ['.', '0', '.'], ['0', '.', '.']], '0', 0, False), ] self.set_for_diagonal = [ ([['X', '.', '.'], ['.', 'X', '.'], ['.', '.', 'X']], 'X', True), ([['X', '.', '.'], ['.', 'X', '.'], ['.', '.', 'X']], '0', False), ([['0', '.', '.'], ['.', 'X', '.'], ['.', '.', '0']], '0', False), ([['.', '.', '0'], ['.', '0', '.'], ['0', '.', '.']], '0', True), ([['.', '.', '0'], ['.', '0', '.'], ['0', '.', '.']], 'X', False), ([['.', '.', 'X'], ['.', '0', '.'], ['0', '.', '.']], '0', False), ] def test_is_empty(self): for i in range(3): for j in range(3): self.assertTrue(self.empty_board.is_empty(i, j)) for i in range(3): for j in range(3): self.assertFalse(self.full_board.is_empty(i, j)) def test_insert(self): for i in range(len(self.set_for_insert)): self.assertEqual(self.empty_board.grid[self.set_for_insert[i][0]][self.set_for_insert[i][1]], '.') self.empty_board.insert(self.set_for_insert[i][0], self.set_for_insert[i][1], self.set_for_insert[i][2]) self.assertEqual(self.empty_board.grid[self.set_for_insert[i][0]][self.set_for_insert[i][1]], self.set_for_insert[i][2]) def test_is_full(self): self.assertFalse(self.empty_board.is_full()) self.assertTrue(self.full_board.is_full()) self.full_board.insert(0, 0, '.') self.assertFalse(self.full_board.is_full()) def test_check_column(self): for i in range(len(self.set_for_column)): self.empty_board.grid = self.set_for_column[i][0] self.assertEqual(self.empty_board.check_column(self.set_for_column[i][2], self.set_for_column[i][1]), self.set_for_column[i][3]) def test_check_row(self): for i in range(len(self.set_for_row)): self.empty_board.grid = self.set_for_row[i][0] self.assertEqual(self.empty_board.check_row(self.set_for_row[i][2], self.set_for_row[i][1]), self.set_for_row[i][3]) def test_check_diagonals(self): for i in range(len(self.set_for_row)): self.empty_board.grid = self.set_for_diagonal[i][0] self.assertEqual(self.empty_board.check_diagonals(self.set_for_diagonal[i][1]), self.set_for_diagonal[i][2])
[ "0610-1994@mail.ru" ]
0610-1994@mail.ru
ff2abfac46a5644809736691859dae9baa1bc63d
7a97d08146dad2120f8364e392c36d20c2487853
/python/k.py
c93422045eec60fc31fcb60d9c8e3a1c9bb69676
[]
no_license
livelikeabel/abel-algorithm
80adee03d45c6143b613fab0c9aa432084e07c62
8582e633aa316abb43fe070610f65d1a06dc07a9
refs/heads/master
2021-01-01T00:50:35.925100
2020-04-28T05:01:47
2020-04-28T05:01:47
239,104,846
1
0
null
null
null
null
UTF-8
Python
false
false
219
py
import sys sys.stdin = open("input.txt", "rt") n, k = map(int, input().split()) cnt = 0 for i in range(1, n + 1): if n % i == 0: cnt += 1 if cnt == k: print(i) break else: print(-1)
[ "esung1129@gmail.com" ]
esung1129@gmail.com
f0639033a33226b06bdee86293166e7906a87b4d
362224f8a23387e8b369b02a6ff8690c200a2bce
/django/django_extra/formFun/formApp/views.py
8094c9700194019cb9af4780cdab17cc2734dc1b
[]
no_license
Helenyixuanwang/python_stack
ac94c7c532655bf47592a8453738daac10f220ad
97fbc77e3971b5df1fe3e79652b294facf8d6cee
refs/heads/main
2023-06-11T02:17:27.277551
2021-06-21T17:01:09
2021-06-21T17:01:09
364,336,066
0
0
null
null
null
null
UTF-8
Python
false
false
535
py
from django.shortcuts import redirect, render from .forms import * from django.contrib.auth.forms import AuthenticationForm # Create your views here. def index(request): # myForm=RegisterForm() # context={ # "myform":myForm # } login_form = AuthenticationForm() context={'myform':login_form} return render(request, 'index.html',context) def register(request): print("Inside Register") bound_form = RegisterForm(request.POST) print(request.POST['first_name']) return redirect("/")
[ "wangyixuan@msn.com" ]
wangyixuan@msn.com
13ab09f1b696555138f142ef55a217ed3ef643a3
3cd4e2aae2a3ee3f9002fea903a6695f9fd5d373
/bigml/api_handlers/pcahandler.py
2166746021326663e5ebe0e0dc57d391a17c0012
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
jaykamau7/python
1c2daf7222f12909563005701b02308b8b80c732
faf718173e4a108ae8d500e82a6b4197fabbecb4
refs/heads/master
2023-02-28T13:29:59.759663
2021-02-07T14:10:20
2021-02-07T14:10:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,702
py
# -*- coding: utf-8 -*- # # Copyright 2018-2020 BigML # # 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. """Base class for PCA' REST calls https://bigml.com/api/pcas """ try: import simplejson as json except ImportError: import json from bigml.api_handlers.resourcehandler import ResourceHandlerMixin from bigml.api_handlers.resourcehandler import check_resource_type, \ resource_is_ready from bigml.constants import PCA_PATH class PCAHandlerMixin(ResourceHandlerMixin): """This class is used by the BigML class as a mixin that provides the REST calls models. It should not be instantiated independently. """ def __init__(self): """Initializes the PCAHandler. This class is intended to be used as a mixin on ResourceHandler, that inherits its attributes and basic method from BigMLConnection, and must not be instantiated independently. """ self.pca_url = self.url + PCA_PATH def create_pca(self, datasets, args=None, wait_time=3, retries=10): """Creates a PCA from a `dataset` of a list o `datasets`. """ create_args = self._set_create_from_datasets_args( datasets, args=args, wait_time=wait_time, retries=retries) body = json.dumps(create_args) return self._create(self.pca_url, body) def get_pca(self, pca, query_string='', shared_username=None, shared_api_key=None): """Retrieves a PCA. The model parameter should be a string containing the PCA id or the dict returned by create_pca. As a PCA is an evolving object that is processed until it reaches the FINISHED or FAULTY state, the function will return a dict that encloses the PCA values and state info available at the time it is called. If this is a shared PCA, the username and sharing api key must also be provided. """ check_resource_type(pca, PCA_PATH, message="A PCA id is needed.") return self.get_resource(pca, query_string=query_string, shared_username=shared_username, shared_api_key=shared_api_key) def pca_is_ready(self, pca, **kwargs): """Checks whether a pca's status is FINISHED. """ check_resource_type(pca, PCA_PATH, message="A PCA id is needed.") resource = self.get_pca(pca, **kwargs) return resource_is_ready(resource) def list_pcas(self, query_string=''): """Lists all your PCAs. """ return self._list(self.pca_url, query_string) def update_pca(self, pca, changes): """Updates a PCA. """ check_resource_type(pca, PCA_PATH, message="A PCA id is needed.") return self.update_resource(pca, changes) def delete_pca(self, pca): """Deletes a PCA. """ check_resource_type(pca, PCA_PATH, message="A PCA id is needed.") return self.delete_resource(pca)
[ "merce@bigml.com" ]
merce@bigml.com
4522ee6c5e468713cd2a8f56df01b575f0b21404
277f976227c7590f6de5e7991d8fbed23b6646fe
/euler/cleaned_solutions/p56.py
a55092ed385e8799552c3231d7e3455d59a91071
[]
no_license
domspad/euler
ca19aae72165eb4d08104ef7a2757115cfdb9a18
a4901403e442b376c2edd987a1571ab962dadab2
refs/heads/master
2021-01-17T14:04:39.198658
2016-07-25T23:40:10
2016-07-25T23:40:10
54,561,463
0
0
null
null
null
null
UTF-8
Python
false
false
240
py
# 2 mins # In [7]: time %run p56.py # 972 # CPU times: user 662 ms, sys: 12 ms, total: 674 ms # Wall time: 674 ms def digit_sum(n): return sum(int(d) for d in str(n)) print max(digit_sum(a**b) for a in xrange(100) for b in xrange(100))
[ "domspad@umich.edu" ]
domspad@umich.edu
69919a3651703f97d5f3cf9c1b16bf6160fd8d00
e9538b7ad6d0ce0ccfbb8e10c458f9e0b73926f6
/tests/unit/modules/network/fortimanager/test_fmgr_device_config.py
e0be3934096ea08f7a097be0ccf7fa36a1d9310f
[]
no_license
ansible-collection-migration/misc.not_a_real_collection
b3ef8090c59de9ac30aca083c746ec3595d7f5f5
7ab1af924a3db4ada2f714b09bb392614344cb1e
refs/heads/master
2020-12-18T13:48:51.849567
2020-01-22T17:39:18
2020-01-22T17:39:18
235,400,821
0
0
null
null
null
null
UTF-8
Python
false
false
7,313
py
# Copyright 2018 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json from ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortimanager.fortimanager import FortiManagerHandler import pytest try: from ansible_collections.misc.not_a_real_collection.plugins.modules import fmgr_device_config except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) def load_fixtures(): fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') + "/{filename}.json".format( filename=os.path.splitext(os.path.basename(__file__))[0]) try: with open(fixture_path, "r") as fixture_file: fixture_data = json.load(fixture_file) except IOError: return [] return [fixture_data] @pytest.fixture(autouse=True) def module_mock(mocker): connection_class_mock = mocker.patch('ansible.module_utils.basic.AnsibleModule') return connection_class_mock @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.modules.fmgr_device_config.Connection') return connection_class_mock @pytest.fixture(scope="function", params=load_fixtures()) def fixture_data(request): func_name = request.function.__name__.replace("test_", "") return request.param.get(func_name, None) fmg_instance = FortiManagerHandler(connection_mock, module_mock) def test_update_device_hostname(fixture_data, mocker): mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request', side_effect=fixture_data) # Fixture sets used:########################### ################################################## # adom: ansible # interface: None # device_unique_name: FGT1 # install_config: disable # device_hostname: ansible-fgt01 # interface_ip: None # interface_allow_access: None # mode: update ################################################## ################################################## # adom: ansible # interface: None # device_unique_name: FGT2 # install_config: disable # device_hostname: ansible-fgt02 # interface_ip: None # interface_allow_access: None # mode: update ################################################## ################################################## # adom: ansible # interface: None # device_unique_name: FGT3 # install_config: disable # device_hostname: ansible-fgt03 # interface_ip: None # interface_allow_access: None # mode: update ################################################## # Test using fixture 1 # output = fmgr_device_config.update_device_hostname(fmg_instance, fixture_data[0]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 2 # output = fmgr_device_config.update_device_hostname(fmg_instance, fixture_data[1]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 3 # output = fmgr_device_config.update_device_hostname(fmg_instance, fixture_data[2]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 def test_update_device_interface(fixture_data, mocker): mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request', side_effect=fixture_data) # Fixture sets used:########################### ################################################## # adom: ansible # install_config: disable # device_unique_name: FGT1 # interface: port2 # device_hostname: None # interface_ip: 10.1.1.1/24 # interface_allow_access: ping, telnet, https, http # mode: update ################################################## ################################################## # adom: ansible # install_config: disable # device_unique_name: FGT2 # interface: port2 # device_hostname: None # interface_ip: 10.1.2.1/24 # interface_allow_access: ping, telnet, https, http # mode: update ################################################## ################################################## # adom: ansible # install_config: disable # device_unique_name: FGT3 # interface: port2 # device_hostname: None # interface_ip: 10.1.3.1/24 # interface_allow_access: ping, telnet, https, http # mode: update ################################################## # Test using fixture 1 # output = fmgr_device_config.update_device_interface(fmg_instance, fixture_data[0]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 2 # output = fmgr_device_config.update_device_interface(fmg_instance, fixture_data[1]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 3 # output = fmgr_device_config.update_device_interface(fmg_instance, fixture_data[2]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 def test_exec_config(fixture_data, mocker): mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request', side_effect=fixture_data) # Fixture sets used:########################### ################################################## # adom: ansible # interface: None # device_unique_name: FGT1 # install_config: enable # device_hostname: None # interface_ip: None # interface_allow_access: None # mode: exec ################################################## ################################################## # adom: ansible # install_config: enable # device_unique_name: FGT2, FGT3 # interface: None # device_hostname: None # interface_ip: None # interface_allow_access: None # mode: exec ################################################## # Test using fixture 1 # output = fmgr_device_config.exec_config(fmg_instance, fixture_data[0]['paramgram_used']) assert isinstance(output['raw_response'], dict) is True # Test using fixture 2 # output = fmgr_device_config.exec_config(fmg_instance, fixture_data[1]['paramgram_used']) assert isinstance(output['raw_response'], dict) is True
[ "ansible_migration@example.com" ]
ansible_migration@example.com
52c627ca53565f30d86878726ff73d5d52a24d28
1fe8d4133981e53e88abf633046060b56fae883e
/venv/lib/python3.8/site-packages/tensorflow/python/autograph/converters/call_trees 2.py
0563589169aa076e608dbb30c6236cc9a05e18da
[]
no_license
Akira331/flask-cifar10
6c49db8485038731ce67d23f0972b9574746c7a7
283e7a2867c77d4b6aba7aea9013bf241d35d76c
refs/heads/master
2023-06-14T16:35:06.384755
2021-07-05T14:09:15
2021-07-05T14:09:15
382,864,970
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:9da573568f59bd33ef92c84d65c3c4bddedbcee5e4f54d70a2fc920ccd9bffeb size 7435
[ "business030301@gmail.com" ]
business030301@gmail.com
b85f62bda9d07d71763ee046dd7411731a9ea547
fd86752c58059da70f9ea56233a02d9b5bdae445
/src/tests/test_checks.py
705469a29f80b71d647b73bdba8dbcd4be95085a
[]
no_license
SUNET/scriptherder
4eab03f77df152148ccd565fb333145f85bebe73
ccb788212cf3471f1d38af316a1e6af6f7c41846
refs/heads/master
2023-06-16T00:08:12.984584
2023-03-01T10:12:57
2023-03-01T10:12:57
19,273,787
1
1
null
2015-09-30T11:16:07
2014-04-29T11:16:25
Python
UTF-8
Python
false
false
6,344
py
import sys import logging import unittest from scriptherder import Job, Check logging.basicConfig(level = logging.DEBUG, stream = sys.stderr, format = '%(asctime)s: %(threadName)s %(levelname)s %(message)s') logger = logging.getLogger('unittest') class TestChecks(unittest.TestCase): def _run(self, cmd, ok='', warn='', run=True, runtime_mode = True): check = Check(ok, warn, 'unit_testing', logger, runtime_mode=True) self.job = Job('unittest_job', cmd) if run: self.job.run() self.job.check(check, logger) # Call status summary for all the tests to make sure it works in all # possible states logger.debug('Job status summary: {}'.format(self.job.status_summary())) if not runtime_mode: logger.info('Unit test evaluating checks again, post-execution') check = Check(ok, warn, 'unit_testing', logger, runtime_mode=False) self.job.check(check, logger) logger.debug('Job status summary: {}'.format(self.job.status_summary())) def test_exit_status_ok(self): """ Test exit status matching OK criteria """ self._run(['/bin/echo', 'test'], ok = 'exit_status=0') self.assertTrue(self.job.is_ok()) def test_exit_status_warning(self): """ Test exit status matching WARN criteria """ self._run(['/bin/echo', 'test'], ok = 'exit_status=1', warn = 'exit_status=0') self.assertFalse(self.job.is_ok()) self.assertTrue(self.job.is_warning()) def test_exit_status_critical(self): """ Test exit status matching neither OK nor WARN criteria """ self._run(['/bin/true', 'test'], ok = 'exit_status=1', warn = 'exit_status=2') self.assertFalse(self.job.is_ok()) self.assertFalse(self.job.is_warning()) self.assertEqual(self.job.check_status, 'CRITICAL') def test_exit_status_negated1(self): """ Test exit status matching OK criteria (negated) """ self._run(['/bin/false'], ok = '!exit_status=0') self.assertTrue(self.job.is_ok()) self.assertFalse(self.job.is_warning()) def test_max_age(self): """ Test max_age criteria """ self._run(['/bin/echo', 'test'], ok = 'exit_status=0, max_age=10s', warn = 'exit_status=0, max_age=3h', runtime_mode = False) self.assertTrue(self.job.is_ok()) self.assertFalse(self.job.is_warning()) def test_max_age_negated(self): """ Test max_age criteria (negated) """ self._run(['/bin/echo', 'test'], ok = 'exit_status=0, !max_age=10s', warn = 'exit_status=0, max_age=3h', runtime_mode = False) self.assertFalse(self.job.is_ok()) self.assertTrue(self.job.is_warning()) def test_file_exists(self): """ Test file_exists criteria """ self._run(['/bin/echo', 'test'], ok = 'exit_status=1', warn = 'exit_status=1,OR_file_exists=/etc/services', runtime_mode = False) self.assertFalse(self.job.is_ok()) self.assertTrue(self.job.is_warning()) def test_file_exists_negated(self): """ Test file_exists criteria (negated) """ self._run(['/bin/false'], ok = 'exit_status=0,!OR_file_exists=/this_could_be_a_FAIL_file', runtime_mode = False) self.assertTrue(self.job.is_ok()) def test_file_exists_fail(self): """ Test file_exists criteria failure """ self._run(['/bin/false'], ok = 'exit_status=0,OR_file_exists=/this_file_should_not_exist', runtime_mode = False) self.assertFalse(self.job.is_ok()) self.assertEqual(self.job.check_status, 'CRITICAL') self.assertEqual(self.job.check_reason, 'file_does_not_exist=/this_file_should_not_exist, stored_status=OK==False') def test_OR_running(self): """ Test OR_running criteria """ self._run(['/bin/echo', 'test'], ok = 'exit_status=1,OR_running', warn = 'exit_status=0') self.assertTrue(self.job.is_ok()) self.assertFalse(self.job.is_warning()) def test_OR_running_negated(self): """ Test OR_running criteria """ self._run(['/bin/echo', 'test'], ok = 'exit_status=1,OR_running', warn = '!OR_running', run = False) self.assertFalse(self.job.is_ok()) self.assertTrue(self.job.is_warning()) def test_output_contains(self): """ Test output_contains criteria """ self._run(['/bin/echo', 'STATUS_TESTING_OK'], ok = 'exit_status=0,output_contains=TESTING') self.assertTrue(self.job.is_ok()) self.assertEqual(self.job.check_reason, 'exit=0, output_contains=TESTING==True') def test_output_contains_negated(self): """ Test output_contains criteria (negated) """ self._run(['/bin/echo', 'STATUS_TESTING_OK'], ok = 'exit_status=0,!output_contains=ERROR') self.assertTrue(self.job.is_ok()) self.assertEqual(self.job.check_reason, 'exit=0, !output_contains=ERROR==True') def test_obsolete_output_not_contains(self): """ Test obsolete option output_not_contains """ self._run(['/bin/echo', 'STATUS_TESTING_OK'], ok = 'exit_status=0,output_not_contains=ERROR') self.assertTrue(self.job.is_ok()) self.assertEqual(self.job.check_reason, 'exit=0, !output_contains=ERROR==True') def test_output_matches(self): """ Test output_matches criteria """ self._run(['/bin/echo', 'STATUS_TESTING_OK'], ok = 'exit_status=0,output_matches=.*TESTING.*') self.assertTrue(self.job.is_ok()) self.assertEqual(self.job.check_reason, 'exit=0, output_matches=.*TESTING.*==True') def test_output_matches_negated(self): """ Test output_matches criteria (negated) """ self._run(['/bin/echo', 'STATUS_TESTING_OK'], ok = 'exit_status=0,!output_matches=.*ERROR.*') self.assertTrue(self.job.is_ok()) self.assertEqual(self.job.check_reason, 'exit=0, !output_matches=.*ERROR.*==True')
[ "fredrik@thulin.net" ]
fredrik@thulin.net
123745a51a4487931e5561380391b6c3319da0f7
00c6ded41b84008489a126a36657a8dc773626a5
/.history/Sizing_Method/ConstrainsAnalysis/ConstrainsAnlysisPDP1P2_20210712110121.PY
77e48836eda05077e0c57d444cd96df38cf8a9d6
[]
no_license
12libao/DEA
85f5f4274edf72c7f030a356bae9c499e3afc2ed
1c6f8109bbc18c4451a50eacad9b4dedd29682bd
refs/heads/master
2023-06-17T02:10:40.184423
2021-07-16T19:05:18
2021-07-16T19:05:18
346,111,158
0
0
null
null
null
null
UTF-8
Python
false
false
21,441
py
# author: Bao Li # # Georgia Institute of Technology # import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysis as ca import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysisPD as ca_pd import Sizing_Method.Aerodynamics.Aerodynamics as ad import Sizing_Method.Aerodynamics.ThrustLapse as thrust_lapse import Sizing_Method.Other.US_Standard_Atmosphere_1976 as atm import matplotlib.pylab as plt import numpy as np import sys import os sys.path.insert(0, os.getcwd()) """ The unit use is IS standard """ class ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun: """This is a power-based master constraints analysis""" def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, C_DR=0): """ :param beta: weight fraction :param Hp: P_motor/P_total :param n: number of motor :param K1: drag polar coefficient for 2nd order term :param K2: drag polar coefficient for 1st order term :param C_D0: the drag coefficient at zero lift :param C_DR: additional drag caused, for example, by external stores, braking parachutes or flaps, or temporary external hardware :return: power load: P_WTO """ self.h = altitude self.v = velocity self.rho = atm.atmosphere(geometric_altitude=self.h).density() self.beta = beta self.hp = 1 - Hp self.n = number_of_motor # power lapse ratio self.alpha = thrust_lapse.thrust_lapse_calculation(altitude=self.h, velocity=self.v).high_bypass_ratio_turbofan() self.k1 = ad.aerodynamics_without_pd(self.h, self.v).K1() self.k2 = ad.aerodynamics_without_pd(self.h, self.v).K2() self.cd0 = ad.aerodynamics_without_pd(self.h, self.v).CD_0() self.cdr = C_DR self.w_s = wing_load self.g0 = 9.80665 self.coefficient = self.beta * self.v / self.alpha # Estimation of ΔCL and ΔCD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 self.cl = self.beta * self.w_s / self.q # print(self.cl) self.delta_cl = pd.delta_lift_coefficient(self.cl) self.delta_cd0 = pd.delta_CD_0() def master_equation(self, n, dh_dt, dV_dt): cl = self.cl * n + self.delta_cl cd = self.k1 * cl ** 2 + self.k2 * cl + self.cd0 + self.cdr + self.delta_cd0 p_w = self.coefficient * \ (self.q / (self.beta * self.w_s) * cd + dh_dt / self.v + dV_dt / self.g0) return p_w def cruise(self): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=1, dh_dt=0, dV_dt=0) return p_w def climb(self, roc): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 300 knots, which is about 150 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=load_factor, dh_dt=0, dV_dt=0) return p_w def take_off(self): """ A320neo take-off speed is about 150 knots, which is about 75 m/s required runway length is about 2000 m K_TO is a constant greater than one set to 1.2 (generally specified by appropriate flying regulations) """ Cl_max_to = 2.3 # 2.3 K_TO = 1.2 # V_TO / V_stall s_G = 1266 p_w = 2 / 3 * self.coefficient / self.v * self.beta * K_TO ** 2 / ( s_G * self.rho * self.g0 * Cl_max_to) * self.w_s ** ( 3 / 2) return p_w def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S def service_ceiling(self, roc=0.5): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] class ConstrainsAnalysis_Mattingly_Method_with_DP_electric: """This is a power-based master constraints analysis the difference between turbofun and electric for constrains analysis: 1. assume the thrust_lapse = 1 for electric propution 2. hp = 1 - hp_turbofun """ def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, C_DR=0): """ :param beta: weight fraction :param Hp: P_motor/P_total :param n: number of motor :param K1: drag polar coefficient for 2nd order term :param K2: drag polar coefficient for 1st order term :param C_D0: the drag coefficient at zero lift :param C_DR: additional drag caused, for example, by external stores, braking parachutes or flaps, or temporary external hardware :return: power load: P_WTO """ self.h = altitude self.v = velocity self.rho = atm.atmosphere(geometric_altitude=self.h).density() self.beta = beta self.hp = Hp # this is the difference part compare with turbofun self.n = number_of_motor # power lapse ratio self.alpha = 1 # this is the difference part compare with turbofun self.k1 = ad.aerodynamics_without_pd(self.h, self.v).K1() self.k2 = ad.aerodynamics_without_pd(self.h, self.v).K2() self.cd0 = ad.aerodynamics_without_pd(self.h, self.v).CD_0() self.cdr = C_DR self.w_s = wing_load self.g0 = 9.80665 self.coefficient = self.beta * self.v / self.alpha # Estimation of ΔCL and ΔCD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 self.cl = self.beta * self.w_s / self.q # print(self.cl) self.delta_cl = pd.delta_lift_coefficient(self.cl) self.delta_cd0 = pd.delta_CD_0() def master_equation(self, n, dh_dt, dV_dt): cl = self.cl * n + self.delta_cl cd = self.k1 * cl ** 2 + self.k2 * cl + self.cd0 + self.cdr + self.delta_cd0 p_w = self.coefficient * \ (self.q / (self.beta * self.w_s) * cd + dh_dt / self.v + dV_dt / self.g0) return p_w def cruise(self): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=1, dh_dt=0, dV_dt=0) return p_w def climb(self, roc): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 300 knots, which is about 150 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=load_factor, dh_dt=0, dV_dt=0) return p_w def take_off(self): """ A320neo take-off speed is about 150 knots, which is about 75 m/s required runway length is about 2000 m K_TO is a constant greater than one set to 1.2 (generally specified by appropriate flying regulations) """ Cl_max_to = 2.3 # 2.3 K_TO = 1.2 # V_TO / V_stall s_G = 1266 p_w = 2 / 3 * self.coefficient / self.v * self.beta * K_TO ** 2 / ( s_G * self.rho * self.g0 * Cl_max_to) * self.w_s ** ( 3 / 2) return p_w def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S def service_ceiling(self, roc=0.5): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] class ConstrainsAnalysis_Gudmundsson_Method_with_DP_turbofun: """This is a power-based master constraints analysis based on Gudmundsson_method""" def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, e=0.75, AR=10.3): """ :param beta: weight fraction :param e: wing planform efficiency factor is between 0.75 and 0.85, no more than 1 :param AR: wing aspect ratio, normally between 7 and 10 :return: power load: P_WTO """ self.h = altitude self.v = velocity self.beta = beta self.w_s = wing_load self.g0 = 9.80665 self.beta = beta self.hp = 1 - Hp self.n = number_of_motor self.rho = atm.atmosphere(geometric_altitude=self.h).density() # power lapse ratio self.alpha = thrust_lapse.thrust_lapse_calculation(altitude=self.h, velocity=self.v).high_bypass_ratio_turbofan() h = 2.43 # height of winglets b = 35.8 # equation 9-88, If the wing has winglets the aspect ratio should be corrected ar_corr = AR * (1 + 1.9 * h / b) self.k = 1 / (np.pi * ar_corr * e) self.coefficient = self.beta * self.v / self.alpha # Estimation of ΔCL and ΔCD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 cl = self.beta * self.w_s / self.q self.delta_cl = pd.delta_lift_coefficient(cl) self.delta_cd0 = pd.delta_CD_0() # TABLE 3-1 Typical Aerodynamic Characteristics of Selected Classes of Aircraft cd_min = 0.02 cd_to = 0.03 cl_to = 0.8 self.v_to = 68 self.s_g = 1480 self.mu = 0.04 self.cd_min = cd_min + self.delta_cd0 self.cl = cl + self.delta_cl self.cd_to = cd_to + self.delta_cd0 self.cl_to = cl_to + self.delta_cl def cruise(self): p_w = self.q / self.w_s * (self.cd_min + self.k * self.cl ** 2) return p_w * self.coefficient def climb(self, roc): p_w = roc / self.v + self.q * self.cd_min / self.w_s + self.k * self.cl return p_w * self.coefficient def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 100 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 q = 0.5 * self.rho * v ** 2 p_w = q / self.w_s * (self.cd_min + self.k * (load_factor / q * self.w_s + self.delta_cl) ** 2) return p_w * self.coefficient def take_off(self): q = self.q / 2 p_w = self.v_to ** 2 / (2 * self.g0 * self.s_g) + q * self.cd_to / self.w_s + self.mu * ( 1 - q * self.cl_to / self.w_s) return p_w * self.coefficient def service_ceiling(self, roc=0.5): vy = (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 q = 0.5 * self.rho * vy ** 2 p_w = roc / vy + q / self.w_s * \ (self.cd_min + self.k * (self.w_s / q + self.delta_cl) ** 2) # p_w = roc / (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 + 4 * ( # self.k * self.cd_min / 3) ** 0.5 return p_w * self.coefficient def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] class ConstrainsAnalysis_Gudmundsson_Method_with_DP_electric: """This is a power-based master constraints analysis based on Gudmundsson_method the difference between turbofun and electric for constrains analysis: 1. assume the thrust_lapse = 1 for electric propution 2. hp = 1 - hp_turbofun """ def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, e=0.75, AR=10.3): """ :param beta: weight fraction :param e: wing planform efficiency factor is between 0.75 and 0.85, no more than 1 :param AR: wing aspect ratio, normally between 7 and 10 :return: power load: P_WTO """ self.h = altitude self.v = velocity self.beta = beta self.w_s = wing_load self.g0 = 9.80665 self.beta = beta self.hp = Hp # this is the difference part compare with turbofun self.n = number_of_motor self.rho = atm.atmosphere(geometric_altitude=self.h).density() # power lapse ratio self.alpha = 1 # this is the difference part compare with turbofun h = 2.43 # height of winglets b = 35.8 # equation 9-88, If the wing has winglets the aspect ratio should be corrected ar_corr = AR * (1 + 1.9 * h / b) self.k = 1 / (np.pi * ar_corr * e) self.coefficient = self.beta * self.v / self.alpha # Estimation of ΔCL and ΔCD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 cl = self.beta * self.w_s / self.q self.delta_cl = pd.delta_lift_coefficient(cl) self.delta_cd0 = pd.delta_CD_0() # TABLE 3-1 Typical Aerodynamic Characteristics of Selected Classes of Aircraft cd_min = 0.02 cd_to = 0.03 cl_to = 0.8 self.v_to = 68 self.s_g = 1480 self.mu = 0.04 self.cd_min = cd_min + self.delta_cd0 self.cl = cl + self.delta_cl self.cd_to = cd_to + self.delta_cd0 self.cl_to = cl_to + self.delta_cl def cruise(self): p_w = self.q / self.w_s * (self.cd_min + self.k * self.cl ** 2) return p_w * self.coefficient def climb(self, roc): p_w = roc / self.v + self.q * self.cd_min / self.w_s + self.k * self.cl return p_w * self.coefficient def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 100 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 q = 0.5 * self.rho * v ** 2 p_w = q / self.w_s * (self.cd_min + self.k * (load_factor / q * self.w_s + self.delta_cl) ** 2) return p_w * self.coefficient def take_off(self): q = self.q / 2 p_w = self.v_to ** 2 / (2 * self.g0 * self.s_g) + q * self.cd_to / self.w_s + self.mu * ( 1 - q * self.cl_to / self.w_s) return p_w * self.coefficient def service_ceiling(self, roc=0.5): vy = (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 q = 0.5 * self.rho * vy ** 2 p_w = roc / vy + q / self.w_s * \ (self.cd_min + self.k * (self.w_s / q + self.delta_cl) ** 2) # p_w = roc / (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 + 4 * ( # self.k * self.cd_min / 3) ** 0.5 return p_w * self.coefficient def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] if __name__ == "__main__": n = 100 w_s = np.linspace(100, 9000, n) constrains_name = ['take off', 'stall speed', 'cruise', 'service ceiling', 'level turn @3000m', 'climb @S-L', 'climb @3000m', 'climb @7000m'] constrains = np.array([[0, 68, 0.988, 0.8, 0.5], [0, 80, 1, 0.5], [11300, 230, 0.948, 0.8], [11900, 230, 0.78, 0.5], [ 3000, 100, 0.984, 0.8], [0, 100, 0.984, 0.5], [3000, 200, 0.975, 0.6], [7000, 230, 0.96, 0.8]]) color = ['c', 'k', 'b', 'g', 'y', 'plum', 'violet', 'm'] label = ['feasible region with PD', 'feasible region with PD', 'feasible region Gudmundsson', 'feasible region without PD', 'feasible region without PD', 'feasible region Mattingly'] methods = [ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun, ConstrainsAnalysis_Gudmundsson_Method_with_DP_turbofun, ConstrainsAnalysis_Mattingly_Method_with_DP_electric, ConstrainsAnalysis_Gudmundsson_Method_with_DP_electric, ca.ConstrainsAnalysis_Mattingly_Method, ca.ConstrainsAnalysis_Gudmundsson_Method] m = constrains.shape[0] p_w = np.zeros([2 * m, n]) # plots fig, axs = plt.subplot(4, 2, figsize=(20, 20), sharex=True, sharey=True) for k in range(8): for i in range(m): for j in range(n): h = constrains[i, 0] v = constrains[i, 1] beta = constrains[i, 2] hp = constrains[i, 3] if k < 6: problem1 = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun( h, v, beta, w_s[j], hp) problem2 = ConstrainsAnalysis_Mattingly_Method_with_DP_electric( h, v, beta, w_s[j], hp) plt.title( r'Constraint Analysis: $\bf{Mattingly-Method}$ - Normalized to Sea Level') elif k == 1: problem1 = ConstrainsAnalysis_Gudmundsson_Method_with_DP_turbofun( h, v, beta, w_s[j], hp) problem2 = ConstrainsAnalysis_Gudmundsson_Method_with_DP_electric( h, v, beta, w_s[j], hp) plt.title( r'Constraint Analysis: $\bf{Gudmundsson-Method}$ - Normalized to Sea Level') else: problem1 = ca.ConstrainsAnalysis_Mattingly_Method( h, v, beta, w_s[j]) problem2 = ca.ConstrainsAnalysis_Gudmundsson_Method( h, v, beta, w_s[j]) plt.title( r'Constraint Analysis: $\bf{with}$ $\bf{DP}$ - Normalized to Sea Level') if i >= 5: p_w[i, j] = problem1.allFuncs[-1](problem1, roc=15 - 5 * (i - 5)) p_w[i + m, j] = problem2.allFuncs[-1](problem2, roc=15 - 5 * (i - 5)) else: p_w[i, j] = problem1.allFuncs[i](problem1) p_w[i + m, j] = problem2.allFuncs[i](problem2) if i == 1: axs[].plot(p_w[i, :], np.linspace( 0, 250, n), color=color[i], label=constrains_name[i]) l1b, = plt.plot( p_w[i + m, :], np.linspace(0, 250, n), color=color[i], linestyle='--') else: plt.plot(w_s, p_w[i, :], color=color[i], label=constrains_name[i]) plt.plot(w_s, p_w[i + m, :], color=color[i], linestyle='--') p_w[1, :] = 200 / (p_w[1, -1] - p_w[1, 20]) * (w_s - p_w[1, 2]) if k != 2: p_w[1 + m, :] = 10 ** 10 * (w_s - p_w[1 + m, 2]) else: p_w[1 + m, :] = 200 / (p_w[1 + m, -1] - p_w[1 + m, 20]) * (w_s - p_w[1 + m, 2]) plt.fill_between(w_s, np.amax(p_w[0:m - 1, :], axis=0), 200, color='b', alpha=0.25, label=label[k]) plt.fill_between(w_s, np.amax(p_w[m:2 * m - 1, :], axis=0), 200, color='r', alpha=0.25, label=label[k + 3]) plt.xlabel('Wing Load: $W_{TO}$/S (N/${m^2}$)') plt.ylabel('Power-to-Load: $P_{SL}$/$W_{TO}$ (W/N)') plt.legend(bbox_to_anchor=(1.002, 1), loc="upper left") plt.gca().add_artist(l1) plt.xlim(100, 9000) plt.ylim(0, 200) plt.tight_layout() plt.grid() plt.show()
[ "libao@gatech.edu" ]
libao@gatech.edu
1c402ab7373067bbc21a099324a4a52e008eaf33
e2f68f7f2b96af92d0d56ef9aa3119e7909cd992
/dataplicity/app.py
4324d9a7ad59def5aae43dca0bbb127b31f85691
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
anuradhawick/dataplicity-agent
c89edd563103aa251f858d38aeba8ed6c605481c
9d4c234f0d7b24aa144a079f54883d38eb8b9f40
refs/heads/master
2022-04-09T18:16:18.590182
2020-03-26T12:10:44
2020-03-26T12:10:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,933
py
from __future__ import unicode_literals from __future__ import print_function import argparse import logging import logging.config import sys from . import __version__ from . import subcommand from .client import Client from .subcommands import run, version log = logging.getLogger("app") # Map log levels on to integer values _logging_level_names = { "NOTSET": 0, "DEBUG": 10, "INFO": 20, "WARN": 30, "WARNING": 30, "ERROR": 40, "CRITICAL": 50, } class App(object): """Dataplicity Agent command line interface.""" def __init__(self): self.subcommands = { name: cls(self) for name, cls in subcommand.registry.items() } def _make_arg_parser(self): """Make an argument parse object.""" parser = argparse.ArgumentParser("dataplicity", description=self.__doc__) _version = "dataplicity agent v{}".format(__version__) parser.add_argument( "-v", "--version", action="version", version=_version, help="Display version and exit", ) parser.add_argument( "--log-level", metavar="LEVEL", default="INFO", help="Set log level (INFO or WARNING or ERROR or DEBUG)", ) parser.add_argument( "--log-file", metavar="PATH", default=None, help="Set log file" ) parser.add_argument( "-d", "--debug", action="store_true", dest="debug", default=False, help="Enables debug output", ) parser.add_argument( "-s", "--server-url", metavar="URL", dest="server_url", default=None, help="URL of dataplicity.com api", ) parser.add_argument( "-m", "--m2m-url", metavar="WS URL", dest="m2m_url", default=None, help="URL of m2m server (should start with ws:// or wss://", ) parser.add_argument( "-q", "--quiet", action="store_true", default=False, help="Hide output" ) parser.add_argument( "--serial", dest="serial", metavar="SERIAL", default=None, help="Set Dataplicity serial", ) parser.add_argument( "--auth", dest="auth_token", metavar="KEY", default=None, help="Set Dataplicity auth token", ) subparsers = parser.add_subparsers( title="available sub-commands", dest="subcommand", help="sub-command help" ) for name, _subcommand in self.subcommands.items(): subparser = subparsers.add_parser( name, help=_subcommand.help, description=getattr(_subcommand, "__doc__", None), ) _subcommand.add_arguments(subparser) return parser def _init_logging(self): """Initialise logging.""" log_format = "%(asctime)s %(name)s\t: %(message)s" log_level = "CRITICAL" if self.args.quiet else self.args.log_level.upper() try: log_level_no = _logging_level_names[log_level] except IndexError: self.error("invalid log level") if self.args.log_file: log_config = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "class": "logging.Formatter", "format": log_format, "datefmt": "[%d/%b/%Y %H:%M:%S]", } }, "handlers": { "file": { "level": log_level, "class": "logging.handlers.RotatingFileHandler", "maxBytes": 5 * 1024 * 1024, "backupCount": 5, "filename": self.args.log_file, "formatter": "simple", } }, "loggers": {"": {"level": log_level, "handlers": ["file"]}}, } logging.config.dictConfig(log_config) else: logging.basicConfig( format=log_format, datefmt="[%d/%b/%Y %H:%M:%S]", level=log_level_no ) def make_client(self): """Make the client object.""" client = Client( rpc_url=self.args.server_url, m2m_url=self.args.m2m_url, serial=self.args.serial, auth_token=self.args.auth_token, ) return client def error(self, msg, code=-1): """Display error and exit app.""" log.critical("app exit ({%s}) code={%s}", msg, code) sys.stderr.write(msg + "\n") sys.exit(code) def run(self): parser = self._make_arg_parser() args = self.args = parser.parse_args(sys.argv[1:]) self._init_logging() log.debug("ready") if args.subcommand is None: parser.print_help() return 1 subcommand = self.subcommands[args.subcommand] subcommand.args = args try: return subcommand.run() or 0 except Exception as e: if self.args.debug: raise sys.stderr.write("(dataplicity {}) {}\n".format(__version__, e)) cmd = sys.argv[0].rsplit("/", 1)[-1] debug_cmd = " ".join([cmd, "--debug"] + sys.argv[1:]) sys.stderr.write("(run '{}' for a full traceback)\n".format(debug_cmd)) return -1 def main(): """Dataplicity Agent entry point.""" return_code = App().run() or 0 log.debug("exit with code %s", return_code) sys.exit(return_code)
[ "willmcgugan@gmail.com" ]
willmcgugan@gmail.com
5ac7b412818bafed0c9a0fdd1e88eb758822a248
1089437ea52a24ef7e64c22ef4f9887884ddd3fa
/Cursos/Desenvolvimento de Games 2D/Games/Scrolling Platformer/07_Collectible Items/main.py
5117466781411a5766798ce736b786dd71c30126
[]
no_license
Rafael-doctom/CC33Z
326b3d2aae7b1c903ab57753cbe5493d183159b3
df25c2a3d30a79efe0e5d5958ec3a79d6fe5f42f
refs/heads/master
2023-08-01T02:42:18.945223
2021-09-18T18:05:59
2021-09-18T18:05:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,570
py
import pygame import os pygame.init() # Definições da tela WIDTH = 800 HEIGHT = int(WIDTH * 0.8) screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Scrolling Platformer') # Definir frame rate clock = pygame.time.Clock() FPS = 60 # Definir váriaveis do game GRAVITY = 0.75 TILE_SIZE = 40 # Variáveis de ação do player moving_left = False moving_right = False shoot = False grenade = False grenade_thrown = False # Carregar imagens bullet_img = pygame.image.load('images/icons/bullet.png').convert_alpha() grenade_img = pygame.image.load('images/icons/grenade.png').convert_alpha() health_box_img = pygame.image.load('images/icons/health_box.png').convert_alpha() ammo_box_img = pygame.image.load('images/icons/ammo_box.png').convert_alpha() grenade_box_img = pygame.image.load('images/icons/grenade_box.png').convert_alpha() item_boxes = { 'Health' : health_box_img, 'Ammo' : ammo_box_img, 'Grenade' : grenade_box_img } # Definir cores BG = (144, 201, 120) BROWN = (79, 53, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLACK = (0, 0, 0) # Definir fonte font = pygame.font.SysFont('Futura', 30) def draw_text(text, font, text_color, x, y): img = font.render(text, True, text_color) screen.blit(img, (x, y)) def draw_bg(): screen.fill(BG) pygame.draw.line(screen, BROWN, (0, 300), (WIDTH, 300), 5) # Classe que representa um soldado class Soldier(pygame.sprite.Sprite): def __init__(self, char_type, x, y, scale, speed, ammo, grenades): pygame.sprite.Sprite.__init__(self) self.alive = True self.char_type = char_type self.speed = speed self.ammo = ammo self.start_ammo = ammo self.shoot_cooldown = 0 self.grenades = grenades self.health = 100 self.max_health = self.health self.direction = 1 self.vel_y = 0 self.jump = False self.in_air = True self.flip = False self.animation_list = [] self.frame_index = 0 self.action = 0 self.update_time = pygame.time.get_ticks() # Carregar todas as imagens animation_types = ['Idle', 'Run', 'Jump', 'Death'] for animation in animation_types: # Resetar a lista de temporária de imagens temp_list = [] # Contar o número de arquivos no diretório num_of_frames = len(os.listdir(f'images/{self.char_type}/{animation}')) for i in range(num_of_frames): img = pygame.image.load(f'images/{self.char_type}/{animation}/{i}.png').convert_alpha() img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] # Cria um retângulo a partir da imagem do player self.rect = self.image.get_rect() self.rect.center = (x, y) def update(self): self.update_animation() self.check_alive() # Atualizar cooldown if self.shoot_cooldown > 0: self.shoot_cooldown -= 1 def move(self, moving_left, moving_right): # Resetar variáveis de movimento dx = 0 dy = 0 # Atribuir variáveis de movimento se mover para a direita ou esquerda if moving_left: dx = -self.speed self.flip = True self.direction = -1 if moving_right: dx = self.speed self.flip = False self.direction = 1 # Pular if self.jump == True and self.in_air == False: self.vel_y = -11 self.jump = False self.in_air = True # Aplicar gravidade self.vel_y += GRAVITY if self.vel_y > 10: self.vel_y dy += self.vel_y # Checar colisão com o chão if self.rect.bottom + dy > 300: dy = 300 - self.rect.bottom self.in_air = False # Atualizar a posição do retângulo self.rect.x += dx self.rect.y += dy def shoot(self): if self.shoot_cooldown == 0 and self.ammo > 0: self.shoot_cooldown = 20 bullet = Bullet(self.rect.centerx + (0.6 * self.rect.size[0] * self.direction), self.rect.centery, self.direction) bullet_group.add(bullet) # Reduzir munição self.ammo -= 1 def update_animation(self): # Atualizar animação ANIMATION_COOLDOWN = 100 # Atualizar imagem dependendo do frame atual self.image = self.animation_list[self.action][self.frame_index] # Checar se passou tempo suficiente desde a última atualização if pygame.time.get_ticks() - self.update_time > ANIMATION_COOLDOWN: self.update_time = pygame.time.get_ticks() self.frame_index += 1 # Se a animação acabou, então resetar ela para o início if self.frame_index >= len(self.animation_list[self.action]): if self.action == 3: self.frame_index = len(self.animation_list[self.action]) - 1 else: self.frame_index = 0 def update_action(self, new_action): # Checar se a nova ação é diferente da anterior if new_action != self.action: self.action = new_action # Atualizar as configurações da animação self.frame_index = 0 self.update_time = pygame.time.get_ticks() def check_alive(self): if self.health <= 0: self.health = 0 self.speed = 0 self.alive = False self.update_action(3) # 3 = morto def draw(self): screen.blit(pygame.transform.flip(self.image, self.flip, False), self.rect) class ItemBox(pygame.sprite.Sprite): def __init__(self, item_type, x, y): pygame.sprite.Sprite.__init__(self) self.item_type = item_type self.image = item_boxes[self.item_type] self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): # Checar se o player coletou a caixa if pygame.sprite.collide_rect(self, player): # Checar o tipo de caixa que o player coletou if self.item_type == 'Health': player.health += 25 if player.health > player.max_health: player.health = player.max_health elif self.item_type == 'Ammo': player.ammo += 15 elif self.item_type == 'Grenade': player.grenades += 3 # Remover a caixa de item self.kill() class HealthBar(): def __init__(self, x, y, health, max_health): self.x = x self.y = y self.health = health self.max_health = max_health def draw(self, health): # Atualizar a vida do player self.health = health # Calcular a proporação da vida do player ratio = self.health / self.max_health pygame.draw.rect(screen, BLACK, (self.x - 2, self.y - 2, 154, 24)) pygame.draw.rect(screen, RED, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, GREEN, (self.x, self.y, 150 * ratio, 20)) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y, direction): pygame.sprite.Sprite.__init__(self) self.speed = 10 self.image = bullet_img self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction def update(self): # Mover o projétil self.rect.x += (self.direction * self.speed) # Checar se o projétil saiu da tela if self.rect.right < 0 or self.rect.left > WIDTH: self.kill() # Checar colisão com personagens if pygame.sprite.spritecollide(player, bullet_group, False): if player.alive: player.health -= 5 self.kill() for enemy in enemy_group: if pygame.sprite.spritecollide(enemy, bullet_group, False): if enemy.alive: enemy.health -= 25 self.kill() class Grenade(pygame.sprite.Sprite): def __init__(self, x, y, direction): pygame.sprite.Sprite.__init__(self) self.timer = 100 self.vel_y = -11 self.speed = 7 self.image = grenade_img self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction def update(self): self.vel_y += GRAVITY dx = self.direction * self.speed dy = self.vel_y # Checar colisão com o chão if self.rect.bottom + dy > 300: dy = 300 -self.rect.bottom self.speed = 0 # Checar por colisão com paredes if self.rect.left + dx < 0 or self.rect.right + dx > WIDTH: self.direction *= -1 dx = self.direction * self.speed # Atualizar a posição da granada self.rect.x += dx self.rect.y += dy # Countdown timer self.timer -= 1 if self.timer <= 0: self.kill() explosion = Explosion(self.rect.x, self.rect.y, 0.5) explosion_group.add(explosion) # Causar dano a qualquer um que esteja perto if abs(self.rect.centerx - player.rect.centerx) < TILE_SIZE * 2 and abs(self.rect.centery - player.rect.centery) < TILE_SIZE * 2: player.health -= 50 for enemy in enemy_group: if abs(self.rect.centerx - enemy.rect.centerx) < TILE_SIZE * 2 and abs(self.rect.centery - enemy.rect.centery) < TILE_SIZE * 2: enemy.health -= 50 class Explosion(pygame.sprite.Sprite): def __init__(self, x, y, scale): pygame.sprite.Sprite.__init__(self) self.images = [] for num in range(1,6): img = pygame.image.load(f'images/explosion/exp{num}.png').convert_alpha() img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) self.images.append(img) self.frame_index = 0 self.image = self.images[self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) self.counter = 0 def update(self): EXPLOSION_SPEED = 4 # Atualizar a animação da explosão self.counter += 1 if self.counter >= EXPLOSION_SPEED: self.counter = 0 self.frame_index += 1 # Se a animação está completa, então deletar a explosão if self.frame_index >= len(self.images): self.kill() else: self.image = self.images[self.frame_index] # Criar grupos de sprites enemy_group = pygame.sprite.Group() bullet_group = pygame.sprite.Group() grenade_group = pygame.sprite.Group() explosion_group = pygame.sprite.Group() item_box_group = pygame.sprite.Group() # Criar caixas de itens item_box = ItemBox('Health', 100, 259) item_box_group.add(item_box) item_box = ItemBox('Ammo', 430, 259) item_box_group.add(item_box) item_box = ItemBox('Grenade', 470, 259) item_box_group.add(item_box) # Player e inimigos player = Soldier('player', 200, 200, 3, 5, 20, 5) health_bar = HealthBar(10, 10, player.health, player.health) enemy = Soldier('enemy', 400, 245, 3, 5, 20, 0) enemy2 = Soldier('enemy', 500, 245, 3, 5, 20, 0) enemy_group.add(enemy) enemy_group.add(enemy2) # Game Loop run = True while run: clock.tick(FPS) draw_bg() # Apresentar a vida do player health_bar.draw(player.health) # Apresentar a munição do player draw_text('AMMO: ', font, WHITE, 10, 35) for x in range(player.ammo): screen.blit(bullet_img, (90 + (x * 10), 40)) # Apresentar as granadas do player draw_text('GRENADES: ', font, WHITE, 10, 60) for x in range(player.grenades): screen.blit(grenade_img, (135 + (x * 15), 60)) # Desenhar o player e o inimigo player.update() player.draw() for enemy in enemy_group: enemy.update() enemy.draw() # Atualizar e desenhar grupos bullet_group.update() grenade_group.update() explosion_group.update() item_box_group.update() bullet_group.draw(screen) grenade_group.draw(screen) explosion_group.draw(screen) item_box_group.draw(screen) # Atualizar ações do player if player.alive: # Atirar projéteis if shoot: player.shoot() # Arremessar granadas elif grenade and grenade_thrown == False and player.grenades > 0: grenade = Grenade(player.rect.centerx + (0.5 * player.rect.size[0] * player.direction), player.rect.top, player.direction) grenade_group.add(grenade) # Reduzir granadas player.grenades -= 1 grenade_thrown = True if player.in_air: player.update_action(2) # 2 significa 'pulando' elif moving_left or moving_right: player.update_action(1) # 1 significa 'correndo' else: player.update_action(0) # 0 significa 'parado' player.move(moving_left, moving_right) for event in pygame.event.get(): # Sair do game if event.type == pygame.QUIT: run = False # Teclas pressionadas if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: moving_left = True if event.key == pygame.K_d: moving_right = True if event.key == pygame.K_SPACE: shoot = True if event.key == pygame.K_q: grenade = True if event.key == pygame.K_w and player.alive: player.jump = True if event.key == pygame.K_ESCAPE: run = False # Teclas do teclado liberadas if event.type == pygame.KEYUP: if event.key == pygame.K_a: moving_left = False if event.key == pygame.K_d: moving_right = False if event.key == pygame.K_SPACE: shoot = False if event.key == pygame.K_q: grenade = False grenade_thrown = False # Atualizar a tela pygame.display.update() pygame.quit()
[ "gabrielfelippe90@gmail.com" ]
gabrielfelippe90@gmail.com
ceaaef67a466aa7984b5aeb9fc34214bdf9d406f
75f6bbcdf10dec884202b3136feb0317842df55f
/apps/task/migrations/0004_taskhistory_run_time.py
d4d47070a627c7c134373d9e2215331eb3433b6a
[]
no_license
qt-pay/python-devops
bafa305fbcd7bef4498857ab75be7447bc1e0a42
60e9481ab84628cf817fde1c52f4a15d5085e503
refs/heads/main
2023-03-15T12:39:45.813287
2021-01-24T18:40:38
2021-01-24T18:40:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
446
py
# Generated by Django 2.2.2 on 2021-01-06 14:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('task', '0003_auto_20210105_1927'), ] operations = [ migrations.AddField( model_name='taskhistory', name='run_time', field=models.CharField(blank=True, max_length=20, null=True, verbose_name='脚本运行时长'), ), ]
[ "yans121@sina.com" ]
yans121@sina.com
7004ab283426443a3f4451a5ffc528d9736cf14c
31317fee8b739559ca90a5cee532bc71a1e7196d
/sbds/storages/db/utils.py
f92a19a4b35dfffa6ddb76bcaed0b3ee1d4610ab
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
arpwv/sbds
402a966826f1ca4d88816b65ff7dfb19555c103c
a065599365c7b86349dc1223ca1013b3985f56e3
refs/heads/master
2021-01-24T03:43:53.102829
2018-02-16T02:35:29
2018-02-16T02:35:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,633
py
# -*- coding: utf-8 -*- from contextlib import contextmanager from collections import namedtuple import sqlalchemy.orm.exc import sqlalchemy.exc from sqlalchemy import create_engine from sqlalchemy.engine.url import make_url from sqlalchemy.pool import NullPool from sbds.sbds_logging import getLogger import sbds.sbds_json logger = getLogger(__name__) # pylint: disable=too-many-arguments, broad-except, protected-access def _unique(session, cls, hashfunc, queryfunc, constructor, args, kwargs): cache = getattr(session, '_unique_cache', None) cls_name = cls.__name__ if cache is None: session._unique_cache = cache = {} logger.debug('_unique created session cache') key = (cls, hashfunc(*args, **kwargs)) if key in cache: logger.debug('_unique key %s found in session cache', key) return cache[key] else: logger.debug('_unique key %s not found in session cache', key) with session.no_autoflush: q = session.query(cls) q = queryfunc(q, *args, **kwargs) logger.debug('_unique query %s', q) obj = q.one_or_none() if not obj: logger.debug('_unique query found no existing %s instance', cls_name) obj = constructor(*args, **kwargs) # prevent race condition by using savepoint (begin_nested) session.begin(subtransactions=True) logger.debug('_unique beginning subtransaction') try: logger.debug( '_unique while in subtransaction: attempting to create %s', obj) session.add(obj) session.commit() logger.debug('_unique while in subtransaction: created %s', obj) except sqlalchemy.exc.IntegrityError as e: logger.debug( '_unique IntegrityError while creating %s instance', cls_name) session.rollback() logger.debug( '_unique while handling IntegrityError: rollback transaction' ) q = session.query(cls) q = queryfunc(q, *args, **kwargs) obj = q.one() logger.debug( '_unique while handling IntegrityError: query found %s', obj) except Exception as e: logger.error('_unique error creating %s instance: %s', cls_name, e) raise e else: logger.debug('_unique %s instance created', cls_name) else: logger.debug('_unique query found existing %s instance', cls_name) cache[key] = obj return obj class UniqueMixin(object): @classmethod def unique_hash(cls, *arg, **kw): raise NotImplementedError() @classmethod def unique_filter(cls, query, *arg, **kw): raise NotImplementedError() @classmethod def as_unique(cls, session, *arg, **kw): return _unique(session, cls, cls.unique_hash, cls.unique_filter, cls, arg, kw) def is_duplicate_entry_error(error): if isinstance(error, sqlalchemy.orm.exc.FlushError): return 'conflicts with persistent instance' in str(error) elif isinstance(error, sqlalchemy.exc.IntegrityError): code, msg = error.orig.args msg = msg.lower() return all([code == 1062, "duplicate entry" in msg]) # pylint: disable=too-many-branches, too-many-statements @contextmanager def session_scope(session=None, close=False, expunge=False, _raise_unknown=False, _raise_known=False, _raise_all=False): """Provide a transactional scope around a series of db operations.""" if _raise_all: _raise_known = True _raise_unknown = True # rollback passed session if required if not session.is_active: logger.debug('rolling back passed session') session.rollback() try: session.info['err'] = None session.begin(subtransactions=True) yield session session.commit() session.commit() except (sqlalchemy.exc.IntegrityError, sqlalchemy.orm.exc.FlushError) as e: session.rollback() session.info['err'] = e if is_duplicate_entry_error(e): logger.debug('duplicate entry error caught') else: logger.exception('non-duplicate IntegrityError, unable to commit') if _raise_known: raise e except sqlalchemy.exc.DBAPIError as e: session.rollback() session.info['err'] = e logger.exception('Caught DBAPI error') if _raise_known: raise e except Exception as e: session.rollback() session.info['err'] = e logger.exception('unable to commit') if _raise_unknown: raise e finally: if close: logger.debug('calling session.close') session.close() elif expunge: logger.debug('calling session.expunge_all') session.expunge_all() if not session.is_active: logger.debug('second session.rollback required...rolling back') session.rollback() def row_to_json(row): if getattr(row, 'to_json'): return row.to_json() else: return sbds.sbds_json.dumps(dict(row.items())) EngineConfig = namedtuple('EngineConfig', ['database_url', 'url', 'engine_kwargs', 'engine']) def configure_engine(database_url, **kwargs): if kwargs: base_engine_kwargs = kwargs else: base_engine_kwargs = dict() url = make_url(database_url) logger.debug('configuring engine using %s', url.__repr__()) backend = url.get_backend_name() if backend == 'sqlite': logger.debug('configuring sqlite backend') engine_kwargs = base_engine_kwargs if backend == 'mysql': logger.debug('configuring mysql backend') if 'charset' not in url.query: logger.debug('adding `charset=utf8mb4` to mysql engine config') url.query.update(charset='utf8mb4') engine_kwargs = base_engine_kwargs engine_kwargs.update(server_side_cursors=True, encoding='utf8') else: logger.debug('configuring %s backend', backend) engine_kwargs = base_engine_kwargs logger.debug('engine_kwargs: %s', engine_kwargs) engine = create_engine(url, **engine_kwargs) # create tables for in-memory db if backend == 'sqlite' and url.database is None: from .tables import Base Base.metadata.create_all(bind=engine, checkfirst=True) return EngineConfig(database_url, url, engine_kwargs, engine) def configure_nullpool_engine(database_url, poolclass=NullPool, **kwargs): if kwargs: kwargs.pop('poolclass', None) return configure_engine(database_url, poolclass=poolclass, **kwargs) @contextmanager def isolated_nullpool_engine(database_url, **kwargs): engine_config = configure_nullpool_engine(database_url, **kwargs) engine = engine_config.engine try: yield engine except Exception as e: logger.info(e) finally: del engine_config engine.dispose() del engine @contextmanager def isolated_engine(database_url, **kwargs): engine_config = configure_engine(database_url, **kwargs) engine = engine_config.engine try: yield engine except Exception as e: logger.info(e) finally: del engine_config engine.dispose() del engine @contextmanager def isolated_engine_config(database_url, **kwargs): engine_config = configure_engine(database_url, **kwargs) try: yield engine_config except Exception as e: logger.info(e) finally: engine_config.engine.dispose() del engine_config def get_db_processes(database_url, **kwargs): with isolated_nullpool_engine(database_url, **kwargs) as engine: if engine.url.get_backend_name() != 'mysql': raise TypeError('unsupported function for %s database' % engine.url.get_backend_name()) return engine.execute('SHOW PROCESSLIST').all() def kill_db_processes(database_url, db_name=None, db_user_name=None): url = make_url(database_url) if url.get_backend_name() == 'sqlite': return [], [] processes = get_db_processes(database_url) all_procs = [] killed_procs = [] with isolated_nullpool_engine(database_url) as engine: for process in processes: logger.debug( 'process: Id:%s User:%s db:%s Command:%s State:%s Info:%s', process.Id, process.User, process.db, process.Command, process.State, process.Info) all_procs.append(process) if process.db == db_name and process.User == db_user_name: if process.Info != 'SHOW PROCESSLIST': logger.debug('killing process %s on db %s owned by %s', process.Id, process.db, process.User) engine.execute('KILL %s' % process.Id) killed_procs.append(process) return all_procs, killed_procs
[ "john.gerlock@gmail.com" ]
john.gerlock@gmail.com
afe99c5dbd056a118f4b8016b5e82309d514bfcb
cec68acfc0187b7d92fb7d6e5107058e3f8269ea
/Degiskenler/sozluk.py
d095580f7fa0dd6618f37d68ac9c10ee1cf7d9b9
[]
no_license
vektorelpython/Python8
441575224100a687467c4934f7c741aa0c4bd087
d135fbf1444d56a0da38c42fd2e8feda48646f49
refs/heads/master
2022-01-18T12:17:40.387422
2019-09-07T13:47:55
2019-09-07T13:47:55
205,534,765
1
0
null
null
null
null
UTF-8
Python
false
false
206
py
sozluk = {"elma":"apple","portakal":"orange","kitap":"book"} print(sozluk) print(sozluk["elma"]) sozluk["elma"] = "alma" print(sozluk) sozluk.update({"kalem":"pencil"}) print(sozluk) print(sozluk.values())
[ "Kurs" ]
Kurs
a1c0ae12360d7f426f7df523dba5d075c446021e
11ca0c393c854fa7212e783a34269f9dae84e8c7
/Python/381. O(1) 时间插入、删除和获取随机元素 - 允许重复.py
9b0953c2ceda3750878644fdc4c09fbf6a49a38e
[]
no_license
VictoriqueCQ/LeetCode
dc84d81163eed26fa9dbc2114bba0b5c2ea881f4
a77b3ead157f97f5d9599badb4d4c5da69de44ba
refs/heads/master
2021-06-05T06:40:24.659909
2021-03-31T08:31:51
2021-03-31T08:31:51
97,978,957
0
0
null
null
null
null
UTF-8
Python
false
false
828
py
import random class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.v = [] def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. """ self.v.append(val) return val not in self.v[: -1] def remove(self, val: int) -> bool: """ Removes a value from the collection. Returns true if the collection contained the specified element. """ if val not in self.v: return False self.v.remove(val) return True def getRandom(self) -> int: """ Get a random element from the collection. """ return random.choice(self.v)
[ "1997Victorique0317" ]
1997Victorique0317
d1f9477dfbe06bd03429351846beab4de65d55b0
b5cc6d7b5f7ccea36fce4eab961979404414f8b0
/fem/fenics_solvers.py
f3d97983089a684391179e43738572f19b731b8b
[]
no_license
MiroK/cutFEM-beam
adf0c925dbe64b370dab48e82335617450675f5d
2fb3686804e836d4031fbf231a36a0f9ac8a3012
refs/heads/master
2021-01-21T23:54:32.868307
2015-02-14T13:14:59
2015-02-14T13:14:59
25,625,143
0
0
null
null
null
null
UTF-8
Python
false
false
6,241
py
from dolfin import * # Optimization options for the form compiler parameters["form_compiler"]["cpp_optimize"] = True parameters["form_compiler"]["optimize"] = True # Make mesh ghosted for evaluation of DG terms parameters["ghost_mode"] = "shared_facet" def cg_solver(mesh, problem, p=2, verbose=False): ''' Solve biharmonic problem: laplace^2(u) = f in mesh u = 0 on mesh boundary laplace(u) = 0 on mesh boundary We use CG elements of degree p. Interior penalty is used to force continuity of laplace u. ''' assert p > 1 if isinstance(mesh, str): mesh = Mesh(mesh) u_exact = problem['u'] f = problem['f'] V = FunctionSpace(mesh, 'CG', p) u = TrialFunction(V) v = TestFunction(V) h = CellSize(mesh) h_avg = (h('+') + h('-'))/2.0 n = FacetNormal(mesh) # Penalty parameter alpha = Constant(100) # Define bilinear form # Standard term a = inner(div(grad(u)), div(grad(v)))*dx # Ip stab of surface term with grad(v).n a += - inner(avg(div(grad(u))), jump(grad(v), n))*dS \ - inner(jump(grad(u), n), avg(div(grad(v))))*dS \ + alpha/h_avg**(p-1)*inner(jump(grad(u), n), jump(grad(v), n))*dS # Define linear form L = inner(f, v)*dx # DirichletBC bc = DirichletBC(V, Constant(0), DomainBoundary()) # Solve variational problem A, M = PETScMatrix(), PETScMatrix() b = PETScVector() m = inner(u, v)*dx assemble_system(m, L, bc, A_tensor=M, b_tensor=b) assemble_system(a, L, bc, A_tensor=A, b_tensor=b) # try: # esolver = SLEPcEigenSolver(A) # esolver.parameters['spectrum'] = 'largest magnitude' # esolver.solve(1) # max_r, max_c = esolver.get_eigenvalue(0) # if mesh.num_cells() < 513: # print '..' # esolver.parameters['spectrum'] = 'smallest magnitude' # esolver.solve(1) # min_r, min_c = esolver.get_eigenvalue(0) # print '%2E %2E %2E \t' % (max_r, min_r, max_r/min_r) # except: # print 'Eigensolver went wrong' u = Function(V) solve(A, u.vector(), b) # Plot solution if verbose: plot(u, title='numeric') plot(u_exact, mesh=mesh, title='exact') interactive() e_L2 = errornorm(u_exact, u, 'l2') return {'h': mesh.hmax(), 'L2': e_L2, 'a_max': 1, 'uh': u} def mixed_solver(mesh, problem, p, verbose=False): ''' Solve biharmonic problem: laplace^2(u) = f in mesh u = 0 on mesh boundary laplace(u) = 0 on mesh boundary by braking it into -laplace(u) = sigma -laplace(sigma) = f in mesh u = 0 sigma = 0 on mesh boundary We use CG elements of degree p for u-space and n for s-space ''' if isinstance(mesh, str): mesh = Mesh(mesh) u_exact = problem['u'] f = problem['f'] # -------- V = FunctionSpace(mesh, 'CG', p) u = TrialFunction(V) v = TestFunction(V) # Stiffness matrix a = inner(grad(u), grad(v))*dx m = inner(u, v)*dx # Define linear form L = inner(f, v)*dx # DirichletBC bc = DirichletBC(V, Constant(0), DomainBoundary()) A = PETScMatrix() b = PETScVector() assemble_system(a, L, bc, A_tensor=A, b_tensor=b) B, _ = assemble_system(m, L) solver = LUSolver(A) solver.parameters['reuse_factorization'] = True # Solve first for moment sigma = Function(V) print '.' solver.solve(sigma.vector(), b) print '..' # Make the rhs for discplacement system B.mult(sigma.vector(), b) # Solve for u u = Function(V) solver.solve(u.vector(), b) print '...' # Plot solution if verbose: plot(u, title='numeric') plot(u_exact, mesh=mesh, title='exact') interactive() e_L2 = errornorm(u_exact, u, 'l2') return {'h': mesh.hmax(), 'L2': e_L2, 'a_max': 1} # ----------------------------------------------------------------------------- if __name__ == '__main__': DIM = -1 if DIM == 2: from problem import joris_problem D, Lx, Ly, = 1, 1, 1 problem = joris_problem(D, Lx, Ly) mesh = RectangleMesh(0, 0, Lx, Ly, 40, 40) mixed_solver(mesh, problem, 2, True) cg_solver(mesh, problem, 2, True) elif DIM == 1: from problem import manufacture_biharmonic_1d import sympy as sp x = sp.symbols('x') a = -1 b = 1.5 E = 1 u = sp.sin(sp.pi*(x-a)/(b-a)) problem = manufacture_biharmonic_1d(u=u, a=a, b=b, E=E) mesh = IntervalMesh(100, a, b) mixed_solver(mesh, problem, 2, True) cg_solver(mesh, problem, 2, True) else: from problem import manufacture_biharmonic_1d import matplotlib.pyplot as plt from sympy.plotting import plot_parametric from beam_mesh import line_mesh import numpy as np import sympy as sp x = sp.symbols('x') E = 1 A = np.array([0.25, 0]) B = np.array([0.75, 1]) L = np.hypot(*(A-B)) f = 1 problem = manufacture_biharmonic_1d(f=f, a=0, b=L, E=E) u = problem['u'] plot_parametric(A[0] + (B[0]-A[0])*x, A[1] + (B[1]-A[1])*x, (x, 0, 1), xlim=(0, 1), ylim=(0, 1)) n_cells = 2**10 line_mesh(A, B, n_cells, 'mesh.xml') mesh = Mesh('mesh.xml') ans = cg_solver(mesh, problem) uh = ans['uh'] def F(s): return A + (B-A)*s/L s = np.linspace(0, L, 100) plt.figure() plt.plot(s, [u(si) for si in s], label='exact') plt.plot(s, [uh(*F(si)) for si in s], label='numeric') plt.legend(loc='best') plt.axis('tight') plt.show() beam_mesh = mesh plate_mesh = UnitSquareMesh(10, 10) # Constraint is a problem ... V = FunctionSpace(plate_mesh, 'CG', 2) W = FunctionSpace(beam_mesh, 'CG', 2) P = FunctionSpace(beam_mesh, 'CG', 1) M = MixedFunctionSpace([V, W, P])
[ "miroslav.kuchta@gmail.com" ]
miroslav.kuchta@gmail.com
677089b7b1256a45b93d36d61e4e372fe35bacc7
f0fd2b4f56b1753e47139a3557a1625abcfead9e
/django/full_stack/dojo_reads/dojo_reads/settings.py
0b4358dfd60ebfcbe0fa20911d6c4c865e8f3ac9
[]
no_license
nlee1229/Python-Stack
16dd6078be98392d8a21a93965beb7d39ba4157e
1aba5cf17f1f6c50d8fd50de031fcd6ec2bdda21
refs/heads/master
2023-03-26T05:12:14.264780
2021-03-22T01:56:22
2021-03-22T01:56:22
328,876,685
0
0
null
null
null
null
UTF-8
Python
false
false
3,137
py
""" Django settings for dojo_reads project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'h0#b4y0t5hth3zppr06er+!c76zu6!%9elk3x^7al8^2u5#0t7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login_reg_app', 'main_app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dojo_reads.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dojo_reads.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/'
[ "72540269+nlee1229@users.noreply.github.com" ]
72540269+nlee1229@users.noreply.github.com
1384c1ff2612ff5f0f8be90dfae43879dd290276
af4479ae394a5c9d3bc8abe2bf24919f74abe1f8
/stopwatch_gui_withmenu.py
f242feb020c34dd050086c2f80ef539a81850153
[]
no_license
icyflame/stopwatch2
4795f57d34fbc6d3090d391db344049f617c6506
b090c98b449e3013296e1884cbfb00851187ec31
refs/heads/master
2021-01-20T06:17:28.537807
2013-05-31T07:49:40
2013-05-31T07:49:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,182
py
##STOPWATCH 2.0 ## ##CREATED BY SIDDHARTH KANNAN ## ##WRITTEN ON PYTHON 2.7 AND TKINTER 8.5 ## ##OS: WINDOWS XP SP 3 ## This program is free software. It comes without any warranty, to ## the extent permitted by applicable law. You can redistribute it ## and/or modify it under the terms of the Do What The Fuck You Want ## To Public License, Version 2, as published by Sam Hocevar. See ## http://www.wtfpl.net/ for more details. from Tkinter import * from time import * from tkFont import * import tkMessageBox import tkSimpleDialog import datetime now = datetime.datetime.now() FRAME_WIDTH,FRAME_HEIGHT = 600,700 class stopwatch(object): def __init__(self): self.window = Tk() ##The main window instance self.window.title("STOPWATCH") self.firstTime = True ##Variable keeps track of whether this is the first time that the application is being run ##Some fonts for use inside self.small = Font(family='Helvetica',size=11) self.medium = Font(family='Helvetica',size=15) self.big = Font(family='Helvetica',size=24) self.shown = BooleanVar() self.shown.set(True) self.quitted = False self.initFrame() def createMenu(self,event=None): menubar = Menu(self.window) filemenu = Menu(menubar,tearoff = 0) filemenu.add_command(label='Start',command=self.startrunning,accelerator='S') filemenu.add_command(label='Stop',command=self.stoprunning,accelerator='E') filemenu.add_command(label='Lap',command=self.endlap,accelerator='L') filemenu.add_command(label='Reset',command=self.reset,accelerator='R') filemenu.add_command(label='Quit',command=self.quitwin,accelerator='Escape') optionsmenu = Menu(menubar,tearoff=0) optionsmenu.add_checkbutton(label='Show timing after the run is completed',command=self.togglePopUp,variable=self.shown,onvalue = True,offvalue = False) helpmenu = Menu(menubar,tearoff=0) helpmenu.add_command(label='Help',command=self.showHelp) helpmenu.add_command(label='About',command=self.showCredits) menubar.add_cascade(label='File',menu=filemenu) menubar.add_cascade(label='Options',menu=optionsmenu) menubar.add_cascade(label='Help',menu=helpmenu) self.window.config(menu=menubar) def initFrame(self): try: self.frame.destroy() except AttributeError: pass self.frame = Frame(self.window,width=FRAME_WIDTH,height=FRAME_HEIGHT) ##The frame instance self.frame.pack_propagate(0) ##Making sure that the window does not shrink self.frame.pack(fill=None) self.initVariables() self.initBindings() self.createMenu() self.initUI() def initVariables(self,event=None): ##VARIABLES: self.start = None self.stop = None self.timeConsumed = None self.laps = [] self.startOfLap = None self.endOfLap = None self.counterOfLaps = 1 def initBindings(self,event=None): w = self.window w.bind('s',self.startrunning) w.bind('e',self.stoprunning) w.bind('r',self.reset) w.bind('l',self.endlap) w.bind('<Escape>',self.quitwin) def initHelp(self): f = self.frame info = Message(f,text="You can use the buttons below or \ you can use the following keyboard shortcuts to work with the stopwatch\ \n\nPress \'S\' to start running. \ \nPress \'E\' to stop running. \ \nPress \'R\' to reset the stopwatch. \ \nPress \'L\' to end a lap. \ \n\nPress escape button to quit this stopwatch\ Please note that all the times generated are \ being stored in a file \'timings.txt\' from which you can see the timings later.\n\ \n\nYou can see this help again by clicking on the help tab in the menu.",\ font=self.medium) info.pack() def initUI(self): f = self.frame if self.firstTime: self.initHelp() self.firstTime = False start = Button(f,text='START',command=self.startrunning) start.pack(side="top") stop =Button(f,text='STOP',command=self.stoprunning) stop.pack(side="top") lap = Button(f,text='LAP',command=self.endlap) lap.pack(side='top') reset = Button(f,text="RESET",command = self.reset) reset.pack(side="top") close = Button(f,text="QUIT",bg="black",fg = "red",command=self.quitwin) close.pack(side="top") ##Changing the font to increase the size of the buttons buttons = [start,stop,close,reset,lap] for i in buttons: i.config(font=self.medium) def startrunning(self,event=None): self.reset() r = Frame(self.frame) r.pack() self.start = time() self.startOfLap = time() start = Label(r,text="\nStarted running") start.pack() def stoprunning(self,event=None): r = Frame(self.frame) r.pack() self.stop = time() self.timeConsumed = self.stop - self.start Label(r,text='\nstopped running').pack() end = Label(r,text="\nTime consumed is: %0.2f seconds" %self.timeConsumed) end.pack(side = "bottom") if self.shown.get(): tkMessageBox.showinfo('Summary of this run','The run was completed in %0.2f seconds' %self.timeConsumed) self.writeDataToFile() self.initVariables() def togglePopUp(self,event=None): if self.shown.get(): tkMessageBox.showinfo('Message','Pop up after run has been switched on') else: tkMessageBox.showinfo('Message','Pop up after run has been switched off') def writeDataToFile(self,event=None): inputFile = open('timings.txt','a') for i in range(60): inputFile.write('-') dateNow = 'Date:' + str(now.day) + '-' + str(now.month) + '-' \ + str(now.year) \ + ', ' + 'Time:' + str(now.hour) + ':' + str(now.minute) \ + ':' + str(now.second) inputFile.write('\n\n' + dateNow + '\n\n') for i in range(len(self.laps)): inputFile.write('Lap ' + str(i+1) + ': ' + str('%0.2f' %self.laps[i]) + ' seconds\n') if len(self.laps) == 0: inputFile.write('No laps recorded') inputFile.write('\nSummary of this run:'+str(' %0.2f' %self.timeConsumed) + ' seconds' + '\n') def reset(self,event=None): self.frame.destroy() self.initFrame() def endlap(self,event=None): self.endOfLap = time() timeTakenForOneLap = self.endOfLap - self.startOfLap self.laps.append(timeTakenForOneLap) r = Label(self.frame,text="Lap " + str(self.counterOfLaps) +" was completed in %0.2f" %timeTakenForOneLap) r.pack() self.counterOfLaps += 1 self.startOfLap = time() if self.counterOfLaps % 9 == 0: self.frame.pack_propagate(1) def showHelp(self,event=None): tkMessageBox.showinfo('Help','Application that emulates a stopwatch with lap timing facility\ \nCopyright(c) 2013 Siddharth Kannan') self.firstTime = True self.initFrame() def quitwin(self,event=None): self.window.destroy() self.window2 = Tk() self.window2.title('License and Credits') self.window2.bind('<Escape>',self.exit) self.frame =Frame(self.window2) self.frame.pack() self.r = Frame(self.frame) self.r.pack() r = self.r self.big = Font(family='Helvetica',size=24) m = Message(r,text="Created by Siddharth Kannan\ \nWritten on Python 2.7 and Tkinter 8.5\ \nOS: WINDOWS XP SP 3\ \nThis software is licensed under the WTFPL license.\ \nSee the copying file for more details.\ \nPress the quit button below to quit the application\ ",font=self.big) m.pack() b = Button(r,text='QUIT',fg='red',bg='black',command=self.window2.destroy,font=self.big) b.pack(side='bottom') def showCredits(self,event=None): self.window1 = Tk() self.window1.title('License and Credits') self.frame =Frame(self.window1) self.frame.pack() self.r = Frame(self.frame) self.r.pack() r = self.r self.big = Font(family='Helvetica',size=24) m = Message(r,text="Created by Siddharth Kannan\ \nWritten on Python 2.7 and Tkinter 8.5\ \nOS: WINDOWS XP SP 3\ \nThis software is licensed under the WTFPL license.\ \nSee the copying file for more details.\ ",font=self.big) m.pack() b = Button(r,text='OKAY',font=self.big,command=self.window1.destroy) b.pack(side='bottom') def exit(self,event=None): """the function that will kill all the processes and end the application""" self.window2.destroy() print 'This is a GUI application that has been built using Python 2.7 and Tkinter 8.5' print 'Please go to the main window titled \'STOPWATCH\' for using the application' stopwatch() mainloop() #stopwatch()
[ "kannan.siddharth12@gmail.com" ]
kannan.siddharth12@gmail.com
e82af246a4fabbf3a2ba385c7b0c50fb773c3ad8
628ec414b7807fc50de67345361e41cc68ba3720
/mayan/apps/ocr/apps.py
e1d21110b14b38c12ebf713b08bd02902cf0438c
[ "Apache-2.0" ]
permissive
TestingCodeReview/Mayan-EDMS
aafe144424ffa8128a4ff7cee24d91bf1e1f2750
d493ec34b2f93244e32e1a2a4e6cda4501d3cf4e
refs/heads/master
2020-05-27T23:34:44.118503
2019-04-05T02:04:18
2019-04-05T02:04:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,645
py
from __future__ import unicode_literals from datetime import timedelta import logging from kombu import Exchange, Queue from django.apps import apps from django.db.models.signals import post_save from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from acls import ModelPermission from common import ( MayanAppConfig, menu_facet, menu_multi_item, menu_object, menu_secondary, menu_tools ) from common.classes import ModelField from common.settings import settings_db_sync_task_delay from documents.search import document_search, document_page_search from documents.signals import post_version_upload from documents.widgets import document_link from mayan.celery import app from navigation import SourceColumn from .events import event_ocr_document_version_submit from .handlers import ( handler_index_document, handler_initialize_new_ocr_settings, handler_ocr_document_version, ) from .links import ( link_document_page_ocr_content, link_document_ocr_content, link_document_ocr_download, link_document_ocr_errors_list, link_document_submit, link_document_submit_multiple, link_document_type_ocr_settings, link_document_type_submit, link_entry_list ) from .permissions import ( permission_document_type_ocr_setup, permission_ocr_document, permission_ocr_content_view ) from .queues import * # NOQA from .signals import post_document_version_ocr from .utils import get_document_ocr_content logger = logging.getLogger(__name__) def document_ocr_submit(self): latest_version = self.latest_version # Don't error out if document has no version if latest_version: latest_version.submit_for_ocr() def document_version_ocr_submit(self): from .tasks import task_do_ocr event_ocr_document_version_submit.commit( action_object=self.document, target=self ) task_do_ocr.apply_async( eta=now() + timedelta(seconds=settings_db_sync_task_delay.value), kwargs={'document_version_pk': self.pk}, ) class OCRApp(MayanAppConfig): has_rest_api = True has_tests = True name = 'ocr' verbose_name = _('OCR') def ready(self): super(OCRApp, self).ready() Document = apps.get_model( app_label='documents', model_name='Document' ) DocumentPage = apps.get_model( app_label='documents', model_name='DocumentPage' ) DocumentType = apps.get_model( app_label='documents', model_name='DocumentType' ) DocumentTypeSettings = self.get_model( model_name='DocumentTypeSettings' ) DocumentVersion = apps.get_model( app_label='documents', model_name='DocumentVersion' ) DocumentVersionOCRError = self.get_model('DocumentVersionOCRError') Document.add_to_class('submit_for_ocr', document_ocr_submit) DocumentVersion.add_to_class( 'ocr_content', get_document_ocr_content ) DocumentVersion.add_to_class( 'submit_for_ocr', document_version_ocr_submit ) ModelField( Document, name='versions__pages__ocr_content__content' ) ModelPermission.register( model=Document, permissions=( permission_ocr_document, permission_ocr_content_view ) ) ModelPermission.register( model=DocumentType, permissions=( permission_document_type_ocr_setup, ) ) ModelPermission.register_inheritance( model=DocumentTypeSettings, related='document_type', ) SourceColumn( source=DocumentVersionOCRError, label=_('Document'), func=lambda context: document_link(context['object'].document_version.document) ) SourceColumn( source=DocumentVersionOCRError, label=_('Added'), attribute='datetime_submitted' ) SourceColumn( source=DocumentVersionOCRError, label=_('Result'), attribute='result' ) app.conf.CELERY_QUEUES.append( Queue('ocr', Exchange('ocr'), routing_key='ocr'), ) app.conf.CELERY_ROUTES.update( { 'ocr.tasks.task_do_ocr': { 'queue': 'ocr' }, } ) document_search.add_model_field( field='versions__pages__ocr_content__content', label=_('OCR') ) document_page_search.add_model_field( field='ocr_content__content', label=_('OCR') ) menu_facet.bind_links( links=(link_document_ocr_content,), sources=(Document,) ) menu_facet.bind_links( links=(link_document_page_ocr_content,), sources=(DocumentPage,) ) menu_multi_item.bind_links( links=(link_document_submit_multiple,), sources=(Document,) ) menu_object.bind_links( links=(link_document_submit,), sources=(Document,) ) menu_object.bind_links( links=(link_document_page_ocr_content,), sources=(DocumentPage,) ) menu_object.bind_links( links=(link_document_type_ocr_settings,), sources=(DocumentType,) ) menu_secondary.bind_links( links=( link_document_ocr_content, link_document_ocr_errors_list, link_document_ocr_download ), sources=( 'ocr:document_content', 'ocr:document_ocr_error_list', 'ocr:document_ocr_download', ) ) menu_secondary.bind_links( links=(link_entry_list,), sources=( 'ocr:entry_list', 'ocr:entry_delete_multiple', 'ocr:entry_re_queue_multiple', DocumentVersionOCRError ) ) menu_tools.bind_links( links=( link_document_type_submit, link_entry_list ) ) post_document_version_ocr.connect( dispatch_uid='ocr_handler_index_document', receiver=handler_index_document, sender=DocumentVersion ) post_save.connect( dispatch_uid='ocr_handler_initialize_new_ocr_settings', receiver=handler_initialize_new_ocr_settings, sender=DocumentType ) post_version_upload.connect( dispatch_uid='ocr_handler_ocr_document_version', receiver=handler_ocr_document_version, sender=DocumentVersion )
[ "roberto.rosario.gonzalez@gmail.com" ]
roberto.rosario.gonzalez@gmail.com
e74d834f30df938cbf83fabfa08b56e39b2ee9ff
268568ff2d483f39de78a5b29d941ce499cace33
/spyder/plugins/editor/utils/editor.py
234ab01fc1548bf301f06c4a28ef0661786b8b54
[ "MIT" ]
permissive
MarkMoretto/spyder-master
61e7f8007144562978da9c6adecaa3022758c56f
5f8c64edc0bbd203a97607950b53a9fcec9d2f0b
refs/heads/master
2023-01-10T16:34:37.825886
2020-08-07T19:07:56
2020-08-07T19:07:56
285,901,914
2
1
MIT
2022-12-20T13:46:41
2020-08-07T19:03:37
Python
UTF-8
Python
false
false
41,275
py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2013-2016 Colin Duquesnoy and others (see pyqode/AUTHORS.rst) # Copyright (c) 2016- Spyder Project Contributors (see AUTHORS.txt) # # Distributed under the terms of the MIT License # (see NOTICE.txt in the Spyder root directory for details) # ----------------------------------------------------------------------------- """ This module contains utility functions/classes for Spyder's Editor. Adapted from pyqode/core/api/utils.py of the `PyQode project <https://github.com/pyQode/pyQode>`_. Original file: <https://github.com/pyQode/pyqode.core/blob/master/pyqode/core/api/utils.py> """ # Standard library imports import functools import weakref # Third party imports from qtpy.QtCore import QTimer, Qt from qtpy.QtGui import (QColor, QTextBlockUserData, QTextCursor, QTextBlock, QTextDocument, QCursor) from qtpy.QtWidgets import QApplication # Local imports from spyder.py3compat import to_text_string def drift_color(base_color, factor=110): """ Return color that is lighter or darker than the base color. If base_color.lightness is higher than 128, the returned color is darker otherwise is is lighter. :param base_color: The base color to drift from ;:param factor: drift factor (%) :return A lighter or darker color. """ base_color = QColor(base_color) if base_color.lightness() > 128: return base_color.darker(factor) else: if base_color == QColor('#000000'): return drift_color(QColor('#101010'), factor + 20) else: return base_color.lighter(factor + 10) class BlockUserData(QTextBlockUserData): def __init__(self, editor, color=None, selection_start=None, selection_end=None): QTextBlockUserData.__init__(self) self.editor = editor self.breakpoint = False self.breakpoint_condition = None self.bookmarks = [] self.code_analysis = [] self.todo = '' self.color = color self.oedata = None self.import_statement = None self.selection_start = selection_start self.selection_end = selection_end # Add a reference to the user data in the editor as the block won't. # The list should /not/ be used to list BlockUserData as the blocks # they refer to might not exist anymore. # This prevent a segmentation fault. if editor is None: # Won't be destroyed self.refloop = self return # Destroy with the editor if not hasattr(editor, '_user_data_reference_list'): editor._user_data_reference_list = [] editor._user_data_reference_list.append(self) def _selection(self): """ Function to compute the selection. This is slow to call so it is only called when needed. """ if self.selection_start is None or self.selection_end is None: return None document = self.editor.document() cursor = self.editor.textCursor() block = document.findBlockByNumber(self.selection_start['line']) cursor.setPosition(block.position()) cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition( QTextCursor.NextCharacter, n=self.selection_start['character']) block2 = document.findBlockByNumber( self.selection_end['line']) cursor.setPosition(block2.position(), QTextCursor.KeepAnchor) cursor.movePosition( QTextCursor.StartOfBlock, mode=QTextCursor.KeepAnchor) cursor.movePosition( QTextCursor.NextCharacter, n=self.selection_end['character'], mode=QTextCursor.KeepAnchor) return QTextCursor(cursor) class DelayJobRunner(object): """ Utility class for running job after a certain delay. If a new request is made during this delay, the previous request is dropped and the timer is restarted for the new request. We use this to implement a cooldown effect that prevents jobs from being executed while the IDE is not idle. A job is a simple callable. """ def __init__(self, delay=500): """ :param delay: Delay to wait before running the job. This delay applies to all requests and cannot be changed afterwards. """ self._timer = QTimer() self.delay = delay self._timer.timeout.connect(self._exec_requested_job) self._args = [] self._kwargs = {} self._job = lambda x: None def request_job(self, job, *args, **kwargs): """ Request a job execution. The job will be executed after the delay specified in the DelayJobRunner contructor elapsed if no other job is requested until then. :param job: job. :type job: callable :param args: job's position arguments :param kwargs: job's keyworded arguments """ self.cancel_requests() self._job = job self._args = args self._kwargs = kwargs self._timer.start(self.delay) def cancel_requests(self): """Cancels pending requests.""" self._timer.stop() self._job = None self._args = None self._kwargs = None def _exec_requested_job(self): """Execute the requested job after the timer has timeout.""" self._timer.stop() self._job(*self._args, **self._kwargs) class TextHelper(object): """ Text helper helps you manipulate the content of CodeEditor and extends the Qt text api for an easier usage. FIXME: Some of this methods are already implemented in CodeEditor, move and unify redundant methods. """ @property def _editor(self): try: return self._editor_ref() except TypeError: return self._editor_ref def __init__(self, editor): """:param editor: The editor to work on.""" try: self._editor_ref = weakref.ref(editor) except TypeError: self._editor_ref = editor def goto_line(self, line, column=0, end_column=0, move=True, word=''): """ Moves the text cursor to the specified position. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :param word: Highlight the word, when moving to the line. :return: The new text cursor :rtype: QtGui.QTextCursor """ line = min(line, self.line_count()) text_cursor = self._move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if end_column: text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor, end_column) if move: block = text_cursor.block() self.unfold_if_colapsed(block) self._editor.setTextCursor(text_cursor) if self._editor.isVisible(): self._editor.centerCursor() else: self._editor.focus_in.connect( self._editor.center_cursor_on_next_focus) if word and to_text_string(word) in to_text_string(block.text()): self._editor.find(word, QTextDocument.FindCaseSensitively) return text_cursor def unfold_if_colapsed(self, block): """Unfold parent fold trigger if the block is collapsed. :param block: Block to unfold. """ try: folding_panel = self._editor.panels.get('FoldingPanel') except KeyError: pass else: if block.isVisible(): return block = folding_panel.find_parent_scope(block) folding_panel.toggle_fold_trigger(block) def selected_text(self): """Returns the selected text.""" return self._editor.textCursor().selectedText() def word_under_cursor(self, select_whole_word=False, text_cursor=None): """ Gets the word under cursor using the separators defined by :attr:`spyder.plugins.editor.widgets.codeeditor.CodeEditor.word_separators`. FIXME: This is not working because CodeEditor have no attribute word_separators .. note: Instead of returning the word string, this function returns a QTextCursor, that way you may get more information than just the string. To get the word, just call ``selectedText`` on the returned value. :param select_whole_word: If set to true the whole word is selected, else the selection stops at the cursor position. :param text_cursor: Optional custom text cursor (e.g. from a QTextDocument clone) :returns: The QTextCursor that contains the selected word. """ editor = self._editor if not text_cursor: text_cursor = editor.textCursor() word_separators = editor.word_separators end_pos = start_pos = text_cursor.position() # select char by char until we are at the original cursor position. while not text_cursor.atStart(): text_cursor.movePosition( text_cursor.Left, text_cursor.KeepAnchor, 1) try: char = text_cursor.selectedText()[0] word_separators = editor.word_separators selected_txt = text_cursor.selectedText() if (selected_txt in word_separators and (selected_txt != "n" and selected_txt != "t") or char.isspace()): break # start boundary found except IndexError: break # nothing selectable start_pos = text_cursor.position() text_cursor.setPosition(start_pos) if select_whole_word: # select the resot of the word text_cursor.setPosition(end_pos) while not text_cursor.atEnd(): text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor, 1) char = text_cursor.selectedText()[0] selected_txt = text_cursor.selectedText() if (selected_txt in word_separators and (selected_txt != "n" and selected_txt != "t") or char.isspace()): break # end boundary found end_pos = text_cursor.position() text_cursor.setPosition(end_pos) # now that we habe the boundaries, we can select the text text_cursor.setPosition(start_pos) text_cursor.setPosition(end_pos, text_cursor.KeepAnchor) return text_cursor def word_under_mouse_cursor(self): """ Selects the word under the **mouse** cursor. :return: A QTextCursor with the word under mouse cursor selected. """ editor = self._editor text_cursor = editor.cursorForPosition(editor._last_mouse_pos) text_cursor = self.word_under_cursor(True, text_cursor) return text_cursor def cursor_position(self): """ Returns the QTextCursor position. The position is a tuple made up of the line number (0 based) and the column number (0 based). :return: tuple(line, column) """ return (self._editor.textCursor().blockNumber(), self._editor.textCursor().columnNumber()) def current_line_nbr(self): """ Returns the text cursor's line number. :return: Line number """ return self.cursor_position()[0] def current_column_nbr(self): """ Returns the text cursor's column number. :return: Column number """ return self.cursor_position()[1] def line_count(self): """ Returns the line count of the specified editor. :return: number of lines in the document. """ return self._editor.document().blockCount() def line_text(self, line_nbr): """ Gets the text of the specified line. :param line_nbr: The line number of the text to get :return: Entire line's text :rtype: str """ doc = self._editor.document() block = doc.findBlockByNumber(line_nbr) return block.text() def previous_line_text(self): """ Gets the previous line text (relative to the current cursor pos). :return: previous line text (str) """ if self.current_line_nbr(): return self.line_text(self.current_line_nbr() - 1) return '' def current_line_text(self): """ Returns the text of the current line. :return: Text of the current line """ return self.line_text(self.current_line_nbr()) def set_line_text(self, line_nbr, new_text): """ Replace an entire line with ``new_text``. :param line_nbr: line number of the line to change. :param new_text: The replacement text. """ editor = self._editor text_cursor = self._move_cursor_to(line_nbr) text_cursor.select(text_cursor.LineUnderCursor) text_cursor.insertText(new_text) editor.setTextCursor(text_cursor) def remove_last_line(self): """Removes the last line of the document.""" editor = self._editor text_cursor = editor.textCursor() text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor) text_cursor.select(text_cursor.LineUnderCursor) text_cursor.removeSelectedText() text_cursor.deletePreviousChar() editor.setTextCursor(text_cursor) def clean_document(self): """ Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocument. FIXME: It was deprecated in pyqode, maybe It should be deleted """ editor = self._editor value = editor.verticalScrollBar().value() pos = self.cursor_position() editor.textCursor().beginEditBlock() # cleanup whitespaces editor._cleaning = True eaten = 0 removed = set() for line in editor._modified_lines: # parse line before and line after modified line (for cases where # key_delete or key_return has been pressed) for j in range(-1, 2): # skip current line if line + j != pos[0]: if line + j >= 0: txt = self.line_text(line + j) stxt = txt.rstrip() if txt != stxt: self.set_line_text(line + j, stxt) removed.add(line + j) editor._modified_lines -= removed # ensure there is only one blank line left at the end of the file i = self.line_count() while i: line = self.line_text(i - 1) if line.strip(): break self.remove_last_line() i -= 1 if self.line_text(self.line_count() - 1): editor.appendPlainText('') # restore cursor and scrollbars text_cursor = editor.textCursor() doc = editor.document() assert isinstance(doc, QTextDocument) text_cursor = self._move_cursor_to(pos[0]) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.MoveAnchor) cpos = text_cursor.position() text_cursor.select(text_cursor.LineUnderCursor) if text_cursor.selectedText(): text_cursor.setPosition(cpos) offset = pos[1] - eaten text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, offset) else: text_cursor.setPosition(cpos) editor.setTextCursor(text_cursor) editor.verticalScrollBar().setValue(value) text_cursor.endEditBlock() editor._cleaning = False editor.document_did_change() def select_whole_line(self, line=None, apply_selection=True): """ Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor """ if line is None: line = self.current_line_nbr() return self.select_lines(line, line, apply_selection=apply_selection) def _move_cursor_to(self, line): cursor = self._editor.textCursor() block = self._editor.document().findBlockByNumber(line-1) cursor.setPosition(block.position()) return cursor def select_lines(self, start=0, end=-1, apply_selection=True): """ Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being applied on the code editor widget by setting ``apply_selection`` to False. :param start: Start line number (0 based) :param end: End line number (0 based). Use -1 to select up to the end of the document :param apply_selection: True to apply the selection before returning the QTextCursor. :returns: A QTextCursor that holds the requested selection """ editor = self._editor if end == -1: end = self.line_count() - 1 if start < 0: start = 0 text_cursor = self._move_cursor_to(start) if end > start: # Going down text_cursor.movePosition(text_cursor.Down, text_cursor.KeepAnchor, end - start) text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) elif end < start: # going up # don't miss end of line ! text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.MoveAnchor) text_cursor.movePosition(text_cursor.Up, text_cursor.KeepAnchor, start - end) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.KeepAnchor) else: text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) if apply_selection: editor.setTextCursor(text_cursor) return text_cursor def selection_range(self): """ Returns the selected lines boundaries (start line, end line) :return: tuple(int, int) """ editor = self._editor doc = editor.document() start = doc.findBlock( editor.textCursor().selectionStart()).blockNumber() end = doc.findBlock( editor.textCursor().selectionEnd()).blockNumber() text_cursor = QTextCursor(editor.textCursor()) text_cursor.setPosition(editor.textCursor().selectionEnd()) if text_cursor.columnNumber() == 0 and start != end: end -= 1 return start, end def line_pos_from_number(self, line_number): """ Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line. """ editor = self._editor block = editor.document().findBlockByNumber(line_number) if block.isValid(): return int(editor.blockBoundingGeometry(block).translated( editor.contentOffset()).top()) if line_number <= 0: return 0 else: return int(editor.blockBoundingGeometry( block.previous()).translated(editor.contentOffset()).bottom()) def line_nbr_from_position(self, y_pos): """ Returns the line number from the y_pos. :param y_pos: Y pos in the editor :return: Line number (0 based), -1 if out of range """ editor = self._editor height = editor.fontMetrics().height() for top, line, block in editor.visible_blocks: if top <= y_pos <= top + height: return line return -1 def mark_whole_doc_dirty(self): """ Marks the whole document as dirty to force a full refresh. **SLOW** """ text_cursor = self._editor.textCursor() text_cursor.select(text_cursor.Document) self._editor.document().markContentsDirty(text_cursor.selectionStart(), text_cursor.selectionEnd()) def line_indent(self, line_nbr=None): """ Returns the indent level of the specified line. :param line_nbr: Number of the line to get indentation (1 base). Pass None to use the current line number. Note that you can also pass a QTextBlock instance instead of an int. :return: Number of spaces that makes the indentation level of the current line """ if line_nbr is None: line_nbr = self.current_line_nbr() elif isinstance(line_nbr, QTextBlock): line_nbr = line_nbr.blockNumber() line = self.line_text(line_nbr) indentation = len(line) - len(line.lstrip()) return indentation def get_right_word(self, cursor=None): """ Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor. """ if cursor is None: cursor = self._editor.textCursor() cursor.movePosition(QTextCursor.WordRight, QTextCursor.KeepAnchor) return cursor.selectedText().strip() def get_right_character(self, cursor=None): """ Gets the character that is on the right of the text cursor. :param cursor: QTextCursor that defines the position where the search will start. """ next_char = self.get_right_word(cursor=cursor) if len(next_char): next_char = next_char[0] else: next_char = None return next_char def insert_text(self, text, keep_position=True): """ Inserts text at the cursor position. :param text: text to insert :param keep_position: Flag that specifies if the cursor position must be kept. Pass False for a regular insert (the cursor will be at the end of the inserted text). """ text_cursor = self._editor.textCursor() if keep_position: s = text_cursor.selectionStart() e = text_cursor.selectionEnd() text_cursor.insertText(text) if keep_position: text_cursor.setPosition(s) text_cursor.setPosition(e, text_cursor.KeepAnchor) self._editor.setTextCursor(text_cursor) self._editor.document_did_change() def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor) def move_right(self, keep_anchor=False, nb_chars=1): """ Moves the cursor on the right. :param keep_anchor: True to keep anchor (to select text) or False to move the anchor (no selection) :param nb_chars: Number of characters to move. """ text_cursor = self._editor.textCursor() text_cursor.movePosition( text_cursor.Right, text_cursor.KeepAnchor if keep_anchor else text_cursor.MoveAnchor, nb_chars) self._editor.setTextCursor(text_cursor) def selected_text_to_lower(self): """Replaces the selected text by its lower version.""" txt = self.selected_text() self.insert_text(txt.lower()) def selected_text_to_upper(self): """Replaces the selected text by its upper version.""" txt = self.selected_text() self.insert_text(txt.upper()) def search_text(self, text_cursor, search_txt, search_flags): """ Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occurrence index :rtype: tuple([], int) """ def compare_cursors(cursor_a, cursor_b): """ Compares two QTextCursor. :param cursor_a: cursor a :param cursor_b: cursor b :returns; True if both cursor are identical (same position, same selection) """ return (cursor_b.selectionStart() >= cursor_a.selectionStart() and cursor_b.selectionEnd() <= cursor_a.selectionEnd()) text_document = self._editor.document() occurrences = [] index = -1 cursor = text_document.find(search_txt, 0, search_flags) original_cursor = text_cursor while not cursor.isNull(): if compare_cursors(cursor, original_cursor): index = len(occurrences) occurrences.append((cursor.selectionStart(), cursor.selectionEnd())) cursor.setPosition(cursor.position() + 1) cursor = text_document.find(search_txt, cursor, search_flags) return occurrences, index def is_comment_or_string(self, cursor_or_block, formats=None): """ Checks if a block/cursor is a string or a comment. :param cursor_or_block: QTextCursor or QTextBlock :param formats: the list of color scheme formats to consider. By default, it will consider the following keys: 'comment', 'string', 'docstring'. """ if formats is None: formats = ["comment", "string", "docstring"] layout = None pos = 0 if isinstance(cursor_or_block, QTextBlock): pos = len(cursor_or_block.text()) - 1 layout = cursor_or_block.layout() elif isinstance(cursor_or_block, QTextCursor): b = cursor_or_block.block() pos = cursor_or_block.position() - b.position() layout = b.layout() if layout is not None: additional_formats = layout.additionalFormats() sh = self._editor.syntax_highlighter if sh: ref_formats = sh.color_scheme.formats for r in additional_formats: if r.start <= pos < (r.start + r.length): for fmt_type in formats: is_user_obj = (r.format.objectType() == r.format.UserObject) if (ref_formats[fmt_type] == r.format and is_user_obj): return True return False def select_extended_word(self, continuation_chars=('.',)): """ Performs extended word selection. Extended selection consists in selecting the word under cursor and any other words that are linked by a ``continuation_chars``. :param continuation_chars: the list of characters that may extend a word. """ cursor = self._editor.textCursor() original_pos = cursor.position() start_pos = None end_pos = None # go left stop = False seps = self._editor.word_separators + [' '] while not stop: cursor.clearSelection() cursor.movePosition(cursor.Left, cursor.KeepAnchor) char = cursor.selectedText() if cursor.atBlockStart(): stop = True start_pos = cursor.position() elif char in seps and char not in continuation_chars: stop = True start_pos = cursor.position() + 1 # go right cursor.setPosition(original_pos) stop = False while not stop: cursor.clearSelection() cursor.movePosition(cursor.Right, cursor.KeepAnchor) char = cursor.selectedText() if cursor.atBlockEnd(): stop = True end_pos = cursor.position() if char in seps: end_pos -= 1 elif char in seps and char not in continuation_chars: stop = True end_pos = cursor.position() - 1 if start_pos and end_pos: cursor.setPosition(start_pos) cursor.movePosition(cursor.Right, cursor.KeepAnchor, end_pos - start_pos) self._editor.setTextCursor(cursor) def match_select(self, ignored_symbols=None): """ Performs matched selection, selects text between matching quotes or parentheses. :param ignored_symbols; matching symbols to ignore. """ def filter_matching(ignored_symbols, matching): """ Removes any ignored symbol from the match dict. """ if ignored_symbols is not None: for symbol in matching.keys(): if symbol in ignored_symbols: matching.pop(symbol) return matching def find_opening_symbol(cursor, matching): """ Find the position ot the opening symbol :param cursor: Current text cursor :param matching: symbol matches map """ start_pos = None opening_char = None closed = {k: 0 for k in matching.values() if k not in ['"', "'"]} # go left stop = False while not stop and not cursor.atStart(): cursor.clearSelection() cursor.movePosition(cursor.Left, cursor.KeepAnchor) char = cursor.selectedText() if char in closed.keys(): closed[char] += 1 elif char in matching.keys(): opposite = matching[char] if opposite in closed.keys() and closed[opposite]: closed[opposite] -= 1 continue else: # found opening quote or parenthesis start_pos = cursor.position() + 1 stop = True opening_char = char return opening_char, start_pos def find_closing_symbol(cursor, matching, opening_char, original_pos): """ Finds the position of the closing symbol. :param cursor: current text cursor :param matching: symbold matching dict :param opening_char: the opening character :param original_pos: position of the opening character. """ end_pos = None cursor.setPosition(original_pos) rev_matching = {v: k for k, v in matching.items()} opened = {k: 0 for k in rev_matching.values() if k not in ['"', "'"]} stop = False while not stop and not cursor.atEnd(): cursor.clearSelection() cursor.movePosition(cursor.Right, cursor.KeepAnchor) char = cursor.selectedText() if char in opened.keys(): opened[char] += 1 elif char in rev_matching.keys(): opposite = rev_matching[char] if opposite in opened.keys() and opened[opposite]: opened[opposite] -= 1 continue elif matching[opening_char] == char: # found opening quote or parenthesis end_pos = cursor.position() - 1 stop = True return end_pos matching = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'"} filter_matching(ignored_symbols, matching) cursor = self._editor.textCursor() original_pos = cursor.position() end_pos = None opening_char, start_pos = find_opening_symbol(cursor, matching) if opening_char: end_pos = find_closing_symbol( cursor, matching, opening_char, original_pos) if start_pos and end_pos: cursor.setPosition(start_pos) cursor.movePosition(cursor.Right, cursor.KeepAnchor, end_pos - start_pos) self._editor.setTextCursor(cursor) return True else: return False class TextBlockHelper(object): """ Helps retrieving the various part of the user state bitmask. This helper should be used to replace calls to ``QTextBlock.setUserState``/``QTextBlock.getUserState`` as well as ``QSyntaxHighlighter.setCurrentBlockState``/ ``QSyntaxHighlighter.currentBlockState`` and ``QSyntaxHighlighter.previousBlockState``. The bitmask is made up of the following fields: - bit0 -> bit26: User state (for syntax highlighting) - bit26: fold trigger state - bit27-bit29: fold level (8 level max) - bit30: fold trigger flag - bit0 -> bit15: 16 bits for syntax highlighter user state ( for syntax highlighting) - bit16-bit25: 10 bits for the fold level (1024 levels) - bit26: 1 bit for the fold trigger flag (trigger or not trigger) - bit27: 1 bit for the fold trigger state (expanded/collapsed) """ @staticmethod def get_state(block): """ Gets the user state, generally used for syntax highlighting. :param block: block to access :return: The block state """ if block is None: return -1 state = block.userState() if state == -1: return state return state & 0x0000FFFF @staticmethod def set_state(block, state): """ Sets the user state, generally used for syntax highlighting. :param block: block to modify :param state: new state value. :return: """ if block is None: return user_state = block.userState() if user_state == -1: user_state = 0 higher_part = user_state & 0x7FFF0000 state &= 0x0000FFFF state |= higher_part block.setUserState(state) @staticmethod def get_fold_lvl(block): """ Gets the block fold level. :param block: block to access. :returns: The block fold level """ if block is None: return 0 state = block.userState() if state == -1: state = 0 return (state & 0x03FF0000) >> 16 @staticmethod def set_fold_lvl(block, val): """ Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7] """ if block is None: return state = block.userState() if state == -1: state = 0 if val >= 0x3FF: val = 0x3FF state &= 0x7C00FFFF state |= val << 16 block.setUserState(state) @staticmethod def is_fold_trigger(block): """ Checks if the block is a fold trigger. :param block: block to check :return: True if the block is a fold trigger (represented as a node in the fold panel) """ if block is None: return False state = block.userState() if state == -1: state = 0 return bool(state & 0x04000000) @staticmethod def set_fold_trigger(block, val): """ Set the block fold trigger flag (True means the block is a fold trigger). :param block: block to set :param val: value to set """ if block is None: return state = block.userState() if state == -1: state = 0 state &= 0x7BFFFFFF state |= int(val) << 26 block.setUserState(state) @staticmethod def is_collapsed(block): """ Checks if the block is expanded or collased. :param block: QTextBlock :return: False for an open trigger, True for for closed trigger """ if block is None: return False state = block.userState() if state == -1: state = 0 return bool(state & 0x08000000) @staticmethod def set_collapsed(block, val): """ Sets the fold trigger state (collapsed or expanded). :param block: The block to modify :param val: The new trigger state (True=collapsed, False=expanded) """ if block is None: return state = block.userState() if state == -1: state = 0 state &= 0x77FFFFFF state |= int(val) << 27 block.setUserState(state) class ParenthesisInfo(object): """ Stores information about a parenthesis in a line of code. """ def __init__(self, pos, char): #: Position of the parenthesis, expressed as a number of character self.position = pos #: The parenthesis character, one of "(", ")", "{", "}", "[", "]" self.character = char def get_block_symbol_data(editor, block): """ Gets the list of ParenthesisInfo for specific text block. :param editor: Code editor instance :param block: block to parse """ def list_symbols(editor, block, character): """ Retuns a list of symbols found in the block text :param editor: code editor instance :param block: block to parse :param character: character to look for. """ text = block.text() symbols = [] cursor = QTextCursor(block) cursor.movePosition(cursor.StartOfBlock) pos = text.find(character, 0) cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos) while pos != -1: if not TextHelper(editor).is_comment_or_string(cursor): # skips symbols in string literal or comment info = ParenthesisInfo(pos, character) symbols.append(info) pos = text.find(character, pos + 1) cursor.movePosition(cursor.StartOfBlock) cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos) return symbols parentheses = sorted( list_symbols(editor, block, '(') + list_symbols(editor, block, ')'), key=lambda x: x.position) square_brackets = sorted( list_symbols(editor, block, '[') + list_symbols(editor, block, ']'), key=lambda x: x.position) braces = sorted( list_symbols(editor, block, '{') + list_symbols(editor, block, '}'), key=lambda x: x.position) return parentheses, square_brackets, braces def keep_tc_pos(func): """ Cache text cursor position and restore it when the wrapped function exits. This decorator can only be used on modes or panels. :param func: wrapped function """ @functools.wraps(func) def wrapper(editor, *args, **kwds): """ Decorator """ sb = editor.verticalScrollBar() spos = sb.sliderPosition() pos = editor.textCursor().position() retval = func(editor, *args, **kwds) text_cursor = editor.textCursor() text_cursor.setPosition(pos) editor.setTextCursor(text_cursor) sb.setSliderPosition(spos) return retval return wrapper def with_wait_cursor(func): """ Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param func: wrapped function """ @functools.wraps(func) def wrapper(*args, **kwargs): QApplication.setOverrideCursor( QCursor(Qt.WaitCursor)) try: ret_val = func(*args, **kwargs) finally: QApplication.restoreOverrideCursor() return ret_val return wrapper
[ "mark.moretto@forcepoint.com" ]
mark.moretto@forcepoint.com
152ffb10dc25b1ca59f9931e30c3976970cc1f2a
e754658e64e2bf6361fb01dcdf52d3f7364c2dae
/geemap/__init__.py
dbd53ffe9b416156f0132ee9ae815c0684ad3764
[ "MIT" ]
permissive
wha7/geemap
ad4f00163d8a13aac583b32e74916ac5011877cf
57f1cb182ac51e9560976ac1452b28beee6d5312
refs/heads/master
2023-01-08T08:45:24.860924
2020-11-06T04:03:28
2020-11-06T04:03:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
220
py
"""Top-level package for geemap.""" __author__ = """Qiusheng Wu""" __email__ = "giswqs@gmail.com" __version__ = "0.8.1" from .geemap import * # from .basemaps import ee_basemaps # from .legends import builtin_legends
[ "giswqs@gmail.com" ]
giswqs@gmail.com
4595a184419af2980cd94de30541698d57fcb270
97fbcd3e36f8a4fbe02c03f3433107be597cd5db
/anvil/type_utils.py
84f09746a037b710fd1b3ff63588ed9c69dbfca8
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jzako/anvil
049f04eb49d13ea12bb9d65cc2f0650cef575490
1bbe7a5059fcaba5f6f8c84b01dbf44fcccf9d8a
refs/heads/master
2021-01-22T14:20:27.198719
2015-10-20T20:24:37
2015-10-20T20:24:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,332
py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Yahoo! 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. import types def make_bool(val): if isinstance(val, bool): return val if isinstance(val, types.NoneType): return False sval = str(val).lower().strip() if sval in ['true', '1', 'on', 'yes', 't']: return True if sval in ['0', 'false', 'off', 'no', 'f', '', 'none']: return False raise TypeError("Unable to convert %r to a boolean" % (val)) def obj_name(obj): if isinstance(obj, (types.TypeType, types.ModuleType, types.FunctionType, types.LambdaType)): return str(obj.__name__) return obj_name(obj.__class__)
[ "harlowja@yahoo-inc.com" ]
harlowja@yahoo-inc.com
923de07c828013eb85346a55e30a0a84ed441652
d99e5b65624f115db6982dd88af9390e8d766042
/tensorflow/contrib/solvers/python/ops/lanczos.py
e2eba0d999f3458f68d3d068b11cef2a0e0202fe
[ "Apache-2.0" ]
permissive
golbin/tensorflow
03dbecb6f093f5628c072086c780659bcc14dba8
8a58a304bdcf909f8b55ec49e9280fc3af01c7d3
refs/heads/master
2021-01-12T07:05:41.360503
2016-12-20T00:15:41
2016-12-20T00:15:41
76,907,006
2
0
null
2016-12-19T23:58:44
2016-12-19T23:58:43
null
UTF-8
Python
false
false
9,296
py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Lanczos algorithms.""" # TODO(rmlarsen): Add implementation of symmetric Lanczos algorithm. from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import tensorflow as tf from tensorflow.contrib.solvers.python.ops import util def lanczos_bidiag(operator, k, orthogonalize=True, starting_vector=None, name="lanczos_bidiag"): """Computes a Lanczos bidiagonalization for a linear operator. Computes matrices `U` of shape `[m, k+1]`, `V` of shape `[n, k]` and lower bidiagonal matrix `B` of shape `[k+1, k]`, that satisfy the equations `A * V = U * B` and `A' * U[:, :-1] = V * B[:-1, :]'`. The columns of `U` are orthonormal and form a basis for the Krylov subspace `K(A*A', U[:,0])`. The columns of `V` are orthonormal and form a basis for the Krylov subspace `K(A'*A, A' U[:,0])`. Args: operator: An object representing a linear operator with attributes: - shape: Either a list of integers or a 1-D `Tensor` of type `int32` of length 2. `shape[0]` is the dimension on the domain of the operator, `shape[1]` is the dimension of the co-domain of the operator. On other words, if operator represents an M x N matrix A, `shape` must contain `[M, N]`. - dtype: The datatype of input to and output from `apply` and `apply_adjoint`. - apply: Callable object taking a vector `x` as input and returning a vector with the result of applying the operator to `x`, i.e. if `operator` represents matrix `A`, `apply` should return `A * x`. - apply_adjoint: Callable object taking a vector `x` as input and returning a vector with the result of applying the adjoint operator to `x`, i.e. if `operator` represents matrix `A`, `apply_adjoint` should return `conj(transpose(A)) * x`. k: An integer or a scalar Tensor of type `int32`. Determines the maximum number of steps to run. If an invariant subspace is found, the algorithm may terminate before `k` steps have been run. orthogonalize: If `True`, perform full orthogonalization. If `False` no orthogonalization is performed. starting_vector: If not null, must be a `Tensor` of shape `[n]`. name: A name scope for the operation. Returns: output: A namedtuple representing a Lanczos bidiagonalization of `operator` with attributes: u: A rank-2 `Tensor` of type `operator.dtype` and shape `[operator.shape[0], k_actual+1]`, where `k_actual` is the number of steps run. v: A rank-2 `Tensor` of type `operator.dtype` and shape `[operator.shape[1], k_actual]`, where `k_actual` is the number of steps run. alpha: A rank-1 `Tensor` of type `operator.dtype` and shape `[k]`. beta: A rank-1 `Tensor` of type `operator.dtype` and shape `[k]`. """ def tarray(size, dtype, name): return tf.TensorArray( dtype=dtype, size=size, tensor_array_name=name, clear_after_read=False) # Reads a row-vector at location i in tarray and returns it as a # column-vector. def read_colvec(tarray, i): return tf.expand_dims(tarray.read(i), -1) # Writes an column-vector as a row-vecor at location i in tarray. def write_colvec(tarray, colvec, i): return tarray.write(i, tf.squeeze(colvec)) # Ephemeral class holding Lanczos bidiagonalization state: # u = left Lanczos vectors # v = right Lanczos vectors # alpha = diagonal of B_k. # beta = subdiagonal of B_k. # Notice that we store the left and right Lanczos vectors as the _rows_ # of u and v. This is done because tensors are stored row-major and # TensorArray only supports packing along dimension 0. lanzcos_bidiag_state = collections.namedtuple("LanczosBidiagState", ["u", "v", "alpha", "beta"]) def update_state(old, i, u, v, alpha, beta): return lanzcos_bidiag_state( write_colvec(old.u, u, i + 1), write_colvec(old.v, v, i), old.alpha.write(i, alpha), old.beta.write(i, beta)) def gram_schmidt_step(j, basis, v): """Makes v orthogonal to the j'th vector in basis.""" v_shape = v.get_shape() basis_vec = read_colvec(basis, j) v -= tf.matmul(basis_vec, v, adjoint_a=True) * basis_vec v.set_shape(v_shape) return j + 1, basis, v def orthogonalize_once(i, basis, v): j = tf.constant(0, dtype=tf.int32) _, _, v = tf.while_loop(lambda j, basis, v: j < i, gram_schmidt_step, [j, basis, v]) return util.l2normalize(v) # Iterated modified Gram-Schmidt orthogonalization adapted from PROPACK. # TODO(rmlarsen): This is possibly the slowest implementation of # iterated Gram-Schmidt orthogonalization since the abacus. Move to C++. def orthogonalize_(i, basis, v): v_norm = util.l2norm(v) v_new, v_new_norm = orthogonalize_once(i, basis, v) # If the norm decreases more than 1/sqrt(2), run a second # round of MGS. See proof in: # B. N. Parlett, ``The Symmetric Eigenvalue Problem'', # Prentice-Hall, Englewood Cliffs, NJ, 1980. pp. 105-109 return tf.cond(v_new_norm < 0.7071 * v_norm, lambda: orthogonalize_once(i, basis, v), lambda: (v_new, v_new_norm)) def stopping_criterion(i, _): # TODO(rmlarsen): Stop if an invariant subspace is detected. return i < k def lanczos_bidiag_step(i, ls): """Extends the Lanczos bidiagonalization ls by one step.""" u = read_colvec(ls.u, i) r = operator.apply_adjoint(u) # The shape inference doesn't work across cond, save and reapply the shape. r_shape = r.get_shape() r = tf.cond( i > 0, lambda: r - ls.beta.read(i - 1) * read_colvec(ls.v, i - 1), lambda: r) r.set_shape(r_shape) if orthogonalize: v, alpha = orthogonalize_(i - 1, ls.v, r) else: v, alpha = util.l2normalize(r) p = operator.apply(v) - alpha * u if orthogonalize: u, beta = orthogonalize_(i, ls.u, p) else: u, beta = util.l2normalize(p) return i + 1, update_state(ls, i, u, v, alpha, beta) with tf.name_scope(name): dtype = operator.dtype if starting_vector is None: starting_vector = tf.random_uniform( operator.shape[:1], -1, 1, dtype=dtype) u0, _ = util.l2normalize(starting_vector) ls = lanzcos_bidiag_state( u=write_colvec(tarray(k + 1, dtype, "u"), u0, 0), v=tarray(k, dtype, "v"), alpha=tarray(k, dtype, "alpha"), beta=tarray(k, dtype, "beta")) i = tf.constant(0, dtype=tf.int32) _, ls = tf.while_loop(stopping_criterion, lanczos_bidiag_step, [i, ls]) return lanzcos_bidiag_state( tf.matrix_transpose(ls.u.stack()), tf.matrix_transpose(ls.v.stack()), ls.alpha.stack(), ls.beta.stack()) # TODO(rmlarsen): Implement C++ ops for handling bidiagonal matrices # efficiently. Such a module should provide # - multiplication, # - linear system solution by back-substitution, # - QR factorization, # - SVD. def bidiag_matmul(matrix, alpha, beta, adjoint_b=False, name="bidiag_matmul"): """Multiplies a matrix by a bidiagonal matrix. alpha and beta are length k vectors representing the diagonal and first lower subdiagonal of (K+1) x K matrix B. If adjoint_b is False, computes A * B as follows: A * B = A[:, :-1] * diag(alpha) + A[:, 1:] * diag(beta) If adjoint_b is True, computes A * B[:-1, :]' as follows A * B[:-1, :]' = A * diag(alpha) + [zeros(m,1), A[:, :-1] * diag(beta[:-1])] Args: matrix: A rank-2 `Tensor` representing matrix A. alpha: A rank-1 `Tensor` representing the diagonal of B. beta: A rank-1 `Tensor` representing the lower subdiagonal diagonal of B. adjoint_b: `bool` determining what to compute. name: A name scope for the operation. Returns: If `adjoint_b` is False the `A * B` is returned. If `adjoint_b` is True the `A * B'` is returned. """ with tf.name_scope(name): alpha = tf.expand_dims(alpha, 0) if adjoint_b is False: beta = tf.expand_dims(beta, 0) return matrix[:, :-1] * alpha + matrix[:, 1:] * beta else: beta = tf.expand_dims(beta[:-1], 0) shape = tf.shape(matrix) zero_column = tf.expand_dims(tf.zeros(shape[:1], dtype=matrix.dtype), 1) return matrix * alpha + tf.concat_v2([zero_column, matrix[:, :-1] * beta], 1)
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
8cac4526b7a7108207dd13871b04a87c0ec849b3
22be44dce81f6c0ac9f891e1661118299e4feaf1
/labs/src/A.0.HelloPython/startingpoint/main.py
807eef2c1b435052d484207f144f158a3277586d
[]
no_license
KathiW/python_foundations
18a1b24a140e8f3e482a1581986c9bafd64565ff
02b6d5b2532fb9c71a497ab1fe506a7d70bc13e1
refs/heads/main
2023-02-19T10:47:02.391016
2021-01-20T13:00:51
2021-01-20T13:00:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
182
py
min_possible=1 max_possible=100 print("Think of a whole number between 1 and 100.") print("Then I'll try to guess it.") print("Ready?") print('\n\nTODO:Implement this game\n\n')
[ "you@example.com" ]
you@example.com
40f444b118b051a4a4b714f45b5074514526826d
7bb3b187c9cd2b5f16bd740e920eb875bccd2bbb
/Sqlite.py
6da147a1460fc3f925efe642aa5a17333e588bdd
[]
no_license
yaowenqiang/python-security-demo
c85c3066eb944267e2693f49f3291b1459ea829b
ece715fbb824fa395710fc5e82b8731ce1d370a8
refs/heads/master
2020-05-29T08:47:31.487050
2016-10-05T19:47:30
2016-10-05T19:47:30
70,012,123
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
import sqlite3 conn = sqlite3.connect('dbname.db') cur = conn.cursor() for row in cur.execute('select * from table'): print(row)
[ "yaowenqiang111@163.com" ]
yaowenqiang111@163.com
16b0f445540dde1647ce7b4edbe3557f4e17109d
555b9f764d9bca5232360979460bc35c2f5ad424
/google/ads/google_ads/v1/proto/enums/price_extension_type_pb2.py
d68fc2e76ee0a79c0fb5e4882d13b5b99bbeac9c
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
juanmacugat/google-ads-python
b50256163782bc0223bcd8b29f789d74f4cfad05
0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a
refs/heads/master
2021-02-18T17:00:22.067673
2020-03-05T16:13:57
2020-03-05T16:13:57
245,215,877
1
0
Apache-2.0
2020-03-05T16:39:34
2020-03-05T16:39:33
null
UTF-8
Python
false
true
5,168
py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v1/proto/enums/price_extension_type.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 google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/ads/googleads_v1/proto/enums/price_extension_type.proto', package='google.ads.googleads.v1.enums', syntax='proto3', serialized_options=_b('\n!com.google.ads.googleads.v1.enumsB\027PriceExtensionTypeProtoP\001ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V1.Enums\312\002\035Google\\Ads\\GoogleAds\\V1\\Enums\352\002!Google::Ads::GoogleAds::V1::Enums'), serialized_pb=_b('\n>google/ads/googleads_v1/proto/enums/price_extension_type.proto\x12\x1dgoogle.ads.googleads.v1.enums\x1a\x1cgoogle/api/annotations.proto\"\xeb\x01\n\x16PriceExtensionTypeEnum\"\xd0\x01\n\x12PriceExtensionType\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\n\n\x06\x42RANDS\x10\x02\x12\n\n\x06\x45VENTS\x10\x03\x12\r\n\tLOCATIONS\x10\x04\x12\x11\n\rNEIGHBORHOODS\x10\x05\x12\x16\n\x12PRODUCT_CATEGORIES\x10\x06\x12\x11\n\rPRODUCT_TIERS\x10\x07\x12\x0c\n\x08SERVICES\x10\x08\x12\x16\n\x12SERVICE_CATEGORIES\x10\t\x12\x11\n\rSERVICE_TIERS\x10\nB\xec\x01\n!com.google.ads.googleads.v1.enumsB\x17PriceExtensionTypeProtoP\x01ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\xa2\x02\x03GAA\xaa\x02\x1dGoogle.Ads.GoogleAds.V1.Enums\xca\x02\x1dGoogle\\Ads\\GoogleAds\\V1\\Enums\xea\x02!Google::Ads::GoogleAds::V1::Enumsb\x06proto3') , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _PRICEEXTENSIONTYPEENUM_PRICEEXTENSIONTYPE = _descriptor.EnumDescriptor( name='PriceExtensionType', full_name='google.ads.googleads.v1.enums.PriceExtensionTypeEnum.PriceExtensionType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNSPECIFIED', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='UNKNOWN', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='BRANDS', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='EVENTS', index=3, number=3, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='LOCATIONS', index=4, number=4, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='NEIGHBORHOODS', index=5, number=5, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='PRODUCT_CATEGORIES', index=6, number=6, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='PRODUCT_TIERS', index=7, number=7, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SERVICES', index=8, number=8, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SERVICE_CATEGORIES', index=9, number=9, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SERVICE_TIERS', index=10, number=10, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=155, serialized_end=363, ) _sym_db.RegisterEnumDescriptor(_PRICEEXTENSIONTYPEENUM_PRICEEXTENSIONTYPE) _PRICEEXTENSIONTYPEENUM = _descriptor.Descriptor( name='PriceExtensionTypeEnum', full_name='google.ads.googleads.v1.enums.PriceExtensionTypeEnum', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ _PRICEEXTENSIONTYPEENUM_PRICEEXTENSIONTYPE, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=128, serialized_end=363, ) _PRICEEXTENSIONTYPEENUM_PRICEEXTENSIONTYPE.containing_type = _PRICEEXTENSIONTYPEENUM DESCRIPTOR.message_types_by_name['PriceExtensionTypeEnum'] = _PRICEEXTENSIONTYPEENUM _sym_db.RegisterFileDescriptor(DESCRIPTOR) PriceExtensionTypeEnum = _reflection.GeneratedProtocolMessageType('PriceExtensionTypeEnum', (_message.Message,), dict( DESCRIPTOR = _PRICEEXTENSIONTYPEENUM, __module__ = 'google.ads.googleads_v1.proto.enums.price_extension_type_pb2' , __doc__ = """Container for enum describing types for a price extension. """, # @@protoc_insertion_point(class_scope:google.ads.googleads.v1.enums.PriceExtensionTypeEnum) )) _sym_db.RegisterMessage(PriceExtensionTypeEnum) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
[ "noreply@github.com" ]
juanmacugat.noreply@github.com
07be74c1ce70c9e40a4ac69d3170a13087bb46e4
eff2fe0333955dee20091e5de3ff7beb5c49a447
/django_project/projet1/site_info/infos/forms.py
c75ba26a9bfedd48edc57a46bc0260cc61de834e
[]
no_license
xarala221/python-pour-toure
ec8aad2100f9a157b158fe1727c3b0566f09c2da
27d90bc580acb159182e0914dffd2e037ef6f86b
refs/heads/master
2023-04-27T00:29:55.927458
2019-11-08T00:09:55
2019-11-08T00:09:55
209,387,702
0
0
null
2023-04-21T20:39:02
2019-09-18T19:26:11
Python
UTF-8
Python
false
false
283
py
from django import forms from .models import Article class ArticleForm(forms.ModelForm): titre = forms.CharField(label="Titre", max_length=150) contenu = forms.CharField(widget=forms.Textarea) class Meta: model = Article fields = ('titre', 'contenu',)
[ "xaralaxarala@gmail.com" ]
xaralaxarala@gmail.com
d32f045e7c74e6bb2e63be845ceb6e1fa3fc9139
24d8cf871b092b2d60fc85d5320e1bc761a7cbe2
/eXe/rev2735-2877/left-trunk-2877/nevow/rend.py
96afeed9d470191caa470c225a6500c17feb9fb9
[]
no_license
joliebig/featurehouse_fstmerge_examples
af1b963537839d13e834f829cf51f8ad5e6ffe76
1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad
refs/heads/master
2016-09-05T10:24:50.974902
2013-03-28T16:28:47
2013-03-28T16:28:47
9,080,611
3
2
null
null
null
null
UTF-8
Python
false
false
22,657
py
"""Page, Fragment and other standard renderers. This module contains classes and function responsible for rendering dynamic content and a few useful mixin classes for inheriting common functionality. Mostly, you'll use the renderers: - B{Page} - Nevow's main resource type for rendering web pages and locating child resource. - B{Fragment} - useful for rendering more complex parts of a document that require a set of data_* and render_* methods. - B{sequence} - render each item in a sequence. - B{mapping} - publish a dictionary by filling slots """ from cStringIO import StringIO import os.path import urllib import warnings import traceback from nevow.context import WovenContext, NodeNotFound, PageContext, RequestContext from nevow import compy from nevow import inevow from nevow import tags from nevow import flat from nevow.util import log from nevow import util import formless from formless import iformless from time import time as now try: import random except ImportError: import whrandom as random class RenderFactory(object): __implements__ = inevow.IRendererFactory, def renderer(self, context, name): """Return a renderer with the given name. """ args = [] if name.find(' ') != -1: name, args = name.split(None, 1) args = [arg.strip() for arg in args.split(',')] callable = getattr(self, 'render_%s' % name, None) if callable is None: callable = lambda context, data: context.tag[ "The renderer named '%s' was not found in %r." % (name, self)] if args: return callable(*args) return callable render_sequence = lambda self, context, data: sequence(context, data) render_mapping = lambda self, context, data: mapping(context, data) render_string = lambda self, context, data: string(context, data) render_xml = lambda self, context, data: context.tag.clear()[tags.xml(data)] render_data = lambda self, context, data_: data(context, data_) class MacroFactory(object): __implements__ = inevow.IMacroFactory, def macro(self, ctx, name): """Return a macro with the given name. """ args = [] if name.find(' ') != -1: name, args = name.split(None, 1) args = [arg.strip() for arg in args.split(',')] callable = getattr(self, 'macro_%s' % name, None) if callable is None: callable = lambda ctx, *args: ctx.tag[ "The macro named '%s' was not found in %r." % (name, self)] if args: return lambda ctx: callable(ctx, *args) return callable class DataFactory(object): __implements__ = inevow.IContainer, def child(self, context, n): args = [] if n.find(' ') != -1: name, args = n.split(None, 1) args = [arg.strip() for arg in args.split(',')] else: name = n callable = getattr(self, 'data_%s' % name, None) if callable is None: container = inevow.IContainer(self.original, None) if container is None: util.log.msg("ERROR: The data named '%s' was not found in %r." % (name, self)) callable = lambda context, data: context.tag["The data named '%s' was not found in %r." % (name, self)] else: return container.child(context, n) if args: return callable(*args) return callable class LiveEvilChildMixin: """Mixin that provides the LiveEvil child resources.""" def child_nevow_liveOutput(self, ctx): from nevow import liveevil self.child_nevow_liveOutput = liveevil.liveOutput return liveevil.liveOutput def child_nevow_liveInput(self, ctx): from nevow import liveevil self.child_nevow_liveInput = liveevil.liveInput return liveevil.liveInput class FreeformChildMixin: """Mixin that handles locateChild for freeform segments.""" def locateChild(self, ctx, segments): request = inevow.IRequest(ctx) bindingName = None name = segments[0] if name.startswith('freeform_post!'): configurableName, bindingName = name.split('!')[1:3] elif name.startswith('freeform-action-post!'): configurableName, request.args['freeform-actee'] = name.split('!')[1:3] bindingName = request.args['freeform-action'][0] if bindingName: ctx.remember(self, inevow.IResource) ctx.remember(request, inevow.IRequest) cf = iformless.IConfigurableFactory(self) def checkC(c): if c is not None: return self.webFormPost(request, self, c, ctx, bindingName, request.args) return util.maybeDeferred(cf.locateConfigurable, ctx, configurableName).addCallback(checkC) return NotFound class ConfigurableFactory: """Locates configurables by looking for methods that start with configurable_ and end with the name of the configurable. The method should take a single arg (other than self) - the current context. """ __implements__ = iformless.IConfigurableFactory def locateConfigurable(self, context, name): """formless.webform.renderForms calls locateConfigurable on the IConfigurableFactory instance it retrieves from the context. It passes the "name" that was passed to it, so if renderForms() was placed in the DOM, locateConfigurable will be called with name = ''; if renderForms('foo') was placed in the DOM, locateConfigurable will be called with name = 'foo'. This default implementation of locateConfigurable looks for a configurable_* method corresponding to the name which was passed. """ return util.maybeDeferred(getattr(self, 'configurable_%s'%name), context).addCallback(iformless.IConfigurable) def configurable_(self, context): """Configurable factory for use when self is a configurable; aka it implements IConfigurable or one or more TypedInterface subclasses. Usage: >>> class IFoo(TypedInterface): ... def bar(self): pass ... bar = autocallable(bar) ... >>> class Foo(Page): ... __implements__ = IFoo, ... ... def bar(self): ... print "bar called through the web!" ... ... def render_forms(self, ctx, data): ... return renderForms() # or renderForms('') ... ... docFactory = stan(render_forms). """ return self def configurable_original(self, ctx): """Configurable factory for use when self.original is a configurable; aka it implements IConfigurable or one or more TypedInterface subclasses. Usage: >>> class Foo(Page): ... def __init__(self): ... self.original = SomeConfigurable() ... def render_forms(self, ctx, data): ... return renderForms('original') ... docFactory = stan(render_forms) """ return self.original _CARRYOVER = {} def defaultsFactory(ctx): co = _CARRYOVER.get( ctx.tag.args.get('_nevow_carryover_', [None])[0], None) from formless import webform defaults = webform.FormDefaults() if co is not None: e = iformless.IFormErrors(co, {}) for k, v in e.items(): defaults.getAllDefaults(k).update(v.partialForm) return defaults def errorsFactory(ctx): co = _CARRYOVER.get( ctx.tag.args.get('_nevow_carryover_', [None])[0], None) from formless import webform errs = webform.FormErrors() if co is not None: e = iformless.IFormErrors(co, {}) for k, v in e.items(): errs.updateErrors(k, v.errors) errs.setError(k, v.formErrorMessage) return errs def handFactory(ctx): co = _CARRYOVER.get( ctx.tag.args.get('_nevow_carryover_', [None])[0], None) return inevow.IHand(co, None) def statusFactory(ctx): co = _CARRYOVER.get( ctx.tag.args.get('_nevow_carryover_', [None])[0], None) return inevow.IStatusMessage(co, None) def originalFactory(ctx): return ctx.tag class Fragment(DataFactory, RenderFactory, MacroFactory): """A fragment is a renderer that can be embedded in a stan document and hooks its template (from the docFactory) up to its data_ and render_ methods, i.e. it remembers itself as the IRendererFactory and IContainer. Fragment primarily serves as the base for Page, Nevow's web resource, but it can be used for more complex rendering. For instance, a fragment might be used to encapsulate the rendering of a complex piece of data where the template is read from disk and contains standard renderers (sequence, mapping etc) and/or custom render methods. """ __implements__ = ( inevow.IRenderer, inevow.IGettable, RenderFactory.__implements__, DataFactory.__implements__, MacroFactory.__implements__) docFactory = None original = None def __init__(self, original=None, docFactory=None): if original is not None: self.original = original self.toremember = [] self._context = None if docFactory is not None: self.docFactory = docFactory def get(self, context): return self.original def rend(self, context, data): self.rememberStuff(context) old = self.docFactory.pattern self.docFactory.pattern = 'content' self.docFactory.precompiledDoc = None try: doc = self.docFactory.load(context) self.docFactory.pattern = old self.docFactory.precompiledDoc = None except NodeNotFound: self.docFactory.pattern = old self.docFactory.precompiledDoc = None doc = self.docFactory.load(context) return doc def remember(self, obj, inter=None): """Remember an object for an interface on new PageContexts which are constructed around this Page. Whenever this Page is involved in object traversal in the future, all objects will be visible to .locate() calls at the level of a PageContext wrapped around this Page and all contexts below it. This does not affect existing Context instances. """ self.toremember.append((obj, inter)) def rememberStuff(self, ctx): ctx.remember(self, inevow.IRenderer) ctx.remember(self, inevow.IRendererFactory) ctx.remember(self, inevow.IMacroFactory) ctx.remember(self, inevow.IData) class ChildLookupMixin(FreeformChildMixin, LiveEvilChildMixin): children = None def locateChild(self, ctx, segments): """Locate a child page of this one. ctx is a nevow.context.PageContext representing the parent Page, and segments is a tuple of each element in the URI. An tuple (page, segments) should be returned, where page is an instance of nevow.rend.Page and segments a tuple representing the remaining segments of the URI. If the child is not found, return NotFound instead. locateChild is designed to be easily overridden to perform fancy lookup tricks. However, the default locateChild is useful, and looks for children in three places, in this order: - in a dictionary, self.children - a member of self named child_<childname>. This can be either an attribute or a method. If an attribute, it should be an object which can be adapted to IResource. If a method, it should take the context and return an object which can be adapted to IResource. - by calling self.childFactory(ctx, name). Name is a single string instead of a tuple of strings. This should return an object that can be adapted to IResource. """ if self.children is not None: r = self.children.get(segments[0], None) if r is not None: return r, segments[1:] w = getattr(self, 'child_%s'%segments[0], None) if w is not None: if inevow.IResource(w, default=None) is not None: return w, segments[1:] r = w(ctx) if r is not None: return r, segments[1:] r = self.childFactory(ctx, segments[0]) if r is not None: return r, segments[1:] return FreeformChildMixin.locateChild(self, ctx, segments) def childFactory(self, ctx, name): """Used by locateChild to return children which are generated dynamically. Note that higher level interfaces use only locateChild, and only nevow.rend.Page.locateChild uses this. segment is a string represnting one element of the URI. Request is a nevow.appserver.NevowRequest. The default implementation of this always returns None; it is intended to be overridden.""" rv = self.getDynamicChild(name, ctx) if rv is not None: warnings.warn("getDynamicChild is deprecated; use childFactory instead.", stacklevel=1) return rv def getDynamicChild(self, segment, request): """Deprecated, use childFactory instead. The name is different and the order of the arguments is reversed.""" return None def putChild(self, name, child): if self.children is None: self.children = {} self.children[name] = child class Page(Fragment, ConfigurableFactory, ChildLookupMixin): """A page is the main Nevow resource and renders a document loaded via the document factory (docFactory). """ __implements__ = Fragment.__implements__, inevow.IResource, ConfigurableFactory.__implements__ buffered = False beforeRender = None afterRender = None addSlash = None flattenFactory = lambda self, *args: flat.flattenFactory(*args) def renderHTTP(self, ctx): if self.beforeRender is not None: return util.maybeDeferred(self.beforeRender,ctx).addCallback( lambda result,ctx: self._renderHTTP(ctx),ctx) return self._renderHTTP(ctx) def _renderHTTP(self, ctx): request = inevow.IRequest(ctx) if self.addSlash and inevow.ICurrentSegments(ctx)[-1] != '': request.redirect(request.URLPath().child('')) return '' log.msg(http_render=None, uri=request.uri) self.rememberStuff(ctx) def finishRequest(): carryover = request.args.get('_nevow_carryover_', [None])[0] if carryover is not None and _CARRYOVER.has_key(carryover): del _CARRYOVER[carryover] if self.afterRender is not None: return util.maybeDeferred(self.afterRender,ctx) if self.buffered: io = StringIO() writer = io.write def finisher(result): request.write(io.getvalue()) return util.maybeDeferred(finishRequest).addCallback(lambda r: result) else: writer = request.write def finisher(result): return util.maybeDeferred(finishRequest).addCallback(lambda r: result) doc = self.docFactory.load(ctx) ctx = WovenContext(ctx, tags.invisible[doc]) return self.flattenFactory(doc, ctx, writer, finisher) def rememberStuff(self, ctx): Fragment.rememberStuff(self, ctx) ctx.remember(self, inevow.IResource) def renderString(self): """Render this page outside of the context of a web request, returning a Deferred which will result in a string. If twisted is not installed, this method will return a string result immediately, and this method is equivalent to renderSynchronously. """ io = StringIO() writer = io.write def finisher(result): return io.getvalue() ctx = PageContext(tag=self) self.rememberStuff(ctx) doc = self.docFactory.load(ctx) ctx = WovenContext(ctx, tags.invisible[doc]) return self.flattenFactory(doc, ctx, writer, finisher) def renderSynchronously(self): """Render this page synchronously, returning a string result immediately. Raise an exception if a Deferred is required to complete the rendering process. """ io = StringIO() ctx = PageContext(tag=self) self.rememberStuff(ctx) doc = self.docFactory.load(ctx) ctx = WovenContext(ctx, tags.invisible[doc]) def raiseAlways(item): raise NotImplementedError("renderSynchronously can not support" " rendering: %s" % (item, )) list(flat.iterflatten(doc, ctx, io.write, raiseAlways)) return io.getvalue() def child_(self, ctx): """When addSlash is True, a page rendered at a url with no trailing slash and a page rendered at a url with a trailing slash will be identical. addSlash is useful for the root resource of a site or directory-like resources. """ if self.addSlash and len(inevow.IRemainingSegments(ctx)) == 1: return self warnings.warn( "Allowing an empty child ('/') of resources automatically is " "deprecated. If the class '%s' is a directory-index-like resource, " "please add addSlash=True to the class definition." % (self.__class__), DeprecationWarning, 2) return self def webFormPost(self, request, res, configurable, ctx, bindingName, args): def redirectAfterPost(aspects): redirectAfterPost = request.getComponent(iformless.IRedirectAfterPost, None) if redirectAfterPost is None: ref = request.getHeader('referer') or '' else: ref = str(redirectAfterPost) from nevow import url refpath = url.URL.fromString(ref) magicCookie = '%s%s%s' % (now(),request.getClientIP(),random.random()) refpath = refpath.replace('_nevow_carryover_', magicCookie) _CARRYOVER[magicCookie] = C = compy.Componentized(aspects) request.redirect(str(refpath)) from nevow import static return static.Data('You posted a form to %s' % bindingName, 'text/plain'), () return util.maybeDeferred( configurable.postForm, ctx, bindingName, args ).addCallback( self.onPostSuccess, request, ctx, bindingName, redirectAfterPost ).addErrback( self.onPostFailure, request, ctx, bindingName, redirectAfterPost ) def onPostSuccess(self, result, request, ctx, bindingName, redirectAfterPost): if result is None: message = "%s success." % formless.nameToLabel(bindingName) else: message = result return redirectAfterPost({inevow.IHand: result, inevow.IStatusMessage: message}) def onPostFailure(self, reason, request, ctx, bindingName, redirectAfterPost): reason.trap(formless.ValidateError) return redirectAfterPost({iformless.IFormErrors: {bindingName: reason.value}}) def sequence(context, data): """Renders each item in the sequence using patterns found in the children of the element. Sequence recognises the following patterns: - header: Rendered at the start, before the first item. If multiple header patterns are provided they are rendered together in the order they were defined. - footer: Just like the header only renderer at the end, after the last item. - item: Rendered once for each item in the sequence. If multiple item patterns are provided then the pattern is cycled in the order defined. - divider: Rendered once between each item in the sequence. Multiple divider patterns are cycled. - empty: Rendered instead of item and divider patterns when the sequence contains no items. Example:: <table nevow:render="sequence" nevow:data="peopleSeq"> <tr nevow:pattern="header"> <th>name</th> <th>email</th> </tr> <tr nevow:pattern="item" class="odd"> <td>name goes here</td> <td>email goes here</td> </tr> <tr nevow:pattern="item" class="even"> <td>name goes here</td> <td>email goes here</td> </tr> <tr nevow:pattern="empty"> <td colspan="2"><em>they've all gone!</em></td> </tr> </table> """ tag = context.tag headers = tag.allPatterns('header') pattern = tag.patternGenerator('item') divider = tag.patternGenerator('divider', default=tags.invisible) content = [(pattern(data=element), divider(data=element)) for element in data] if not content: content = tag.allPatterns('empty') else: content[-1] = content[-1][0] footers = tag.allPatterns('footer') return tag.clear()[ headers, content, footers ] def mapping(context, data): """Fills any slots in the element's children with data from a dictionary. The dict keys are used as the slot names, the dict values are used as filling. Example:: <tr nevow:render="mapping" nevow:data="personDict"> <td><nevow:slot name="name"/></td> <td><nevow:slot name="email"/></td> </tr> """ for k, v in data.items(): context.fillSlots(k, v) return context.tag def string(context, data): return context.tag.clear()[str(data)] def data(context, data): """Replace the tag's content with the current data. """ return context.tag.clear()[data] class FourOhFour: """A simple 404 (not found) page. """ __implements__ = inevow.IResource, notFound = "<html><head><title>Page Not Found</title><head><body>Sorry, but I couldn't find the object you requested.</body></html>" original = None def locateChild(self, ctx, segments): return NotFound def renderHTTP(self, ctx): from twisted.protocols import http inevow.IRequest(ctx).setResponseCode(404) try: notFoundHandler = ctx.locate(inevow.ICanHandleNotFound) return notFoundHandler.renderHTTP_notFound(PageContext(parent=ctx, tag=notFoundHandler)) except KeyError, e: return self.notFound except: log.err() return self.notFound def __nonzero__(self): return False NotFound = None, ()
[ "joliebig@fim.uni-passau.de" ]
joliebig@fim.uni-passau.de
189efb22bc96c8dbf39159cfa00bac64b62041ab
384e179223c646e6390fce9e97242d34842cb192
/tests/minmax.py
b691b3232828b0326e6803175594c6c94da6bd27
[]
no_license
mykespb/edu
3a36fd1981fb696b622e23d878d45a098da819e7
0364b261234a2488c0ad3408ad83406594a5238e
refs/heads/master
2023-08-07T15:37:19.285125
2023-08-06T18:13:28
2023-08-06T18:13:28
20,329,609
0
0
null
null
null
null
UTF-8
Python
false
false
2,589
py
#!/usr/bin/env python3 # программа ищет максимумы и минимумы в списке # (C) М.Колодин, 2021-06-25, 2021-10-06 1.3 # -------------------------------------- подготовка import random rang = range(10) def makerand(size=10, lower=-100, upper=100): """ сделать список из size элементов, минимальное значение lower, максимальное значение upper """ return [random.randint(lower, upper) for _ in range(size)] def head(s): """ напечатать заголовок """ sep = "---------------------------------" print(f"\n{sep}\n{s}\n{sep}\n") def test(f): """ запустить функцию на тест """ for i in rang: a = makerand() print(a) print(f(a)) # -------------------------------------- запуски функций head("найти максимум") def getmax1(a): """ найти максимум """ if not a: return None return max(a) print(getmax1([])) test(getmax1) def getmax2(a): """ найти максимум """ if not a: return None m = a[0] for e in a: if e > m: m = e return m print(getmax2([])) test(getmax1) head("найти минимум, нетривиально") def getmin2(a): """ найти минимум """ if not a: return None m = a[0] for e in a: if e < m: m = e return m test(getmin2) head("найти минимум и максимум за 1 проход") def getall1(a): """ найти максимум и минимум """ if not a: return None mi = ma = a[0] for e in a: if e > ma: ma = e if e < mi: mi = e return mi, ma test(getall1) head("найти максимум по модулю") def maxmod1(a): """ найти максимум по модулю """ return sorted(a, key=lambda x: abs(x), reverse=True)[0] if a else None test(maxmod1) head("найти максимум и минимум по модулю") def minmaxmod1(a): """ найти минимум и максимум по модулю за 1 проход """ if not a: return None m = sorted(a, key=lambda x: abs(x)) return m[0], m[-1] test(minmaxmod1) def minmaxmod2(a): """ найти минимум и максимум по модулю за 1 проход """ if not a: return None return sorted(a, key=lambda x: abs(x))[0: len(a): len(a)-1] test(minmaxmod2) # ================= the end.
[ "mykespb@gmail.com" ]
mykespb@gmail.com
d95dd338136787acdc0eb23e72b41ad2b218308d
846a7668ac964632bdb6db639ab381be11c13b77
/android/tools/test/connectivity/acts/framework/acts/controllers/native_android_device.py
cbe32373eacb752b1ca8049113a18167327983d1
[]
no_license
BPI-SINOVOIP/BPI-A64-Android8
f2900965e96fd6f2a28ced68af668a858b15ebe1
744c72c133b9bf5d2e9efe0ab33e01e6e51d5743
refs/heads/master
2023-05-21T08:02:23.364495
2020-07-15T11:27:51
2020-07-15T11:27:51
143,945,191
2
0
null
null
null
null
UTF-8
Python
false
false
4,263
py
#!/usr/bin/env python3.4 # # Copyright 2016 - The Android Open Source Project # # 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 acts.controllers.android_device import AndroidDevice from acts.controllers.utils_lib import host_utils import acts.controllers.native as native from subprocess import call import logging import time #TODO(tturney): Merge this into android device ACTS_CONTROLLER_CONFIG_NAME = "NativeAndroidDevice" ACTS_CONTROLLER_REFERENCE_NAME = "native_android_devices" def create(configs): logger = logging ads = get_instances(configs) for ad in ads: try: ad.get_droid() except: logger.exception("Failed to start sl4n on %s" % ad.serial) return ads def destroy(ads): pass def get_instances(serials, ): """Create AndroidDevice instances from a list of serials. Args: serials: A list of android device serials. logger: A logger to be passed to each instance. Returns: A list of AndroidDevice objects. """ results = [] for s in serials: results.append(NativeAndroidDevice(s)) return results class NativeAndroidDeviceError(Exception): pass class NativeAndroidDevice(AndroidDevice): def __del__(self): if self.h_port: self.adb.forward("--remove tcp:%d" % self.h_port) def get_droid(self, handle_event=True): """Create an sl4n connection to the device. Return the connection handler 'droid'. By default, another connection on the same session is made for EventDispatcher, and the dispatcher is returned to the caller as well. If sl4n server is not started on the device, try to start it. Args: handle_event: True if this droid session will need to handle events. Returns: droid: Android object useds to communicate with sl4n on the android device. ed: An optional EventDispatcher to organize events for this droid. Examples: Don't need event handling: >>> ad = NativeAndroidDevice() >>> droid = ad.get_droid(False) Need event handling: >>> ad = NativeAndroidDevice() >>> droid, ed = ad.get_droid() """ if not self.h_port or not host_utils.is_port_available(self.h_port): self.h_port = host_utils.get_available_host_port() self.adb.tcp_forward(self.h_port, self.d_port) pid = self.adb.shell("pidof -s sl4n", ignore_status=True) while (pid): self.adb.shell("kill {}".format(pid)) pid = self.adb.shell("pidof -s sl4n", ignore_status=True) call( ["adb -s " + self.serial + " shell sh -c \"/system/bin/sl4n\" &"], shell=True) try: time.sleep(3) droid = self.start_new_session() except: droid = self.start_new_session() return droid def start_new_session(self): """Start a new session in sl4n. Also caches the droid in a dict with its uid being the key. Returns: An Android object used to communicate with sl4n on the android device. Raises: sl4nException: Something is wrong with sl4n and it returned an existing uid to a new session. """ droid = native.NativeAndroid(port=self.h_port) droid.open() if droid.uid in self._droid_sessions: raise bt.SL4NException(("SL4N returned an existing uid for a " "new session. Abort.")) return droid self._droid_sessions[droid.uid] = [droid] return droid
[ "mingxin.android@gmail.com" ]
mingxin.android@gmail.com
45a4c5a576c3940d7582246e107c9e4cf88223a8
e206cc00299804ce2271eb5d1513620e44ee9a9b
/course1-algorithm-toolbox/assignments/assignment_003_binary_search/binary_search.py
9f88ea80fac72e56ee2a8046d8fed1a86d21c756
[]
no_license
dmitri-mamrukov/coursera-data-structures-and-algorithms
15459cd160f7bbae5464bf53d995bca868a0b415
01dd6f0dadf62a520bcafafddf7bf2b79e8e2603
refs/heads/master
2020-05-24T18:27:00.665642
2019-05-21T20:45:37
2019-05-21T20:45:37
187,410,737
1
0
null
null
null
null
UTF-8
Python
false
false
774
py
#!/usr/bin/python3 import sys def binary_search(data, key): """Finds the index of the key in the array if any. Otherwise, -1 is returned. """ low = 0 high = len(data) - 1 while low <= high: mid = low + (high - low) // 2 if data[mid] == key: return mid elif key < data[mid]: high = mid - 1 else: low = mid + 1 return -1 def linear_search(a, x): for i in range(len(a)): if a[i] == x: return i return -1 if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] m = data[n + 1] a = data[1 : n + 1] for x in data[n + 2:]: print(binary_search(a, x), end = ' ') print()
[ "dmitri.mamrukov@gmail.com" ]
dmitri.mamrukov@gmail.com
256abba517d9e7d62ae15a8a78fa14b8944a73e9
2e43fc58f2a70b38c8f74101d639d1ad6fffb609
/ParadoxTrading/Indicator/General/STD.py
83f4e6feb10387c9f7a07fe2930542fb323df01c
[ "MIT" ]
permissive
ppaanngggg/ParadoxTrading
9cac27dee26a49739dde661c1e03d83bda09df9b
2c4024e60b14bf630fd141ccd4c77f197b7c901a
refs/heads/master
2021-05-11T20:13:14.871616
2018-07-13T05:49:15
2018-07-13T05:49:15
117,434,771
96
26
MIT
2018-03-21T08:47:27
2018-01-14T13:57:16
Python
UTF-8
Python
false
false
946
py
import statistics from collections import deque from ParadoxTrading.Indicator.IndicatorAbstract import IndicatorAbstract from ParadoxTrading.Utils import DataStruct class STD(IndicatorAbstract): def __init__( self, _period: int, _use_key: str = 'closeprice', _idx_key: str = 'time', _ret_key: str = 'std' ): super().__init__() self.use_key = _use_key self.idx_key = _idx_key self.ret_key = _ret_key self.data = DataStruct( [self.idx_key, self.ret_key], self.idx_key ) self.period = _period self.buf = deque(maxlen=self.period) def _addOne(self, _data_struct: DataStruct): index_value = _data_struct.index()[0] self.buf.append(_data_struct.getColumn(self.use_key)[0]) self.data.addDict({ self.idx_key: index_value, self.ret_key: statistics.pstdev(self.buf), })
[ "hantian.pang@gmail.com" ]
hantian.pang@gmail.com
4986ee44c897cc2a4e04b19ff047103d8eca4928
f30b91db647dca1f77fffa4b7e26b6c6a68abbc6
/7_kyu/Some (but not all)/python/solution.py
b48c4eab6b9c5151e62e37c956fd72d09b425a2e
[]
no_license
estraviz/codewars
73caf95519eaac6f34962b8ade543bf4417df5b7
5f8685e883cb78381c528a0988f2b5cad6c129c2
refs/heads/master
2023-05-13T07:57:43.165290
2023-05-08T21:50:39
2023-05-08T21:50:39
159,744,593
10
55
null
null
null
null
UTF-8
Python
false
false
100
py
# Some (but not all) def some_but_not_all(seq, pred): return 0 < sum(map(pred, seq)) < len(seq)
[ "javier.estraviz@gmail.com" ]
javier.estraviz@gmail.com
f4a4f1b9134f9a48c469deecb483c3546f1f388b
4be56098894a95da5964622fc4102b69e4530ab6
/题库/685.冗余连接II.py
339cc805281bb9a05de9b605ac333a5b24b13f4b
[]
no_license
ACENDER/LeetCode
7c7c7ecc8d0cc52215272f47ec34638637fae7ac
3383b09ab1246651b1d7b56ab426a456f56a4ece
refs/heads/master
2023-03-13T19:19:07.084141
2021-03-15T09:29:21
2021-03-15T09:29:21
299,332,864
0
0
null
null
null
null
UTF-8
Python
false
false
81
py
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @File : 685.冗余连接II.py
[ "1641429327@qq.com" ]
1641429327@qq.com
e3e11bcf554e35eb35d669c631db19e936d7b28b
05536893d069dd87256ba74ecdee06bdf481d44b
/args_api/ORAXE/ORAXE-SYIQ.py
9a9aa44a950397dc067696eb28519378a6436380
[]
no_license
TheRockStarDBA/DataBuddy
b2d889e11745d0afe1b39a11aab5945e2bd08cf7
38fa7adfdd228e2b2e4b4408393505163c5702e8
refs/heads/master
2020-12-25T23:27:02.363977
2015-05-28T19:14:12
2015-05-28T19:14:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
20,444
py
#do not change aa={'ORAXE_ShardedTable.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 3, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 3, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_589000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'from_table': ('-c', '--from_table', 'SCOTT.Timestamp_test_from', 'From table.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'ORAXE_Table_KeepSpoolFile.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 1, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 1, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_496000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'from_table': ('-c', '--from_table', 'SCOTT.Timestamp_test_from', 'From table.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'default': [{'ask_to_truncate': ['-E', '--ask_to_truncate', '', 'Ask to truncate.'], 'shard_pre_etl': ['-2', '--shard_pre_etl', '', 'Path to shard level pre-ETL Python script.'], 'keep_data_file': ['-K', '--keep_data_file', '', 'Keep data dump.'], 'default_spool_dir': ['-F', '--default_spool_dir', '', 'Default data dump dir (default_spool_dir/job_name/timestamp).'], 'arg_6': ['-6', '--arg_6', '', 'Generic string argument 1.'], 'lame_duck': ['-l', '--lame_duck', '', 'Limit rows (lame duck run).'], 'copy_vector': ['-w', '--copy_vector', '', 'Data copy direction.'], 'log_dir': ['-M', '--log_dir', '', 'Log destination.'], 'time_stamp': ['-Y', '--time_stamp', '', 'Timestamp (log_dir/job_name/timestamp).'], 'job_name': ['-B', '--job_name', '', 'Job name (log_dir/job_name).'], 'job_pre_etl': ['-1', '--job_pre_etl', '', 'Path to job level pre-ETL Python script.'], 'num_of_shards': ['-r', '--num_of_shards', '', 'Number of shards.'], 'loader_profile': ['-C', '--loader_profile', '', 'SQL*Loader profile (user defined).'], 'email_to': ['-L', '--email_to', '', 'Email job status.'], 'host_map': ['-5', '--host_map', '', 'Host-to-shard map.'], 'arg_8': ['-8', '--arg_8', '', 'Generic string argument 3.'], 'validate': ['-V', '--validate', '', 'Check if source and target objects exist.'], 'arg_7': ['-7', '--arg_7', '', 'Generic string argument 2.'], 'field_term': ['-t', '--field_term', '', 'Field terminator.'], 'pool_size': ['-o', '--pool_size', '', 'Pool size.'], 'column_buckets': ['-0', '--column_buckets', '', 'Wide row support.'], 'job_post_etl': ['-3', '--job_post_etl', '', 'Jobs post-etl script.'], 'truncate_target': ['-U', '--truncate_target', '', 'Truncate target table/partition/subpartition.'], 'shard_post_etl': ['-4', '--shard_post_etl', '', 'Shards post-etl script.'], 'key_on_exit': ['-X', '--key_on_exit', '', 'Ask for an "Enter" key upon exit.']}, {'query_sql_file': ['-q', '--query_sql_file', '', 'Input file with Oracle XE query sql.'], 'from_db_name': ['-b', '--from_db_name', '', 'Oracle XE source database.'], 'header': ['-A', '--header', '', 'Include header to Oracle XE extract.'], 'from_table': ['-c', '--from_table', '', 'From table.'], 'nls_timestamp_format': ['-m', '--nls_timestamp_format', '', 'nls_timestamp_format for source.'], 'nls_date_format': ['-e', '--nls_date_format', '', 'nls_date_format for source.'], 'keep_whitespace': ['-W', '--keep_whitespace', '', 'Keep whitespace from CHAR type in "Oracle XE" extract.'], 'nls_timestamp_tz_format': ['-O', '--nls_timestamp_tz_format', '', 'nls_timestamp_tz_format for source.'], 'from_user': ['-j', '--from_user', '', 'Oracle XE source user.'], 'from_passwd': ['-x', '--from_passwd', '', 'Oracle XE source user password.'], 'query_sql_dir': ['-Q', '--query_sql_dir', '', 'Input dir with Oracle XE query files sql.']}, {'to_db_name': ['-d', '--to_db_name', '', 'Target Sybase IQ database.'], 'target_client_home': ['-Z', '--target_client_home', '', 'Path to Sybase IQ client home bin dir.'], 'skip_rows': ['-k', '--skip_rows', '', 'Header size. Number of rows to skip in input file.'], 'to_user': ['-u', '--to_user', '', 'Target Sybase IQ db user.'], 'to_passwd': ['-p', '--to_passwd', '', 'Target Sybase IQ db user password.'], 'to_db_server': ['-s', '--to_db_server', '', 'Target Sybase IQ db instance name.'], 'to_table': ['-a', '--to_table', '', 'Target Sybase IQ table.']}], 'ORAXE_Table.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 1, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 1, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_480000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'from_table': ('-c', '--from_table', 'SCOTT.Timestamp_test_from', 'From table.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'ORAXE_TimestampTable.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 1, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 1, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_449000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'from_table': ('-c', '--from_table', 'SCOTT.Timestamp_test_from', 'From table.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'ORAXE_ParallelQueryDir.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 3, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 3, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_558000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.'), 'query_sql_dir': ('-Q', '--query_sql_dir', 'C:\\Python27\\data_migrator_1239_12c\\test\\v101\\query\\query_dir_ora', 'Input dir with Oracle XE query files sql.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'ORAXE_TimezoneTable.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 1, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 1, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_418000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'from_table': ('-c', '--from_table', 'SCOTT.Timestamp_test_from', 'From table.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'ORAXE_QueryDir.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 1, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 1, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_527000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.'), 'query_sql_dir': ('-Q', '--query_sql_dir', 'C:\\Python27\\data_migrator_1239_12c\\test\\v101\\query\\query_dir_ora', 'Input dir with Oracle XE query files sql.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}], 'ORAXE_QueryFile.SYIQ_Table': [{'field_term': ('-t', '--field_term', '"|"', 'Field terminator.'), 'num_of_shards': ('-r', '--num_of_shards', 1, 'Number of shards.'), 'pool_size': ('-o', '--pool_size', 1, 'Pool size.'), 'copy_vector': ('-w', '--copy_vector', 'oraxe-syiq', 'Data copy direction.'), 'keep_data_file': ('-K', '--keep_data_file', 1, 'Keep data dump.'), 'default_spool_dir': ('-F', '--default_spool_dir', 'C:\\tmp\\TEST_default_spool', 'Default data dump dir (default_spool_dir/job_name/timestamp).'), 'time_stamp': ('-Y', '--time_stamp', '20150515_180349_605000', 'Timestamp (log_dir/job_name/timestamp).'), 'host_map': ('-5', '--host_map', '".\\config\\host_map_v2.py"', 'Host-to-shard map.'), 'job_name': ('-B', '--job_name', 'qc_job', 'Job name (log_dir/job_name).'), 'log_dir': ('-M', '--log_dir', 'C:\\Temp\\qc_log', 'Log destination.')}, {'query_sql_file': ('-q', '--query_sql_file', 'C:\\Python27\\data_migrator_1239_12c\\test\\v101\\query\\oracle_query.sql', 'Input file with Oracle XE query sql.'), 'from_db_name': ('-b', '--from_db_name', 'orcl', 'Oracle XE source database.'), 'nls_timestamp_format': ('-m', '--nls_timestamp_format', '"YYYY-MM-DD HH24.MI.SS.FF2"', 'nls_timestamp_format for source.'), 'nls_date_format': ('-e', '--nls_date_format', '"YYYY-MM-DD HH24.MI.SS"', 'nls_date_format for source.'), 'nls_timestamp_tz_format': ('-O', '--nls_timestamp_tz_format', '"YYYY-MM-DD HH:MI:SS.FF2 TZH:TZM"', 'nls_timestamp_tz_format for source.'), 'from_user': ('-j', '--from_user', 'SCOTT', 'Oracle XE source user.'), 'from_passwd': ('-x', '--from_passwd', 'tiger', 'Oracle XE source user password.')}, {'to_db_name': ('-d', '--to_db_name', '"demo"', 'Target Sybase IQ database.'), 'target_client_home': ('-Z', '--target_client_home', '"C:\\Program Files\\SQL Anywhere 16\\Bin64"', 'Path to Sybase IQ client home bin dir.'), 'to_user': ('-u', '--to_user', '"dba"', 'Target Sybase IQ db user.'), 'to_passwd': ('-p', '--to_passwd', '"sql"', 'Target Sybase IQ db user password.'), 'to_db_server': ('-s', '--to_db_server', '"demo16"', 'Target Sybase IQ db instance name.'), 'to_table': ('-a', '--to_table', '"Timestamp_test_to"', 'Target Sybase IQ table.')}]}
[ "alexbuzunov@gmail.com" ]
alexbuzunov@gmail.com
6ef3df3ba55360dabdcd3af3998b357a862e67e0
4ddb15eff1020ce0a8045bc04837dc9ec6e00ca9
/flexinfer/postprocess/obj_det/bbox/bbox.py
3035a187fa9ee293135ceed6329bda3fc0553f61
[ "Apache-2.0" ]
permissive
YuxinZou/flexinfer
ebd8db24efcf983a5abfb9b5b7cf68e038ba00f8
f2b45251b919e3426745c712f3a380e6f44a17d8
refs/heads/master
2023-04-20T11:45:28.218726
2021-04-29T11:37:00
2021-04-29T11:37:00
283,115,582
0
0
Apache-2.0
2020-07-28T06:00:22
2020-07-28T06:00:22
null
UTF-8
Python
false
false
9,731
py
# adapted from https://github.com/open-mmlab/mmcv or # https://github.com/open-mmlab/mmdetection import numpy as np import torch from flexinfer.ops import batched_nms def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6): """Calculate overlap between two set of bboxes. If ``is_aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. Args: bboxes1 (Tensor): shape (m, 4) in <x1, y1, x2, y2> format or empty. bboxes2 (Tensor): shape (n, 4) in <x1, y1, x2, y2> format or empty. If is_aligned is ``True``, then m and n must be equal. mode (str): "iou" (intersection over union) or iof (intersection over foreground). Returns: ious(Tensor): shape (m, n) if is_aligned == False else shape (m, 1) Example: >>> bboxes1 = torch.FloatTensor([ >>> [0, 0, 10, 10], >>> [10, 10, 20, 20], >>> [32, 32, 38, 42], >>> ]) >>> bboxes2 = torch.FloatTensor([ >>> [0, 0, 10, 20], >>> [0, 10, 10, 19], >>> [10, 10, 20, 20], >>> ]) >>> bbox_overlaps(bboxes1, bboxes2) tensor([[0.5000, 0.0000, 0.0000], [0.0000, 0.0000, 1.0000], [0.0000, 0.0000, 0.0000]]) Example: >>> empty = torch.FloatTensor([]) >>> nonempty = torch.FloatTensor([ >>> [0, 0, 10, 9], >>> ]) >>> assert tuple(bbox_overlaps(empty, nonempty).shape) == (0, 1) >>> assert tuple(bbox_overlaps(nonempty, empty).shape) == (1, 0) >>> assert tuple(bbox_overlaps(empty, empty).shape) == (0, 0) """ assert mode in ['iou', 'iof'] # Either the boxes are empty or the length of boxes's last dimenstion is 4 assert (bboxes1.size(-1) == 4 or bboxes1.size(0) == 0) assert (bboxes2.size(-1) == 4 or bboxes2.size(0) == 0) rows = bboxes1.size(0) cols = bboxes2.size(0) if is_aligned: assert rows == cols if rows * cols == 0: return bboxes1.new(rows, 1) if is_aligned else bboxes1.new(rows, cols) if is_aligned: lt = torch.max(bboxes1[:, :2], bboxes2[:, :2]) # [rows, 2] rb = torch.min(bboxes1[:, 2:], bboxes2[:, 2:]) # [rows, 2] wh = (rb - lt).clamp(min=0) # [rows, 2] overlap = wh[:, 0] * wh[:, 1] area1 = (bboxes1[:, 2] - bboxes1[:, 0]) * ( bboxes1[:, 3] - bboxes1[:, 1]) if mode == 'iou': area2 = (bboxes2[:, 2] - bboxes2[:, 0]) * ( bboxes2[:, 3] - bboxes2[:, 1]) union = area1 + area2 - overlap else: union = area1 else: lt = torch.max(bboxes1[:, None, :2], bboxes2[:, :2]) # [rows, cols, 2] rb = torch.min(bboxes1[:, None, 2:], bboxes2[:, 2:]) # [rows, cols, 2] wh = (rb - lt).clamp(min=0) # [rows, cols, 2] overlap = wh[:, :, 0] * wh[:, :, 1] area1 = (bboxes1[:, 2] - bboxes1[:, 0]) * ( bboxes1[:, 3] - bboxes1[:, 1]) if mode == 'iou': area2 = (bboxes2[:, 2] - bboxes2[:, 0]) * ( bboxes2[:, 3] - bboxes2[:, 1]) union = area1[:, None] + area2 - overlap else: union = area1[:, None] eps = union.new_tensor([eps]) union = torch.max(union, eps) ious = overlap / union return ious def multiclass_nms(multi_bboxes, multi_scores, score_thr, nms_cfg, max_num=-1, score_factors=None): """NMS for multi-class bboxes. Args: multi_bboxes (Tensor): shape (n, #class*4) or (n, 4) multi_scores (Tensor): shape (n, #class), where the last column contains scores of the background class, but this will be ignored. score_thr (float): bbox threshold, bboxes with scores lower than it will not be considered. nms_thr (float): NMS IoU threshold max_num (int): if there are more than max_num bboxes after NMS, only top max_num will be kept. score_factors (Tensor): The factors multiplied to scores before applying NMS Returns: tuple: (bboxes, labels), tensors of shape (k, 5) and (k, 1). Labels are 0-based. """ num_classes = multi_scores.size(1) - 1 # exclude background category if multi_bboxes.shape[1] > 4: bboxes = multi_bboxes.view(multi_scores.size(0), -1, 4) else: bboxes = multi_bboxes[:, None].expand(-1, num_classes, 4) scores = multi_scores[:, :-1] # filter out boxes with low scores if score_factors is not None: scores = scores * score_factors[:, None] valid_mask = scores > score_thr bboxes = bboxes[valid_mask] scores = scores[valid_mask] labels = valid_mask.nonzero(as_tuple=False)[:, 1] if bboxes.numel() == 0: bboxes = multi_bboxes.new_zeros((0, 5)) labels = multi_bboxes.new_zeros((0, ), dtype=torch.long) return bboxes, labels dets, keep = batched_nms(bboxes, scores, labels, nms_cfg) if max_num > 0: dets = dets[:max_num] keep = keep[:max_num] return dets, labels[keep] def distance2bbox(points, distance, max_shape=None): """Decode distance prediction to bounding box. Args: points (Tensor): Shape (n, 2), [x, y]. distance (Tensor): Distance from the given point to 4 boundaries (left, top, right, bottom). max_shape (tuple): Shape of the image. Returns: Tensor: Decoded bboxes. """ x1 = points[:, 0] - distance[:, 0] y1 = points[:, 1] - distance[:, 1] x2 = points[:, 0] + distance[:, 2] y2 = points[:, 1] + distance[:, 3] if max_shape is not None: x1 = x1.clamp(min=0, max=max_shape[1]) y1 = y1.clamp(min=0, max=max_shape[0]) x2 = x2.clamp(min=0, max=max_shape[1]) y2 = y2.clamp(min=0, max=max_shape[0]) return torch.stack([x1, y1, x2, y2], -1) def bbox2distance(points, bbox, max_dis=None, eps=0.1): """Decode bounding box based on distances. Args: points (Tensor): Shape (n, 2), [x, y]. bbox (Tensor): Shape (n, 4), "xyxy" format max_dis (float): Upper bound of the distance. eps (float): a small value to ensure target < max_dis, instead <= Returns: Tensor: Decoded distances. """ left = points[:, 0] - bbox[:, 0] top = points[:, 1] - bbox[:, 1] right = bbox[:, 2] - points[:, 0] bottom = bbox[:, 3] - points[:, 1] if max_dis is not None: left = left.clamp(min=0, max=max_dis - eps) top = top.clamp(min=0, max=max_dis - eps) right = right.clamp(min=0, max=max_dis - eps) bottom = bottom.clamp(min=0, max=max_dis - eps) return torch.stack([left, top, right, bottom], -1) def bbox2roi(bbox_list): """Convert a list of bboxes to roi format. Args: bbox_list (list[Tensor]): a list of bboxes corresponding to a batch of images. Returns: Tensor: shape (n, 5), [batch_ind, x1, y1, x2, y2] """ rois_list = [] for img_id, bboxes in enumerate(bbox_list): if bboxes.size(0) > 0: img_inds = bboxes.new_full((bboxes.size(0), 1), img_id) rois = torch.cat([img_inds, bboxes[:, :4]], dim=-1) else: rois = bboxes.new_zeros((0, 5)) rois_list.append(rois) rois = torch.cat(rois_list, 0) return rois def bbox2result(bboxes, labels, num_classes): """Convert detection results to a list of numpy arrays. Args: bboxes (Tensor): shape (n, 5) labels (Tensor): shape (n, ) num_classes (int): class number, including background class Returns: list(ndarray): bbox results of each class """ if bboxes.shape[0] == 0: return [np.zeros((0, 5), dtype=np.float32) for i in range(num_classes)] else: bboxes = bboxes.cpu().numpy() labels = labels.cpu().numpy() return [bboxes[labels == i, :] for i in range(num_classes)] def bbox_flip(bboxes, img_shape, direction='horizontal'): """Flip bboxes horizontally or vertically. Args: bboxes (Tensor): Shape (..., 4*k) img_shape (tuple): Image shape. direction (str): Flip direction, options are "horizontal", "vertical", "diagonal". Default: "horizontal" Returns: Tensor: Flipped bboxes. """ assert bboxes.shape[-1] % 4 == 0 assert direction in ['horizontal', 'vertical', 'diagonal'] flipped = bboxes.clone() if direction == 'horizontal': flipped[..., 0::4] = img_shape[1] - bboxes[..., 2::4] flipped[..., 2::4] = img_shape[1] - bboxes[..., 0::4] elif direction == 'vertical': flipped[..., 1::4] = img_shape[0] - bboxes[..., 3::4] flipped[..., 3::4] = img_shape[0] - bboxes[..., 1::4] else: flipped[..., 0::4] = img_shape[1] - bboxes[..., 2::4] flipped[..., 1::4] = img_shape[0] - bboxes[..., 3::4] flipped[..., 2::4] = img_shape[1] - bboxes[..., 0::4] flipped[..., 3::4] = img_shape[0] - bboxes[..., 1::4] return flipped def bbox_revert(bboxes, img_shape, scale_factor, flip, flip_direction='horizontal'): """Map bboxes from testing scale to original image scale.""" new_bboxes = bbox_flip(bboxes, img_shape, flip_direction) if flip else bboxes new_bboxes = new_bboxes.view(-1, 4) / new_bboxes.new_tensor(scale_factor) return new_bboxes.view(bboxes.shape)
[ "hongxiang.cai@media-smart.cn" ]
hongxiang.cai@media-smart.cn
95d67ed09c630944139103b90f434f4f81b48a2f
48e124e97cc776feb0ad6d17b9ef1dfa24e2e474
/sdk/python/pulumi_azure_native/servicefabricmesh/v20180701preview/volume.py
e9863b6c451d2a6b1da47a09dd3c2dce483ffbc6
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bpkgoud/pulumi-azure-native
0817502630062efbc35134410c4a784b61a4736d
a3215fe1b87fba69294f248017b1591767c2b96c
refs/heads/master
2023-08-29T22:39:49.984212
2021-11-15T12:43:41
2021-11-15T12:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,030
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['VolumeArgs', 'Volume'] @pulumi.input_type class VolumeArgs: def __init__(__self__, *, provider: pulumi.Input[Union[str, 'VolumeProvider']], resource_group_name: pulumi.Input[str], azure_file_parameters: Optional[pulumi.Input['VolumeProviderParametersAzureFileArgs']] = None, description: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, volume_name: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a Volume resource. :param pulumi.Input[Union[str, 'VolumeProvider']] provider: Provider of the volume. :param pulumi.Input[str] resource_group_name: Azure resource group name :param pulumi.Input['VolumeProviderParametersAzureFileArgs'] azure_file_parameters: This type describes a volume provided by an Azure Files file share. :param pulumi.Input[str] description: User readable description of the volume. :param pulumi.Input[str] location: The geo-location where the resource lives :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. :param pulumi.Input[str] volume_name: The identity of the volume. """ pulumi.set(__self__, "provider", provider) pulumi.set(__self__, "resource_group_name", resource_group_name) if azure_file_parameters is not None: pulumi.set(__self__, "azure_file_parameters", azure_file_parameters) if description is not None: pulumi.set(__self__, "description", description) if location is not None: pulumi.set(__self__, "location", location) if tags is not None: pulumi.set(__self__, "tags", tags) if volume_name is not None: pulumi.set(__self__, "volume_name", volume_name) @property @pulumi.getter def provider(self) -> pulumi.Input[Union[str, 'VolumeProvider']]: """ Provider of the volume. """ return pulumi.get(self, "provider") @provider.setter def provider(self, value: pulumi.Input[Union[str, 'VolumeProvider']]): pulumi.set(self, "provider", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ Azure resource group name """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="azureFileParameters") def azure_file_parameters(self) -> Optional[pulumi.Input['VolumeProviderParametersAzureFileArgs']]: """ This type describes a volume provided by an Azure Files file share. """ return pulumi.get(self, "azure_file_parameters") @azure_file_parameters.setter def azure_file_parameters(self, value: Optional[pulumi.Input['VolumeProviderParametersAzureFileArgs']]): pulumi.set(self, "azure_file_parameters", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ User readable description of the volume. """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ The geo-location where the resource lives """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Resource tags. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @property @pulumi.getter(name="volumeName") def volume_name(self) -> Optional[pulumi.Input[str]]: """ The identity of the volume. """ return pulumi.get(self, "volume_name") @volume_name.setter def volume_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "volume_name", value) class Volume(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, azure_file_parameters: Optional[pulumi.Input[pulumi.InputType['VolumeProviderParametersAzureFileArgs']]] = None, description: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, provider: Optional[pulumi.Input[Union[str, 'VolumeProvider']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, volume_name: Optional[pulumi.Input[str]] = None, __props__=None): """ This type describes a volume resource. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[pulumi.InputType['VolumeProviderParametersAzureFileArgs']] azure_file_parameters: This type describes a volume provided by an Azure Files file share. :param pulumi.Input[str] description: User readable description of the volume. :param pulumi.Input[str] location: The geo-location where the resource lives :param pulumi.Input[Union[str, 'VolumeProvider']] provider: Provider of the volume. :param pulumi.Input[str] resource_group_name: Azure resource group name :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. :param pulumi.Input[str] volume_name: The identity of the volume. """ ... @overload def __init__(__self__, resource_name: str, args: VolumeArgs, opts: Optional[pulumi.ResourceOptions] = None): """ This type describes a volume resource. :param str resource_name: The name of the resource. :param VolumeArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VolumeArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, azure_file_parameters: Optional[pulumi.Input[pulumi.InputType['VolumeProviderParametersAzureFileArgs']]] = None, description: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, provider: Optional[pulumi.Input[Union[str, 'VolumeProvider']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, volume_name: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = VolumeArgs.__new__(VolumeArgs) __props__.__dict__["azure_file_parameters"] = azure_file_parameters __props__.__dict__["description"] = description __props__.__dict__["location"] = location if provider is None and not opts.urn: raise TypeError("Missing required property 'provider'") __props__.__dict__["provider"] = provider if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["tags"] = tags __props__.__dict__["volume_name"] = volume_name __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:servicefabricmesh:Volume"), pulumi.Alias(type_="azure-native:servicefabricmesh/v20180901preview:Volume")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Volume, __self__).__init__( 'azure-native:servicefabricmesh/v20180701preview:Volume', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Volume': """ Get an existing Volume resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = VolumeArgs.__new__(VolumeArgs) __props__.__dict__["azure_file_parameters"] = None __props__.__dict__["description"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["provider"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None return Volume(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="azureFileParameters") def azure_file_parameters(self) -> pulumi.Output[Optional['outputs.VolumeProviderParametersAzureFileResponse']]: """ This type describes a volume provided by an Azure Files file share. """ return pulumi.get(self, "azure_file_parameters") @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: """ User readable description of the volume. """ return pulumi.get(self, "description") @property @pulumi.getter def location(self) -> pulumi.Output[str]: """ The geo-location where the resource lives """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The name of the resource """ return pulumi.get(self, "name") @property @pulumi.getter def provider(self) -> pulumi.Output[str]: """ Provider of the volume. """ return pulumi.get(self, "provider") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ State of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. """ return pulumi.get(self, "type")
[ "noreply@github.com" ]
bpkgoud.noreply@github.com
68124a7b67fd1c6095d96303a8aca0f384c4afdc
8acffb8c4ddca5bfef910e58d3faa0e4de83fce8
/ml-flask/Lib/site-packages/transformers/benchmark/benchmark_args_tf.py
cd36a0cecd7e703e619b11f5e9e7cad729ff38b1
[ "MIT" ]
permissive
YaminiHP/SimilitudeApp
8cbde52caec3c19d5fa73508fc005f38f79b8418
005c59894d8788c97be16ec420c0a43aaec99b80
refs/heads/master
2023-06-27T00:03:00.404080
2021-07-25T17:51:27
2021-07-25T17:51:27
389,390,951
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:afce00f23314b1eaf01e6b9073d8607e187acc93116a0521b1dc0774527c6b52 size 4573
[ "yamprakash130@gmail.com" ]
yamprakash130@gmail.com
47bc42a6c5aa9ec5584da4120261c20195f8b5b2
fdb9bdc6c4ab2f14ba71e544493706d5e275899f
/fhir/resources/R4B/coding.py
fbfc479eed95b3821cf73e2b01b529bc8a6270ca
[ "BSD-3-Clause" ]
permissive
nazrulworld/fhir.resources
6ae8aea8180c611b0c5050759c6dcdf63e4cb061
1fd6ea476b27b3fcb8c4ef8f23bc51cf161e69e3
refs/heads/main
2023-08-30T18:27:27.277249
2023-07-03T19:57:06
2023-07-03T19:57:06
165,297,877
256
83
NOASSERTION
2023-08-24T15:34:05
2019-01-11T19:26:41
Python
UTF-8
Python
false
false
3,954
py
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Coding Release: R4B Version: 4.3.0 Build ID: c475c22 Last updated: 2022-05-28T12:47:40.239+10:00 """ from pydantic import Field from . import element, fhirtypes class Coding(element.Element): """Disclaimer: Any field name ends with ``__ext`` doesn't part of Resource StructureDefinition, instead used to enable Extensibility feature for FHIR Primitive Data Types. A reference to a code defined by a terminology system. """ resource_type = Field("Coding", const=True) code: fhirtypes.Code = Field( None, alias="code", title="Symbol in syntax defined by the system", description=( "A symbol in syntax defined by the system. The symbol may be a " "predefined code or an expression in a syntax defined by the coding " "system (e.g. post-coordination)." ), # if property is element of this resource. element_property=True, ) code__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_code", title="Extension field for ``code``." ) display: fhirtypes.String = Field( None, alias="display", title="Representation defined by the system", description=( "A representation of the meaning of the code in the system, following " "the rules of the system." ), # if property is element of this resource. element_property=True, ) display__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_display", title="Extension field for ``display``." ) system: fhirtypes.Uri = Field( None, alias="system", title="Identity of the terminology system", description=( "The identification of the code system that defines the meaning of the " "symbol in the code." ), # if property is element of this resource. element_property=True, ) system__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_system", title="Extension field for ``system``." ) userSelected: bool = Field( None, alias="userSelected", title="If this coding was chosen directly by the user", description=( "Indicates that this coding was chosen by a user directly - e.g. off a " "pick list of available items (codes or displays)." ), # if property is element of this resource. element_property=True, ) userSelected__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_userSelected", title="Extension field for ``userSelected``." ) version: fhirtypes.String = Field( None, alias="version", title="Version of the system - if relevant", description=( "The version of the code system which was used when choosing this code." " Note that a well-maintained code system does not need the version " "reported, because the meaning of codes is consistent across versions. " "However this cannot consistently be assured, and when the meaning is " "not guaranteed to be consistent, the version SHOULD be exchanged." ), # if property is element of this resource. element_property=True, ) version__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_version", title="Extension field for ``version``." ) @classmethod def elements_sequence(cls): """returning all elements names from ``Coding`` according specification, with preserving original sequence order. """ return [ "id", "extension", "system", "version", "code", "display", "userSelected", ]
[ "connect2nazrul@gmail.com" ]
connect2nazrul@gmail.com
aabda3c3f3bf812d7795a082ede806aac3d5fa23
8b4516cb0b39a9cdd81656d788443992d1cdf11c
/setup.py
2177e876e8f0ebf3db288220b09885128a7ee444
[]
no_license
zwl-max/mmdetection_clw
321e7c2af349bce5d54c4e2388be0833937b9645
d6d05ce10e2cebe8fac72c06cf79a88e0b1bbefb
refs/heads/main
2023-04-04T00:42:59.671784
2021-04-12T17:06:49
2021-04-12T17:06:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,306
py
#!/usr/bin/env python import os from setuptools import find_packages, setup import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) def readme(): with open('README.md', encoding='utf-8') as f: content = f.read() return content version_file = 'mmdet/version.py' def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__'] def make_cuda_ext(name, module, sources, sources_cuda=[]): define_macros = [] extra_compile_args = {'cxx': []} if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1': define_macros += [('WITH_CUDA', None)] extension = CUDAExtension extra_compile_args['nvcc'] = [ '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] sources += sources_cuda else: print(f'Compiling {name} without CUDA') extension = CppExtension return extension( name=f'{module}.{name}', sources=[os.path.join(*module.split('.'), p) for p in sources], define_macros=define_macros, extra_compile_args=extra_compile_args) def parse_requirements(fname='requirements.txt', with_version=True): """Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())" """ import sys from os.path import exists import re require_fpath = fname def parse_line(line): """Parse information from a line in a requirements text file.""" if line.startswith('-r '): # Allow specifying requirements in other files target = line.split(' ')[1] for info in parse_require_file(target): yield info else: info = {'line': line} if line.startswith('-e '): info['package'] = line.split('#egg=')[1] elif '@git+' in line: info['package'] = line else: # Remove versioning from the package pat = '(' + '|'.join(['>=', '==', '>']) + ')' parts = re.split(pat, line, maxsplit=1) parts = [p.strip() for p in parts] info['package'] = parts[0] if len(parts) > 1: op, rest = parts[1:] if ';' in rest: # Handle platform specific dependencies # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies version, platform_deps = map(str.strip, rest.split(';')) info['platform_deps'] = platform_deps else: version = rest # NOQA info['version'] = (op, version) yield info def parse_require_file(fpath): with open(fpath, 'r') as f: for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): for info in parse_line(line): yield info def gen_packages_items(): if exists(require_fpath): for info in parse_require_file(require_fpath): parts = [info['package']] if with_version and 'version' in info: parts.extend(info['version']) if not sys.version.startswith('3.4'): # apparently package_deps are broken in 3.4 platform_deps = info.get('platform_deps') if platform_deps is not None: parts.append(';' + platform_deps) item = ''.join(parts) yield item packages = list(gen_packages_items()) return packages if __name__ == '__main__': setup( name='mmdet', version=get_version(), description='OpenMMLab Detection Toolbox and Benchmark', long_description=readme(), long_description_content_type='text/markdown', author='OpenMMLab', author_email='openmmlab@gmail.com', keywords='computer vision, object detection', url='https://github.com/open-mmlab/mmdetection', packages=find_packages(exclude=('configs', 'tools', 'demo')), classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], license='Apache License 2.0', setup_requires=parse_requirements('requirements/build.txt'), tests_require=parse_requirements('requirements/tests.txt'), install_requires=parse_requirements('requirements/runtime.txt'), extras_require={ 'all': parse_requirements('requirements.txt'), 'tests': parse_requirements('requirements/tests.txt'), 'build': parse_requirements('requirements/build.txt'), 'optional': parse_requirements('requirements/optional.txt'), }, ext_modules=[ make_cuda_ext( name="deform_conv_cuda", module="mmdet.models.utils.dcn", sources=["src/deform_conv_cuda.cpp", "src/deform_conv_cuda_kernel.cu"], ), make_cuda_ext( name="deform_pool_cuda", module="mmdet.models.utils.dcn", sources=["src/deform_pool_cuda.cpp", "src/deform_pool_cuda_kernel.cu"], ), ], cmdclass={'build_ext': BuildExtension}, zip_safe=False)
[ "623497281@qq.com" ]
623497281@qq.com
6482dd6d3f523eae4b49c9c65952243b23ecdf56
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/components/metrics/net/DEPS
df18a66dd19fb30a0ed7f84f6657cd48a48c334c
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
Python
false
false
178
include_rules = [ "+chromeos/dbus", "+chromeos/network", "+components/data_use_measurement/core", "+components/variations", "+net", "+third_party/cros_system_api", ]
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
ccb8c6765f17d87c44c46722046e8925fa3aacce
40028d1859d9653386ed6c59e22fc539f17d5c64
/ecommerseapi/api/models.py
8a4a50e7074964385d3888b859bf4ea7504f8134
[]
no_license
shobhit1215/E_Commerse_API
20da72298c6ded5b4590a84443fb2f9f2dee177c
76cd8915609f02050138c5c4d47ba13c8050223b
refs/heads/main
2023-06-08T10:31:11.747416
2021-06-06T14:20:47
2021-06-06T14:20:47
373,506,156
1
0
null
null
null
null
UTF-8
Python
false
false
1,931
py
from django.db import models from django.contrib.auth.models import User # Create your models here class Category(models.Model): title = models.CharField(max_length=100) class Meta: verbose_name_plural='categories' def __str__(self): return self.title class Book(models.Model): title = models.CharField(max_length=50) category = models.ForeignKey(Category,related_name='books',on_delete=models.CASCADE) author = models.CharField(max_length=100,default='John Doe') isbn = models.CharField(max_length=20) pages = models.IntegerField() price = models.IntegerField() stock = models.IntegerField() description = models.TextField() imageURL = models.URLField(max_length=500) status = models.BooleanField(default=True) date_created = models.DateField(auto_now_add=True) class Meta: ordering=['-date_created'] def __str__(self): return self.title class Product(models.Model): product_tag = models.CharField(max_length=10) name = models.CharField(max_length=100) category = models.ForeignKey(Category,related_name='products',on_delete=models.CASCADE) price = models.IntegerField() stock = models.IntegerField() imageURL = models.URLField() status = models.BooleanField(default=True) date_created = models.DateField(auto_now_add=True) class Meta: ordering=['-date_created'] def __str__(self): return '{} {}'.format(self.product_tag, self.name) class Cart(models.Model): cart_id = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) created_at = models.DateTimeField(auto_now_add=True) books = models.ForeignKey(Book,on_delete=models.CASCADE,default=1) products = models.ForeignKey(Product,on_delete=models.CASCADE,default=1) class Meta: ordering = ['cart_id','-created_at'] def __str__(self): return f'{self.cart_id}'
[ "imshobhit.sb@gmail.com" ]
imshobhit.sb@gmail.com
9951109087ec9d12722fc9f82d84fd9982978987
102a9e14dc7d86c4b397101b426c6846a6949d5d
/drdown/forum/tests/test_model_category.py
b6539b7ce9a0ccf0ea247e153b5b4927dadd1011
[ "MIT" ]
permissive
fga-eps-mds/2018.1-Dr-Down
2371535227aed7c09bbae9fd8871b8eac8068c05
3423374360105b06ac2c57a320bf2ee8deaa08a3
refs/heads/develop
2023-04-13T18:08:44.880516
2018-06-25T23:36:27
2018-06-25T23:36:27
124,143,479
3
13
MIT
2021-03-29T17:31:49
2018-03-06T21:55:37
Python
UTF-8
Python
false
false
2,358
py
from test_plus.test import TestCase from drdown.forum.models.model_category import Category class ModelTestCase(TestCase): def setUp(self): """ This method will run before any test case. """ self.category1 = Category.objects.create( name='Medicamentos', description='Tipo de Medicamento', slug='med', ) self.category2 = Category.objects.create( name='Eventos', description='Tipo de Eventos', slug='event', ) def tearDown(self): """ This method will run after any test. """ self.category1.delete() self.category2.delete() def test_save_name_ok(self): """ Test to verify if name of category is the correct passed """ self.assertEquals(self.category1.name, 'Medicamentos') self.assertEquals(self.category2.name, 'Eventos') def test_save_description_ok(self): """ Test to verify if description is the correct passed """ self.assertEquals(self.category1.description, 'Tipo de Medicamento') self.assertEquals(self.category2.description, 'Tipo de Eventos') def test_save_slug_ok(self): """ Test to verify if slug is the correct passed """ self.assertEquals(self.category1.slug, 'med') self.assertEquals(self.category2.slug, 'event') def test_save_name_error(self): """ Test to verify if name of category really fail """ self.assertNotEquals(self.category1.name, '') self.assertNotEquals(self.category2.name, '') def test_save_description_error(self): """ Test to verify if description really fail """ self.assertNotEquals(self.category1.description, '') self.assertNotEquals(self.category2.description, '') def test_save_slug_error(self): """ Test to verify if slug really fail """ self.assertNotEquals(self.category1.slug, '') self.assertNotEquals(self.category2.slug, '') def test_str_is_equal_to_title(self): """ Method `__str__` should be equal to field `title` """ self.assertEqual(self.category1.__str__(), self.category1.name)
[ "joberth.rogers18@gmail.com" ]
joberth.rogers18@gmail.com
8fc7138fff62bf36605f163a89c9620cc018d8a0
53bab92377bf98e2c98e0d94b95c5c6f7c3aef31
/bbs/templatetags/table.py
49d0207fbf38a6665c638e2c78d310fdf3811a93
[]
no_license
seiya0723/assets_manager_01
e4a3d7b5bf00803be41261d1ac72db9f878bf58d
c421f3e728836d45077f745a7f26766361a9fe24
refs/heads/master
2023-05-31T14:12:25.713436
2021-06-19T01:04:58
2021-06-19T01:04:58
378,149,413
0
0
null
null
null
null
UTF-8
Python
false
false
1,075
py
from django import template register = template.Library() @register.inclusion_tag("bbs/table.html") def generate_balance(topics): balances = [] # TODO:ページネーション化させる時はこの時点でこれまでのページの残高を計算しておく total = 0 for topic in topics: row = {} row["id"] = topic.id row["category"] = topic.category row["title"] = topic.title row["comment"] = topic.comment row["income"] = topic.income row["spending"] = topic.spending row["dt"] = topic.dt row["pay_dt"] = topic.pay_dt # total = total + row["income"] - row["spending"] if row["spending"]: spending = int(row["spending"]) else: spending = 0 if row["income"]: income = int(row["income"]) else: income = 0 total = total + income - spending row["total"] = total balances.append(row) return {"balances": balances}
[ "seiya@asahina" ]
seiya@asahina
255cd831c415c060347e3abee618ed7d545d1406
4cb8c8f11c2a19a75495771b1d6b53881cd67b58
/Production/test/condorSub/dict_wjets.py
712d8b7480e597b4af4713672f587c5df75c08b8
[]
no_license
kpedro88/TreeMaker
d7498274106067e56aebbed7f086fbee8bf46f7e
0260dc10392e4828452e559beb3b6dc8fa765df5
refs/heads/upgrade2017
2023-07-06T13:24:04.465706
2018-04-03T17:56:48
2018-04-03T17:56:48
38,841,239
0
1
null
2021-11-11T17:20:57
2015-07-09T19:35:41
Python
UTF-8
Python
false
false
1,367
py
flist = { "scenario": "Summer16", "samples": [ ['Summer16.WJetsToLNu_HT-100To200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_HT-200To400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_HT-200To400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_HT-600To800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_HT-600To800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_HT-1200To2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_HT-1200To2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_HT-2500ToInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_HT-2500ToInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1'], ['Summer16.WJetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8'], ['Summer16.WJetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext2'], ] }
[ "kpedro88@gmail.com" ]
kpedro88@gmail.com
6609db224439f06b9e1265ebd59eea9c2ba6e642
75dcb56e318688499bdab789262839e7f58bd4f6
/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master(1)/id055-Matching_Words.py
f700af4611d805c49ae2c364c9265a046a60b80d
[]
no_license
syurskyi/Algorithms_and_Data_Structure
9a1f358577e51e89c862d0f93f373b7f20ddd261
929dde1723fb2f54870c8a9badc80fc23e8400d3
refs/heads/master
2023-02-22T17:55:55.453535
2022-12-23T03:15:00
2022-12-23T03:15:00
226,243,987
4
1
null
2023-02-07T21:01:45
2019-12-06T04:14:10
Jupyter Notebook
UTF-8
Python
false
false
120
py
import collections; print (' '.join(sorted([x for x, y in collections.Counter(raw_input().split()).items() if y > 1])))
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
5aacee947944b556598823f2dc0174abf527df76
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_1/kochie/main.py
d0b158a2aab7b94c30ec932f4a95c829ee42d1d4
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
904
py
__author__ = 'Robert' def main(): with open("A-large.in") as input_data: data = input_data.readlines() for i in range(1, len(data)): solution = count_sheep(data[i][0:-1]) print("Case #{0}: {1}".format(i, solution)) with open("A-large.out", "a") as out_data: out_data.write("Case #{0}: {1}\n".format(i, solution)) def count_sheep(number): number = int(number) numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} a = number if number == 0: return "INSOMNIA" else: while numbers: a = str(a) for digit in a: if digit in numbers: numbers.remove(digit) else: pass a = int(a) a += number return a - number if __name__ == '__main__': main()
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
f6a6a40912984765f880af58386530c7c612fdb1
52b5773617a1b972a905de4d692540d26ff74926
/.history/FrogRiver_20200723131519.py
6effa38dcc4a1b3b5fdf8f76bfbf253c3caa9f2f
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
214
py
def Frog(X,A): # given x where the frog wants to go # find earliest time # once you get the second that has that position # return the second for i in A: print(Frog(5,[1,3,1,4,2,3,]))
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
d497ebe83fb0fc8317599a55ee0b0965f03144e7
795df757ef84073c3adaf552d5f4b79fcb111bad
/elliptic_integral/elliptic_pia.py
cf5577cb036a99449ebb86a48fffbc5007c68c9e
[]
no_license
tnakaicode/jburkardt-python
02cb2f9ba817abf158fc93203eb17bf1cb3a5008
1a63f7664e47d6b81c07f2261b44f472adc4274d
refs/heads/master
2022-05-21T04:41:37.611658
2022-04-09T03:31:00
2022-04-09T03:31:00
243,854,197
3
0
null
null
null
null
UTF-8
Python
false
false
2,415
py
#! /usr/bin/env python3 # def elliptic_pia ( n, a ): #*****************************************************************************80 # ## ELLIPTIC_PIA evaluates the complete elliptic integral Pi(N,A). # # Discussion: # # This is one form of what is sometimes called the complete elliptic # integral of the third kind. # # The function is defined by the formula: # # Pi(N,A) = integral ( 0 <= T <= PI/2 ) # dT / (1 - N sin^2(T) ) sqrt ( 1 - sin^2(A) * sin ( T )^2 ) # # In MATLAB, the function can be evaluated by: # # ellipticPi(n,(sin(a*pi/180)^2) # # The value is computed using Carlson elliptic integrals: # # k = sin ( a * pi / 180 ) # Pi(n,k) = RF ( 0, 1 - k^2, 1 ) + 1/3 n RJ ( 0, 1 - k^2, 1, 1 - n ) # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 02 June 2018 # # Author: # # John Burkardt # # Parameters: # # Input, real N, A, the arguments. # # Output, real VALUE, the function value. # from rf import rf from rj import rj import numpy as np k = np.sin ( a * np.pi / 180.0 ) x = 0.0 y = ( 1.0 - k ) * ( 1.0 + k ) z = 1.0 p = 1.0 - n errtol = 1.0E-03 value1, ierr = rf ( x, y, z, errtol ) value2, ierr = rj ( x, y, z, p, errtol ) value = value1 + n * value2 / 3.0 return value def elliptic_pia_test ( ): #*****************************************************************************80 # ## ELLIPTIC_PIA_TEST tests ELLIPTIC_PIA. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 02 June 2018 # # Author: # # John Burkardt # from elliptic_pia_values import elliptic_pia_values print ( '' ) print ( 'ELLIPTIC_PIA_TEST:' ) print ( ' ELLIPTIC_PIA returns values of' ) print ( ' the complete elliptic integral of the' ) print ( ' third kind, with parameter angle A.' ) print ( '' ) print ( ' N A Pi(N,A) Pi(N,A)' ) print ( ' Tabulated Calculated' ) print ( '' ) n_data = 0 while ( True ): n_data, n, a, pia = elliptic_pia_values ( n_data ) if ( n_data == 0 ): break pia2 = elliptic_pia ( n, a ) print ( ' %14.6f %14.6f %24.16g %24.16g' % ( n, a, pia, pia2 ) ) return if ( __name__ == '__main__' ): from timestamp import timestamp timestamp ( ) elliptic_pia_test ( ) timestamp ( )
[ "tnakaicode@gmail.com" ]
tnakaicode@gmail.com
e0b2f99cbca64ba9f6779056bc840ddd61ca06bd
bc441bb06b8948288f110af63feda4e798f30225
/easy_flow_sdk/model/topology/property_pb2.pyi
d0dbef32cc3fe22a59c299ab9123bf7e0f71f90a
[ "Apache-2.0" ]
permissive
easyopsapis/easyops-api-python
23204f8846a332c30f5f3ff627bf220940137b6b
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
refs/heads/master
2020-06-26T23:38:27.308803
2020-06-16T07:25:41
2020-06-16T07:25:41
199,773,131
5
0
null
null
null
null
UTF-8
Python
false
false
2,822
pyi
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from easy_flow_sdk.model.topology.cmdb_instance_pb2 import ( CmdbInstance as easy_flow_sdk___model___topology___cmdb_instance_pb2___CmdbInstance, ) from easy_flow_sdk.model.topology.strategy_pb2 import ( Strategy as easy_flow_sdk___model___topology___strategy_pb2___Strategy, ) from google.protobuf.descriptor import ( Descriptor as google___protobuf___descriptor___Descriptor, ) from google.protobuf.internal.containers import ( RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer, ) from google.protobuf.message import ( Message as google___protobuf___message___Message, ) from typing import ( Iterable as typing___Iterable, Optional as typing___Optional, Text as typing___Text, Union as typing___Union, ) from typing_extensions import ( Literal as typing_extensions___Literal, ) builtin___bool = bool builtin___bytes = bytes builtin___float = float builtin___int = int if sys.version_info < (3,): builtin___buffer = buffer builtin___unicode = unicode class Property(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... objectId = ... # type: typing___Text instanceId = ... # type: typing___Text @property def strategy(self) -> easy_flow_sdk___model___topology___strategy_pb2___Strategy: ... @property def relateInstances(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[easy_flow_sdk___model___topology___cmdb_instance_pb2___CmdbInstance]: ... def __init__(self, *, objectId : typing___Optional[typing___Text] = None, instanceId : typing___Optional[typing___Text] = None, strategy : typing___Optional[easy_flow_sdk___model___topology___strategy_pb2___Strategy] = None, relateInstances : typing___Optional[typing___Iterable[easy_flow_sdk___model___topology___cmdb_instance_pb2___CmdbInstance]] = None, ) -> None: ... if sys.version_info >= (3,): @classmethod def FromString(cls, s: builtin___bytes) -> Property: ... else: @classmethod def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> Property: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def HasField(self, field_name: typing_extensions___Literal[u"strategy",b"strategy"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"instanceId",b"instanceId",u"objectId",b"objectId",u"relateInstances",b"relateInstances",u"strategy",b"strategy"]) -> None: ...
[ "service@easyops.cn" ]
service@easyops.cn
bbbd2d726161d9fb00f8dc6eefd6b35ec2230fb4
3da6b8a0c049a403374e787149d9523012a1f0fc
/Coder_Old/pycharm_daima/爬虫大师班/代理/ip_test.py
2f983188dcfea397ba5a11c983db0967a738a609
[]
no_license
AndersonHJB/PyCharm_Coder
d65250d943e84b523f022f65ef74b13e7c5bc348
32f2866f68cc3a391795247d6aba69a7156e6196
refs/heads/master
2022-07-25T11:43:58.057376
2021-08-03T02:50:01
2021-08-03T02:50:01
348,922,058
3
3
null
2021-09-05T02:20:10
2021-03-18T02:57:16
Python
UTF-8
Python
false
false
1,308
py
# !/usr/bin/python3 # -*- coding: utf-8 -*- # @Author:AI悦创 @DateTime :2020/2/2 15:36 @Function :功能 Development_tool :PyCharm # code is far away from bugs with the god animal protecting #    I love animals. They taste delicious. import requests # url = 'https://www.kuaidaili.com/free/' # url = 'https://www.kuaidaili.com/free/inha/2/' # url = 'https://www.kuaidaili.com/free/inha/3/' # url = 'https://www.kuaidaili.com/free/inha/4/' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36', 'Referer': 'https://www.kuaidaili.com', } session = requests.Session() session.headers = headers def Crawl_Spider(): url_list = ['https://www.kuaidaili.com/free/inha/{}'.format(page) for page in range(1,3)] for url in url_list: print(url) html = session.get(url, headers = headers) # html.encoding = html.apparent_encoding html.encoding = 'gbk' print(html.status_code) print(html.text) if __name__ == '__main__': Crawl_Spider() # proxies = { # 'http': 'http://10.10.1.10:3128', # 'https': 'http://10.10.1.10:1080', # } # try: # html = requests.get('http://icanhazip.com', proxies=proxies, timeout=1) # print(html.status_code) # except: # pass
[ "1432803776@qq.com" ]
1432803776@qq.com
61027afb89c2cbe3b76699d2d494ba891d4779b8
e514bbdf8e0abe5ef0b58b94fe5f7d2afb38ea6b
/test_suite/system_tests/scripts/frame_order/cam/iso_cone.py
89a05903a501948e08f4b948fb8b3f2df9ede2b7
[]
no_license
edward-dauvergne/relax
98ad63703e68a4535bfef3d6c0529e07cc84ff29
9710dc0f2dfe797f413756272d4bec83cf6ca1c9
refs/heads/master
2020-04-07T04:25:25.382027
2017-01-04T15:38:09
2017-01-04T15:38:09
46,500,334
1
1
null
null
null
null
UTF-8
Python
false
false
2,134
py
############################################################################### # # # Copyright (C) 2012-2014 Edward d'Auvergne # # # # This file is part of the program relax (http://www.nmr-relax.com). # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### # Module docstring. """Script for optimising the isotropic cone frame order test model of CaM.""" # relax module imports. from base_script import Base_script from lib.frame_order.variables import MODEL_ISO_CONE class Analysis(Base_script): # Set up some class variables. DIRECTORY = 'iso_cone' MODEL = MODEL_ISO_CONE AXIS_THETA = 0.96007997859534299767 AXIS_PHI = 4.03227550621962294031 CONE_THETA = 0.6 CONE_SIGMA_MAX = 0.9 #LOAD_STATE = True # Execute the analysis. Analysis(self._execute_uf)
[ "bugman@b7916896-f9f9-0310-9fe5-b3996d8957d5" ]
bugman@b7916896-f9f9-0310-9fe5-b3996d8957d5
71489e2a730b9d585b1695295c9ff3b287aad20f
552556631580799b16d0fb31e8f10850383ef3b2
/ex3/outputs/astar/astar.DW_32-WS_064.out/info.py
586a79bd1699b923cc3bab97288cf9b5e20c148e
[]
no_license
gregth/NTUA-advcomparch
f19ee414f8b77f749a09f263feb980350f88880d
bc501f427ddf1423f851ce1a052dc335183c5103
refs/heads/master
2022-11-14T20:11:49.035503
2020-06-27T09:17:43
2020-06-27T09:17:43
262,262,423
0
2
null
null
null
null
UTF-8
Python
false
false
18,827
py
power = {'BUSES': {'Area': 1.51446, 'Bus/Area': 1.51446, 'Bus/Gate Leakage': 0.00754019, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0786284, 'Bus/Subthreshold Leakage with power gating': 0.0294857, 'Gate Leakage': 0.00754019, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthreshold Leakage': 0.0786284, 'Subthreshold Leakage with power gating': 0.0294857}, 'Core': [{'Area': 184.621, 'Execution Unit/Area': 137.377, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.0, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202689, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.0, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.712714, 'Execution Unit/Instruction Scheduler/Area': 99.7953, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.31611, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00142193, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.68822, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.104134, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0189637, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.0102364, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.34276, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 60.828, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.31154, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 123.522, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 1.01891, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 4.72247, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 2.69123, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 196.541, 'Execution Unit/Instruction Scheduler/ROB/Area': 38.6511, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.0297974, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 71.33, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.588692, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.468244, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.183113, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 1.71174, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 5.20968, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 2.88458, 'Execution Unit/Integer ALUs/Area': 3.76696, 'Execution Unit/Integer ALUs/Gate Leakage': 0.212233, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.0761327, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.182934, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 3.21776, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 1.20666, 'Execution Unit/Peak Dynamic': 196.81, 'Execution Unit/Register Files/Area': 28.3565, 'Execution Unit/Register Files/Floating Point RF/Area': 9.63068, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.00825445, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.0175024, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.128663, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.0497709, 'Execution Unit/Register Files/Gate Leakage': 0.026159, 'Execution Unit/Register Files/Integer RF/Area': 18.7258, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.0179046, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.142477, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.145724, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.273097, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.103541, 'Execution Unit/Register Files/Peak Dynamic': 0.142477, 'Execution Unit/Register Files/Runtime Dynamic': 0.163227, 'Execution Unit/Register Files/Subthreshold Leakage': 0.40176, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.153311, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.210396, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.0266427, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0402783, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 1.04186, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.403943, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.151479, 'Execution Unit/Runtime Dynamic': 3.60648, 'Execution Unit/Subthreshold Leakage': 10.586, 'Execution Unit/Subthreshold Leakage with power gating': 4.90334, 'Gate Leakage': 1.0969, 'Instruction Fetch Unit/Area': 21.7974, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000853062, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000853062, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000751993, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000296018, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000308396, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00276651, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00785837, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.116348, 'Instruction Fetch Unit/Instruction Buffer/Area': 2.64509, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 0.0346434, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 497.007, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 2.11291, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.290984, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.110014, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.31277, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0997209, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 14.8639, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 10.9923, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0700968, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 510.058, 'Instruction Fetch Unit/Runtime Dynamic': 2.29335, 'Instruction Fetch Unit/Subthreshold Leakage': 1.35897, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.569197, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.0476918, 'L2/Runtime Dynamic': 0.0133275, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 9.11865, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 2.18001, 'Load Store Unit/Data Cache/Runtime Dynamic': 0.470383, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0578642, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0305048, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.0305048, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 2.59149, 'Load Store Unit/Runtime Dynamic': 0.651327, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.0752196, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.150439, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.728535, 'Load Store Unit/Subthreshold Leakage with power gating': 0.334749, 'Memory Management Unit/Area': 0.743537, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0266957, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0274111, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.0308614, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.0816233, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.0163505, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 1.50659, 'Memory Management Unit/Runtime Dynamic': 0.0437617, 'Memory Management Unit/Subthreshold Leakage': 0.213824, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0912885, 'Peak Dynamic': 1040.19, 'Renaming Unit/Area': 6.65402, 'Renaming Unit/FP Front End RAT/Area': 0.168486, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 21.1714, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925, 'Renaming Unit/Free List/Area': 1.14677, 'Renaming Unit/Free List/Gate Leakage': 0.000181868, 'Renaming Unit/Free List/Peak Dynamic': 1.30603, 'Renaming Unit/Free List/Runtime Dynamic': 0.0166569, 'Renaming Unit/Free List/Subthreshold Leakage': 0.00363194, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.00179151, 'Renaming Unit/Gate Leakage': 0.0397953, 'Renaming Unit/Int Front End RAT/Area': 4.98475, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.00867665, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 304.203, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 1.93036, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.136044, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.0775451, 'Renaming Unit/Peak Dynamic': 329.172, 'Renaming Unit/Runtime Dynamic': 1.94702, 'Renaming Unit/Subthreshold Leakage': 0.340283, 'Renaming Unit/Subthreshold Leakage with power gating': 0.163091, 'Runtime Dynamic': 8.55526, 'Subthreshold Leakage': 15.9396, 'Subthreshold Leakage with power gating': 7.16692}], 'DRAM': {'Area': 0, 'Gate Leakage': 0, 'Peak Dynamic': 0.9653755470077123, 'Runtime Dynamic': 0.9653755470077123, 'Subthreshold Leakage': 4.252, 'Subthreshold Leakage with power gating': 4.252}, 'L3': [{'Area': 61.9075, 'Gate Leakage': 0.0484137, 'Peak Dynamic': 0.0685374, 'Runtime Dynamic': 0.0231651, 'Subthreshold Leakage': 6.80085, 'Subthreshold Leakage with power gating': 3.32364}], 'Processor': {'Area': 248.043, 'Gate Leakage': 1.15286, 'Peak Dynamic': 1040.25, 'Peak Power': 1064.23, 'Runtime Dynamic': 8.57843, 'Subthreshold Leakage': 22.819, 'Subthreshold Leakage with power gating': 10.6757, 'Total Cores/Area': 184.621, 'Total Cores/Gate Leakage': 1.0969, 'Total Cores/Peak Dynamic': 1040.19, 'Total Cores/Runtime Dynamic': 8.55526, 'Total Cores/Subthreshold Leakage': 15.9396, 'Total Cores/Subthreshold Leakage with power gating': 7.16692, 'Total L3s/Area': 61.9075, 'Total L3s/Gate Leakage': 0.0484137, 'Total L3s/Peak Dynamic': 0.0685374, 'Total L3s/Runtime Dynamic': 0.0231651, 'Total L3s/Subthreshold Leakage': 6.80085, 'Total L3s/Subthreshold Leakage with power gating': 3.32364, 'Total Leakage': 23.9719, 'Total NoCs/Area': 1.51446, 'Total NoCs/Gate Leakage': 0.00754019, 'Total NoCs/Peak Dynamic': 0.0, 'Total NoCs/Runtime Dynamic': 0.0, 'Total NoCs/Subthreshold Leakage': 0.0786284, 'Total NoCs/Subthreshold Leakage with power gating': 0.0294857}}
[ "gregthanasoulas@gmail.com" ]
gregthanasoulas@gmail.com
fec0bc215597217e9037b9916c94e29b98c8eeb0
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/7/r0a.py
3f272fcfb59e98d7736a30ad74b89a06ca97175f
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'r0A': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
b0baa479b033bd29837c2a9f4e3a838c7a5127db
9140ba97a4ff6e9ef9f4e49d67ab238b669a3597
/verify/migrations/0001_initial.py
c3671a31e432d3d8842519b23a9845a56ab6c277
[]
no_license
poojapauskar/foodromeoproject-api
877ada5d72db0ac364e735a1ad7af0f46ad02bcc
2007ed7ae12a3f5d1d227faaccaf7e6bd93f760d
refs/heads/master
2021-01-21T13:30:31.838067
2016-05-09T06:41:10
2016-05-09T06:41:10
54,105,875
0
0
null
null
null
null
UTF-8
Python
false
false
869
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-19 12:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Verify', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('email', models.EmailField(default=b'', max_length=100)), ('password', models.CharField(default=b'', max_length=100)), ('confirmed', models.CharField(default=b'', max_length=100)), ], options={ 'ordering': ('created',), }, ), ]
[ "git.poojapauskar@gmail.com" ]
git.poojapauskar@gmail.com
757da35bcf9e29eb2f8637c05bb3c0f0bf47ff64
786232b3c9eac87728cbf2b5c5636d7b6f10f807
/Leetcode/medium/179.py
bdfde1bbaf3d55528702f8c3f435055590278c86
[]
no_license
luoyanhan/Algorithm-and-data-structure
c9ada2e123fae33826975665be37ca625940ddd4
fb42c3a193f58360f6b6f3b7d5d755cd6e80ad5b
refs/heads/master
2021-12-22T15:45:28.260386
2021-12-02T03:08:35
2021-12-02T03:08:35
251,007,078
0
0
null
null
null
null
UTF-8
Python
false
false
297
py
class Solution: def largestNumber(self, nums): from functools import cmp_to_key temp = sorted(list(map(str, nums)), key=cmp_to_key(lambda x, y: int(x+y)-int(y+x)), reverse=True) return ''.join(temp if temp[0] != '0' else '0') print(Solution().largestNumber([10,2]))
[ "707025023@qq.com" ]
707025023@qq.com
629fe2adc3713e315432d3b15fd4fba274bebdcb
ae13e905feec06f2f94245481b31fcb605e485de
/practice/algorithms/sorting/running_time_of_algorithms.py
17ad574e552f3d72e89f7b310cc6e374b6d893e3
[]
no_license
feadoor/hackerrank
e7a84bb20c01d420a3c37f0a7e5176ab0aac6604
8fa88b71d37ae83b0826a76499c9e69f947d0aeb
refs/heads/master
2021-05-04T17:28:27.089671
2019-02-21T17:25:34
2019-02-21T17:25:34
120,271,651
0
0
null
null
null
null
UTF-8
Python
false
false
696
py
#!/usr/local/bin/pypy3 def read_space_separated_integers(): return [int(x) for x in input().strip().split(' ')] def do_step(values, curr_idx): curr = values[curr_idx] for idx in range(curr_idx - 1, -1, -1): if values[idx] > curr: values[idx + 1] = values[idx] else: values[idx + 1] = curr return curr_idx - idx - 1 else: values[0] = curr return curr_idx def insertion_sort_shifts(values): return sum(do_step(values, idx) for idx in range(1, len(values))) def main(): _, values = input(), read_space_separated_integers() print(insertion_sort_shifts(values)) if __name__ == '__main__': main()
[ "sam.capplemanlynes@gmail.com" ]
sam.capplemanlynes@gmail.com
be56930ad1eee66ec01c8926ba39ee318fecbaaf
ec85250addb7357dfe7bb3e0680d53fc7b0fd8fb
/python_modules/libraries/dagster-snowflake-pyspark/dagster_snowflake_pyspark_tests/test_version.py
c22e2549820ed9442e2c4eb4c5d04a21559e40bc
[ "Apache-2.0" ]
permissive
dagster-io/dagster
6adb5deee8bcf3ea1866a6a64f2ed81e1db5e73a
fe21995e0402878437a828c6a4244025eac8c43b
refs/heads/master
2023-09-05T20:46:08.203794
2023-09-05T19:54:52
2023-09-05T19:54:52
131,619,646
8,565
1,154
Apache-2.0
2023-09-14T21:57:37
2018-04-30T16:30:04
Python
UTF-8
Python
false
false
103
py
from dagster_snowflake_pyspark.version import __version__ def test_version(): assert __version__
[ "noreply@github.com" ]
dagster-io.noreply@github.com
5dc83ed2b8b1d5fbec5ca51398141236af407567
aa4024b6a846d2f6032a9b79a89d2e29b67d0e49
/GM2AUTOSAR_MM/Properties/unit_contracts/HUnitR04a_IsolatedLHS.py
1ba6aae69ee4d2788ef8b611c16c451ffdad007c
[ "MIT" ]
permissive
levilucio/SyVOLT
41311743d23fdb0b569300df464709c4954b8300
0f88827a653f2e9d3bb7b839a5253e74d48379dc
refs/heads/master
2023-08-11T22:14:01.998341
2023-07-21T13:33:36
2023-07-21T13:33:36
36,246,850
3
2
MIT
2023-07-21T13:33:39
2015-05-25T18:15:26
Python
UTF-8
Python
false
false
2,513
py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitR04a_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitR04a_IsolatedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitR04a_IsolatedLHS, self).__init__(name='HUnitR04a_IsolatedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitR04a_IsolatedLHS') self["equations"] = [] # Set the node attributes # match class PhysicalNode(4.0.m.0PhysicalNode) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__PhysicalNode""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'4.0.m.0PhysicalNode') # match class Partition(4.0.m.1Partition) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Partition""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'4.0.m.1Partition') # match class Module(4.0.m.2Module) node self.add_node() self.vs[2]["MT_pre__attr1"] = """return True""" self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__Module""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'4.0.m.2Module') # match class Scheduler(4.0.m.3Scheduler) node self.add_node() self.vs[3]["MT_pre__attr1"] = """return True""" self.vs[3]["MT_label__"] = """4""" self.vs[3]["mm__"] = """MT_pre__Scheduler""" self.vs[3]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'4.0.m.3Scheduler') # match class Service(4.0.m.4Service) node self.add_node() self.vs[4]["MT_pre__attr1"] = """return True""" self.vs[4]["MT_label__"] = """5""" self.vs[4]["mm__"] = """MT_pre__Service""" self.vs[4]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'4.0.m.4Service') # define evaluation methods for each apply class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True def eval_attr13(self, attr_value, this): return True def eval_attr14(self, attr_value, this): return True def eval_attr15(self, attr_value, this): return True def constraint(self, PreNode, graph): return True
[ "bentleyjoakes@gmail.com" ]
bentleyjoakes@gmail.com
ac87d87525a2a7a63d565f016d76f063a999f440
2bdedcda705f6dcf45a1e9a090377f892bcb58bb
/src/main/output/DNS/car/job_group_morning_mother/history/way/information/car.py
9a3868ea3b6b3e2c6836fc812a9b7b4faa377dcb
[]
no_license
matkosoric/GenericNameTesting
860a22af1098dda9ea9e24a1fc681bb728aa2d69
03f4a38229c28bc6d83258e5a84fce4b189d5f00
refs/heads/master
2021-01-08T22:35:20.022350
2020-02-21T11:28:21
2020-02-21T11:28:21
242,123,053
1
0
null
null
null
null
UTF-8
Python
false
false
1,564
py
'use strict'; let https = require ('https'); // ********************************************** // *** Update or verify the following values. *** // ********************************************** // Replace the subscriptionKey string value with your valid subscription key. let subscriptionKey = '956bf92f63606179b70abdd657524465'; let host = 'api.microsofttranslator.com'; let path = '/V2/Http.svc/TranslateArray'; let target = 'fr-fr'; let params = ''; let ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; let content = '<TranslateArrayRequest>\n' + // NOTE: AppId is required, but it can be empty because we are sending the Ocp-Apim-Subscription-Key header. ' <AppId />\n' + ' <Texts>\n' + ' <string xmlns=\"' + ns + '\">Hello</string>\n' + ' <string xmlns=\"' + ns + '\">Goodbye</string>\n' + ' </Texts>\n' + ' <To>' + target + '</To>\n' + '</TranslateArrayRequest>\n'; let response_handler = function (response) { let body = ''; response.on ('data', function (d) { body += d; }); response.on ('end', function () { console.log (body); }); response.on ('error', function (e) { console.log ('Error: ' + e.message); }); }; let TranslateArray = function () { let request_params = { method : 'POST', hostname : host, path : path + params, headers : { 'Content-Type' : 'text/xml', '30d5b1752ddf8cef3c90f48f26c8fbf5' : subscriptionKey, } }; let req = https.request (request_params, response_handler); req.write (content); req.end (); } TranslateArray ();
[ "soric.matko@gmail.com" ]
soric.matko@gmail.com
bf4f5a8e047458e90c20456c37a3e40e2fda51c2
77b16dcd465b497c22cf3c096fa5c7d887d9b0c2
/Tan_ShinYi/Assignments/Python_Fundamentals/Selection_Sort.py
09d9c318ca543d40256519af0d891fbfe65a5aac
[ "MIT" ]
permissive
curest0x1021/Python-Django-Web
a7cf8a45e0b924ce23791c18f6a6fb3732c36322
6264bc4c90ef1432ba0902c76b567cf3caaae221
refs/heads/master
2020-04-26T17:14:20.277967
2016-10-18T21:54:39
2016-10-18T21:54:39
173,706,702
6
0
null
null
null
null
UTF-8
Python
false
false
412
py
import random nums = [] for i in range(100): nums.append(int((random.random())*10000)) #fills empty nums list with 100 random int's from 0-1000 count=0 while count<(len(nums)-1): min_place=count for i in range(count,len(nums)): if nums[i]<nums[min_place]: min_place=i nums[count], nums[min_place]=nums[min_place], nums[count] count+=1 print nums #prints sorted list
[ "43941751+curest0x1021@users.noreply.github.com" ]
43941751+curest0x1021@users.noreply.github.com
086d8ff799a7540f1931f3cd2a406d7bedad981d
1e1e4ca56b0363d267d9cbef2ea24fdb6f52c025
/day10/进程池.py
2c4017405c16b3bcf4c886842c6c792d9867239e
[]
no_license
yuyuyuyushui/s14
c478ec59f3f5e63cd0e336e30ab3e8dea92f5894
bcc1716c2e2dab86f1fd529f654d8b34fd7efb93
refs/heads/master
2021-04-06T00:33:05.542098
2018-03-24T15:52:04
2018-03-24T15:52:04
116,809,247
0
0
null
null
null
null
UTF-8
Python
false
false
412
py
import multiprocessing import os,time def f(i): time.sleep(2) print(os.getpid()) return i+200 def bar(arg): print('--exce--',arg,os.getpid()) if __name__ == '__main__': pool = multiprocessing.Pool(processes=5)#建立进程池 print(os.getpid()) for i in range(10): pool.apply_async(func=f,args=(i,),callback=bar)#并行调用 print('end') pool.close() pool.join()
[ "786313105@qq.com" ]
786313105@qq.com
061e1a6a8220ce1294d21994f1de664fcd50ee6d
88b91b19a659e90aea4b2cf4da6418f2fd04b9ef
/testPractice/repository/rental_repository.py
c26675b066279181cbcef775dc627f6df79d3ce4
[]
no_license
GeorgianBadita/Python-Problems
d759d7099486179532f9c0f456099ba780b89468
e0324bf24bfc801cc68404f86c720926e144e5aa
refs/heads/master
2021-09-03T01:51:49.865850
2018-01-04T18:03:03
2018-01-04T18:03:03
107,010,845
6
0
null
null
null
null
UTF-8
Python
false
false
1,805
py
""" @author: Badita Marin-Georgian @email: geo.badita@gmail.com @date: 12/10/2017 19:28 """ from repository.client_repository import RepositoryException class RentalRepository: ''' Class controlling the rental data ''' def __init__(self, rent_validator): ''' Function that inits the RentalRepository :param rent_validator: validator for Rental class ''' self.__list = {} self.__validator = rent_validator def get_all_rents(self): ''' Function that gets all rents as a list :return: ''' return list(self.__list.values()) def store_rental(self, rental): ''' Function that stores a rental into the list :post: if the rental doesn't exists in the list, the rental will be added :param rental: Rental type object :return: ''' new_id = len(self.get_all_rents()) + 1 rental.set_rental_id(new_id) if rental.get_rental_id() not in self.get_all_rents(): self.__list[new_id] = rental else: raise RepositoryException("Duplicated ID!") def find_rental(self, rental_id): ''' Function that finds a rental by a given id :param rental_id: :return: ''' all_r = self.get_all_rents() for rental in all_r: if rental.get_rental_id() == rental_id: return rental return None def delete_rental(self, rental_id): ''' Functon that deletes a rental, by rental_id :param rental_id: :return: ''' rent_del = self.find_rental(rental_id) if rental_id is None: return None del self.__list[rental_id] return rent_del
[ "geo.badita@gmail.com" ]
geo.badita@gmail.com
1b403491a8d428779b0a35f972ab5513d4e83ace
c90674d955fe1399c0e99cf34437e583d1cf9fb9
/loop2.py
824c0c074802ea462bb02e3e49e7750afaf7f5ae
[]
no_license
TrellixVulnTeam/My_python_code_QQZ2
556878cbe4f8d6d92e71f48285a6d2439b10ca81
8cd8b697d92e1a79cce109baf560eeff27717ce8
refs/heads/master
2023-03-19T15:26:35.836114
2018-06-29T14:09:06
2018-06-29T14:09:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
names = ["a","b","c"] emaildomain = ["gmail","hotmail","yahoo"] for i,j in zip(names,emaildomain): text = i+"@"+j print(text)
[ "apple@Apples-MacBook-Pro.local" ]
apple@Apples-MacBook-Pro.local
43956a4b7bdeceabe1c6152721cde3980124cf70
473fc28d466ddbe9758ca49c7d4fb42e7d82586e
/app/src/main/java/com/syd/source/aosp/external/toolchain-utils/get_common_image_version.py
da36b98fcf8ba6ea1b5a51ae49d4d952fd6136e3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lz-purple/Source
a7788070623f2965a8caa3264778f48d17372bab
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
refs/heads/master
2020-12-23T17:03:12.412572
2020-01-31T01:54:37
2020-01-31T01:54:37
237,205,127
4
2
null
null
null
null
UTF-8
Python
false
false
2,561
py
#!/usr/bin/python2 # # Copyright 2013 Google Inc. All Rights Reserved. """Script to find list of common images (first beta releases) in Chromeos. Display information about stable ChromeOS/Chrome versions to be used by the team developers. The purpose is to increase team productivity by using stable (known and tested) ChromeOS/Chrome versions instead of using randomly selected versions. Currently we define as a "stable" version the first Beta release in a particular release cycle. """ from __future__ import print_function __author__ = 'llozano@google.com (Luis Lozano)' import argparse import pickle import re import sys import urllib VERSIONS_HISTORY_URL = 'http://cros-omahaproxy.appspot.com/history' def DisplayBetas(betas): print('List of betas from %s' % VERSIONS_HISTORY_URL) for beta in betas: print(' Release', beta['chrome_major_version'], beta) return def FindAllBetas(all_versions): """Get ChromeOS first betas from History URL.""" all_betas = [] prev_beta = {} for line in all_versions: match_obj = re.match( r'(?P<date>.*),(?P<chromeos_version>.*),' r'(?P<chrome_major_version>\d*).(?P<chrome_minor_version>.*),' r'(?P<chrome_appid>.*),beta-channel,,Samsung Chromebook Series 5 550', line) if match_obj: if prev_beta: if (prev_beta['chrome_major_version'] != match_obj.group('chrome_major_version')): all_betas.append(prev_beta) prev_beta = match_obj.groupdict() if prev_beta: all_betas.append(prev_beta) return all_betas def SerializeBetas(all_betas, serialize_file): with open(serialize_file, 'wb') as f: pickle.dump(all_betas, f) print('Serialized list of betas into', serialize_file) return def Main(argv): """Get ChromeOS first betas list from history URL.""" parser = argparse.ArgumentParser() parser.add_argument('--serialize', dest='serialize', default=None, help='Save list of common images into the specified ' 'file.') options = parser.parse_args(argv) try: opener = urllib.URLopener() all_versions = opener.open(VERSIONS_HISTORY_URL) except IOError as ioe: print('Cannot open', VERSIONS_HISTORY_URL) print(ioe) return 1 all_betas = FindAllBetas(all_versions) DisplayBetas(all_betas) if options.serialize: SerializeBetas(all_betas, options.serialize) all_versions.close() return 0 if __name__ == '__main__': retval = Main(sys.argv[1:]) sys.exit(retval)
[ "997530783@qq.com" ]
997530783@qq.com
6583249fabc74884a3eef7897d442bc0e7b7e6c4
d6f84bfc45de7e0e2cb9d058549642b4a50bb23c
/draw2image.py
989cc8209b80108b46ef6ea9512390f77600b50e
[]
no_license
MadhuV99/pypilzet
f007de7213b1cc190f379d9f98ad977d9566e83e
7583b2480fbf32ec8ef8bb62ae685a9c9fafb4cc
refs/heads/main
2023-02-08T11:07:16.855357
2020-12-27T03:36:50
2020-12-27T03:36:50
324,604,495
0
0
null
null
null
null
UTF-8
Python
false
false
554
py
# draw2image.py #!/usr/bin/python from PIL import Image, ImageDraw import sys my_img_rect = Image.new('RGBA', (200, 200), 'white') idraw = ImageDraw.Draw(my_img_rect) idraw.rectangle((10, 10, 100, 100), fill='blue') my_img_rect.show() my_img_fldr = r".\my_imgs\\" my_img_pic = r"rectangle" my_img_format = r".png" my_out_pic = my_img_pic+"_draw" my_out_file = my_img_fldr+my_out_pic+my_img_format try: # img.save('rectangle.png') my_img_rect.save(my_out_file, 'png') except IOError: print("Unable to save image") sys.exit(1)
[ "madhuvasudevan@yahoo.com" ]
madhuvasudevan@yahoo.com
e8be57f2d75bd38180bc6f61eeb02cdb845ad0e4
1adb3f388f06e11d9f85ba00be61931b16304146
/brc_python/reviews/admin.py
d3ad9f6c08e08a7eefd873863a93d89397b79c2a
[]
no_license
jeanruggiero/brc-web
b315e2670a6251a4768b01fe6663c213e5c9d63f
7ac2301a8019da4ffa8e16ea2face94b75dadfa7
refs/heads/master
2021-09-24T00:46:17.498207
2020-01-27T02:59:41
2020-01-27T02:59:41
228,442,226
0
0
null
2021-09-22T18:28:07
2019-12-16T17:44:56
JavaScript
UTF-8
Python
false
false
317
py
from django.contrib import admin from .models import LeavenworthReview, SkillsNightReview, Squamish1Review, \ Squamish2Review, GradClimbReview, InstructorReview admin.site.register([LeavenworthReview, SkillsNightReview, Squamish1Review, Squamish2Review, GradClimbReview, InstructorReview])
[ "jeanruggiero@gmail.com" ]
jeanruggiero@gmail.com
ee177ad5248cdfb57d2f75318dbc120fd3a1113a
26d6c34df00a229dc85ad7326de6cb5672be7acc
/msgraph-cli-extensions/beta/planner_beta/azext_planner_beta/vendored_sdks/planner/aio/operations/_groups_operations.py
2f8dcc1e8df93e9e9efc38e6d1f109232ea6558d
[ "MIT" ]
permissive
BrianTJackett/msgraph-cli
87f92471f68f85e44872939d876b9ff5f0ae6b2c
78a4b1c73a23b85c070fed2fbca93758733f620e
refs/heads/main
2023-06-23T21:31:53.306655
2021-07-09T07:58:56
2021-07-09T07:58:56
386,993,555
0
0
NOASSERTION
2021-07-17T16:56:05
2021-07-17T16:56:05
null
UTF-8
Python
false
false
9,518
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class GroupsOperations: """GroupsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~planner.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get_planner( self, group_id: str, select: Optional[List[Union[str, "models.Get1ItemsItem"]]] = None, expand: Optional[List[Union[str, "models.Get2ItemsItem"]]] = None, **kwargs ) -> "models.MicrosoftGraphPlannerGroup": """Get planner from groups. Get planner from groups. :param group_id: key: id of group. :type group_id: str :param select: Select properties to be returned. :type select: list[str or ~planner.models.Get1ItemsItem] :param expand: Expand related entities. :type expand: list[str or ~planner.models.Get2ItemsItem] :keyword callable cls: A custom type or function that will be passed the direct response :return: MicrosoftGraphPlannerGroup, or the result of cls(response) :rtype: ~planner.models.MicrosoftGraphPlannerGroup :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.MicrosoftGraphPlannerGroup"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) accept = "application/json" # Construct URL url = self.get_planner.metadata['url'] # type: ignore path_format_arguments = { 'group-id': self._serialize.url("group_id", group_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if select is not None: query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.OdataError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MicrosoftGraphPlannerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_planner.metadata = {'url': '/groups/{group-id}/planner'} # type: ignore async def update_planner( self, group_id: str, body: "models.MicrosoftGraphPlannerGroup", **kwargs ) -> None: """Update the navigation property planner in groups. Update the navigation property planner in groups. :param group_id: key: id of group. :type group_id: str :param body: New navigation property values. :type body: ~planner.models.MicrosoftGraphPlannerGroup :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_planner.metadata['url'] # type: ignore path_format_arguments = { 'group-id': self._serialize.url("group_id", group_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(body, 'MicrosoftGraphPlannerGroup') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.OdataError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) update_planner.metadata = {'url': '/groups/{group-id}/planner'} # type: ignore async def delete_planner( self, group_id: str, if_match: Optional[str] = None, **kwargs ) -> None: """Delete navigation property planner for groups. Delete navigation property planner for groups. :param group_id: key: id of group. :type group_id: str :param if_match: ETag. :type if_match: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) accept = "application/json" # Construct URL url = self.delete_planner.metadata['url'] # type: ignore path_format_arguments = { 'group-id': self._serialize.url("group_id", group_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] # Construct headers header_parameters = {} # type: Dict[str, Any] if if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.OdataError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete_planner.metadata = {'url': '/groups/{group-id}/planner'} # type: ignore
[ "japhethobalak@gmail.com" ]
japhethobalak@gmail.com
93fc3918c0adf0e6cc267eb31cea767f7c925ba3
74be814f7cd10d3c91a53460bd6698aa8bc95704
/剑指offer/面试题66. 构建乘积数组.py
90873a93e5900fe421206f4e8f6a77e68c282d3f
[]
no_license
weiyuyan/LeetCode
7202f7422bc3bef6bd35ea299550b51905401656
19db0e78826d3e3d27d2574abd9d461eb41458d1
refs/heads/master
2020-12-03T17:10:53.738507
2020-05-27T08:28:36
2020-05-27T08:28:36
231,402,839
2
0
null
null
null
null
UTF-8
Python
false
false
1,536
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ShidongDu time:2020/3/7 ''' 给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B 中的元素 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。 不能使用除法。 示例: 输入: [1,2,3,4,5] 输出: [120,60,40,30,24]   提示: 所有元素乘积之和不会溢出 32 位整数 a.length <= 100000 ''' # 构造前缀树 class Solution: def constructArr(self, A): if not A: return [] prefix = [1]*len(A) prefix[0]=1 for i in range(1,len(A)): prefix[i] = prefix[i-1]*A[i-1] cur_suffix = 1 for i in range(len(A)-1,-1,-1): prefix[i] = prefix[i] * cur_suffix cur_suffix *= A[i] return prefix # 方法二 from typing import List class Solution: # 将数组分为两部分数组C和D # C[i] = A[0]*A[1]*...*A[i-1] # D[i] = A[i+1]*A[i+2]*...*A[n-1] # C[i]可以用自上到下的方法算出来,即C[i] = C[i-1]*A[i-1] # D[i]可以用自下到上的方法算出来,即D[i] = D[i+1]*A[i+1] def constructArr(self, a: List[int]) -> List[int]: C, D = [1]*len(a), [1]*len(a) res = [] for i in range(1, len(a)): C[i] = C[i-1]*a[i-1] for j in range(len(a)-2, -1, -1): D[j] = D[j+1]*a[j+1] for k in range(len(a)): res.append(C[k]*D[k]) return res solution = Solution() array = [1, 2] res = solution.constructArr(array) print(res)
[ "244128764@qq.com" ]
244128764@qq.com
0aaa65c940fe287810eb79b7feb929c0cc22be6e
001002103510c9f96addeaea7a9861ca24442829
/src/data/datasets/__init__.py
0046350ab2049495ba41179e8cbcce31ba057395
[]
no_license
Tung-I/Mango
d21caf95d737947730186d4369c3327a11ff00d2
7cf2ee84251e8c6c07f37a52dec8750f322086bb
refs/heads/master
2022-10-25T04:58:09.701042
2020-06-16T07:28:51
2020-06-16T07:28:51
261,380,873
0
0
null
null
null
null
UTF-8
Python
false
false
191
py
from .base_dataset import BaseDataset from .mango_dataset import MangoDataset from .cifar_dataset import CIFARDataset from .aug_dataset import AugDataset from .test_dataset import TestDataset
[ "dong893610@gmail.com" ]
dong893610@gmail.com
4de0ff2cd80ffb3061918f2941c6feffb3a36ff4
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/python/testData/resolve/TupleInExcept.py
1ebd91de1cde02793b85153112647b10932d971c
[ "Apache-2.0" ]
permissive
JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560889
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
2023-09-12T07:41:58
2011-09-30T13:33:05
null
UTF-8
Python
false
false
187
py
import errno try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print "I/O error({0}): {1}".format(e<ref>rrno, strerror)
[ "yole@jetbrains.com" ]
yole@jetbrains.com
d20e5a24ef5e784cc61dd6f91edf377bf6f668d6
439386f9097632d44d31d1f599df76ec2820d072
/常规项目/约牌房/1600/YuePai/src/cases/dfqp_enter.py
8336784584c0075cb0c7edab93f0eeade1ec7387
[]
no_license
YiFeng0755/testcase
33693f0940a6497aa40e2e51a0535c9eb6c12b29
edc19480c3e94cbcbf004aa9d20099ec6d1b9304
refs/heads/master
2020-04-28T04:34:28.232022
2019-03-11T11:13:25
2019-03-11T11:13:25
146,287,761
0
0
null
null
null
null
UTF-8
Python
false
false
3,845
py
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' 入口 ''' import time from runcenter.enums import EnumPriority,EnumStatus from runcenter.testcase import debug_run_all,TestCase from uilib.hall_page import Hall_Page from uilib.game_page import Game_Page from uilib.yuepai_page import Yuepai_Page from common.common import Common class C70432_Yuepai_display(TestCase): ''' 约牌房开启,游戏选场列表正常显示约牌房入口 ''' owner = "LucyLiu" status = EnumStatus.Design priority = EnumPriority.High timeout = 10 def pre_test(self): self.common = Common() self.hall_page = Hall_Page() self.game_page = Game_Page() self.yuepai_page = Yuepai_Page() # 初始化Luadriver self.start_step("初始化driver") self.luadriver = self.common.setupdriver() # 每个用例都需要关闭活动,把这个放在初始化里面实现 self.common.closeactivity(self.luadriver) def run_test(self): ''' 测试用例 ''' self.start_step("等待页面加载完成") self.hall_page.wait_element("同步标志") self.start_step("获取子游戏列表") game_list = self.game_page.get_game_list() for i in range(len(game_list)): game_list[i].click() self.game_page.game_is_download() if (self.game_page.element_is_exist("约牌按钮")==True): self.game_page.screenshot("%s.png" %game_list[i].get_attribute("name")) self.game_page.wait_element("约牌按钮").click() self.start_step("进入约牌房") self.game_page.wait_element("返回").click() time.sleep(3) else: self.log_info("无约牌房") try: self.game_page.wait_element("返回1",20).click() except: self.log_info("返回失败") def post_test(self): ''' 测试用例执行完成后,清理测试环境 ''' self.common.closedriver() class C70433_Yuepai_display(TestCase): ''' 约牌房关闭,游戏选场列表正常隐藏约牌房入口 ''' owner = "LucyLiu" status = EnumStatus.Design priority = EnumPriority.High timeout = 10 def pre_test(self): self.common = Common() self.hall_page = Hall_Page() self.game_page = Game_Page() self.yuepai_page = Yuepai_Page() # 初始化Luadriver self.start_step("初始化driver") self.luadriver = self.common.setupdriver() # 每个用例都需要关闭活动,把这个放在初始化里面实现 self.common.closeactivity(self.luadriver) def run_test(self): ''' 测试用例 ''' self.start_step("等待页面加载完成") self.hall_page.wait_element("同步标志") self.start_step("获取子游戏列表") game_list = self.game_page.get_game_list() for i in range(len(game_list)): game_list[i].click() self.game_page.game_is_download() if (self.game_page.element_is_exist("约牌按钮") == False): self.game_page.screenshot("%s.png" % game_list[i].get_attribute("name")) else: self.log_info("有约牌房") try: self.game_page.wait_element("返回1", 20).click() except: self.log_info("返回失败") def post_test(self): ''' 测试用例执行完成后,清理测试环境 ''' self.common.closedriver() # __qtaf_seq_tests__ = [C70524_Recorddisplay] if __name__ == '__main__': # C039_DFQP_Activity = C039_DFQP_Activity() # C039_DFQP_Activity.debug_run() debug_run_all()
[ "YoungLiu@boyaa.com" ]
YoungLiu@boyaa.com
d793f58074e7c3e61444249240e95137417aac64
39a1d46fdf2acb22759774a027a09aa9d10103ba
/model-optimizer/unit_tests/extensions/front/CTCGreedyDecoderReplacement_test.py
063d71173e1f7e5c923ffaf1190fff21491ce5c9
[ "Apache-2.0" ]
permissive
mashoujiang/openvino
32c9c325ffe44f93a15e87305affd6099d40f3bc
bc3642538190a622265560be6d88096a18d8a842
refs/heads/master
2023-07-28T19:39:36.803623
2021-07-16T15:55:05
2021-07-16T15:55:05
355,786,209
1
3
Apache-2.0
2021-06-30T01:32:47
2021-04-08T06:22:16
C++
UTF-8
Python
false
false
5,203
py
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest from extensions.front.CTCGreedyDecoderReplacement import CTCGreedyDecoderReplacement, CTCGreedyDecoderWithSparseToDenseShapeReplacement from mo.front.common.partial_infer.utils import int64_array from mo.utils.ir_engine.compare_graphs import compare_graphs from unit_tests.utils.graph import build_graph, const class CTCGreedyDecoderReplacementTests(unittest.TestCase): def test1(self): nodes_attributes = { # nodes from original graph 'logits': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'}, 'seq_len': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'}, 'order_arr': {'kind': 'op', 'op': 'Const'}, 'transpose': {'type': 'Transpose', 'kind': 'op', 'op': 'Transpose'}, 'decoder': {'kind': 'op', 'op': 'CTCGreedyDecoderSeqLen', 'merge_repeated': True}, 'cast': {'kind': 'op', 'op': 'Cast'}, 'sparse_to_dense': {'kind': 'op', 'op': 'SparseToDense'}, 'last': {'type': None, 'value': None, 'kind': 'op', 'op': 'Result'}, # new nodes 'new_decoder': {'kind': 'op', 'op': 'CTCGreedyDecoderSeqLen', 'use_mask_format': True}, **const('squeeze_axes', int64_array([2, 3])), 'squeeze_dec_seq': {'kind': 'op', 'op': 'Squeeze'}, 'cast_to_int': {'kind': 'op', 'op': 'Cast'}, } graph = build_graph(nodes_attributes, [('logits', 'decoder', {'out': 0, 'in': 0}), ('seq_len', 'decoder', {'out': 0, 'in': 1}), ('decoder', 'sparse_to_dense', {'out': 0, 'in': 0}), ('decoder', 'sparse_to_dense', {'out': 2, 'in': 1}), ('decoder', 'cast', {'out': 1, 'in': 0}), ('cast', 'sparse_to_dense', {'out': 0}), ('sparse_to_dense', 'last', {'out': 0, 'in': 0}), ], nodes_with_edges_only=True) graph.stage = 'front' CTCGreedyDecoderWithSparseToDenseShapeReplacement().find_and_replace_pattern(graph) graph_ref = build_graph(nodes_attributes, [('logits', 'transpose', {'out': 0, 'in': 0}), ('order_arr', 'transpose', {'out': 0, 'in': 1}), ('transpose', 'decoder', {'out': 0, 'in': 0}), ('seq_len', 'decoder', {'out': 0, 'in': 1}), ('decoder', 'last', {'out': 0, 'in': 0}), ], nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'last', check_op_attrs=True) self.assertTrue(flag, resp) def test2(self): nodes_attributes = { # nodes from original graph 'logits': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'}, 'seq_len': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'}, 'order_arr': {'kind': 'op', 'op': 'Const'}, 'transpose': {'type': 'Transpose', 'kind': 'op', 'op': 'Transpose'}, 'decoder': {'kind': 'op', 'op': 'CTCGreedyDecoderSeqLen', 'merge_repeated': True}, 'cast': {'kind': 'op', 'op': 'Cast'}, 'sparse_to_dense': {'kind': 'op', 'op': 'SparseToDense'}, 'last': {'type': None, 'value': None, 'kind': 'op', 'op': 'Result'}, # new nodes 'new_decoder': {'kind': 'op', 'op': 'CTCGreedyDecoderSeqLen', 'use_mask_format': True}, **const('squeeze_axes', int64_array([2, 3])), 'squeeze_dec_seq': {'kind': 'op', 'op': 'Squeeze'}, 'cast_to_int': {'kind': 'op', 'op': 'Cast'}, } graph = build_graph(nodes_attributes, [('logits', 'decoder', {'out': 0, 'in': 0}), ('seq_len', 'decoder', {'out': 0, 'in': 1}), ('decoder', 'sparse_to_dense', {'out': 0, 'in': 0}), ('decoder', 'cast', {'out': 1, 'in': 0}), ('cast', 'sparse_to_dense', {'out': 0}), ('sparse_to_dense', 'last', {'out': 0, 'in': 0}), ], nodes_with_edges_only=True) graph.stage = 'front' CTCGreedyDecoderReplacement().find_and_replace_pattern(graph) graph_ref = build_graph(nodes_attributes, [('logits', 'transpose', {'out': 0, 'in': 0}), ('order_arr', 'transpose', {'out': 0, 'in': 1}), ('transpose', 'decoder', {'out': 0, 'in': 0}), ('seq_len', 'decoder', {'out': 0, 'in': 1}), ('decoder', 'last', {'out': 0, 'in': 0}), ], nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'last', check_op_attrs=True) self.assertTrue(flag, resp)
[ "noreply@github.com" ]
mashoujiang.noreply@github.com
ac7b07e642d05dc0d1ff270fac4e20c2f046348c
200bc48000f6821b5d449ddc3d3269b8e10623be
/dashboard/dashboard/delete_old_tests.py
3ef7ab087b74c2a09d26736697a77184db18b203
[ "BSD-3-Clause" ]
permissive
marcelfarres/catapult
97dab55fc2b231e47fe245c12e76f7169dfa7227
f49c20888bb8ea3208efa29a2eb625ffb926ebc4
refs/heads/master
2021-01-18T04:39:58.000436
2016-06-28T17:49:43
2016-06-28T17:49:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,276
py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A cron job which queues old tests for deletion.""" import datetime from google.appengine.api import taskqueue from google.appengine.datastore import datastore_query from dashboard import datastore_hooks from dashboard import list_tests from dashboard import request_handler from dashboard import utils from dashboard.models import graph_data _CUTOFF_DATE = datetime.timedelta(days=183) # Six months ago _TESTS_TO_CHECK_AT_ONCE = 100 # Queue name needs to be listed in queue.yaml. _TASK_QUEUE_NAME = 'delete-old-tests-queue' _DELETE_TASK_QUEUE_NAME = 'delete-tests-queue' class DeleteOldTestsHandler(request_handler.RequestHandler): """Finds tests with no new data, and deletes them.""" def post(self): """Query for tests, and put ones with no new data on the delete queue.""" datastore_hooks.SetPrivilegedRequest() cursor = datastore_query.Cursor(urlsafe=self.request.get('cursor')) tests, next_cursor, more = graph_data.TestMetadata.query().fetch_page( _TESTS_TO_CHECK_AT_ONCE, keys_only=True, start_cursor=cursor) if more: taskqueue.add( url='/delete_old_tests', params={'cursor': next_cursor.urlsafe()}, queue_name=_TASK_QUEUE_NAME) for test in tests: # Delete this test if: # 1) It has no Rows newer than the cutoff # 2) It has no descendant tests no_new_rows = False last_row = graph_data.Row.query( graph_data.Row.parent_test == utils.OldStyleTestKey(test)).order( -graph_data.Row.timestamp).get() if last_row: if last_row.timestamp < datetime.datetime.today() - _CUTOFF_DATE: no_new_rows = True else: no_new_rows = True descendants = list_tests.GetTestDescendants(test, keys_only=True) descendants.remove(test) if not descendants and no_new_rows: taskqueue.add( url='/delete_test_data', params={ 'test_path': utils.TestPath(test), # For manual inspection. 'test_key': test.urlsafe(), }, queue_name=_DELETE_TASK_QUEUE_NAME)
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
85f92496e765df21ac2cd7377c68dff80637ed1d
7b102f9c8f2e3f9240090d1d67af50333a2ba98d
/shared_code/central_comp/non_fatal/dismod/cascade_ode/run_children.py
9b87545d7d12131ab52a929d1b26c53cba7a0b94
[]
no_license
Nermin-Ghith/ihme-modeling
9c8ec56b249cb0c417361102724fef1e6e0bcebd
746ea5fb76a9c049c37a8c15aa089c041a90a6d5
refs/heads/main
2023-04-13T00:26:55.363986
2020-10-28T19:51:51
2020-10-28T19:51:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,316
py
import logging from copy import copy import sys import drill from drill import Cascade, Cascade_loc import pandas as pd import multiprocessing as mp import gc import os from jobmon import job # Set dUSERt file mask to readable-for all users os.umask(0o0002) def run_loc(args): gc.collect() loc_id, sex_id, year, full_timespan, debug = args if debug: if full_timespan: cl = Cascade_loc(loc_id, sex_id, year, c, timespan=50, parent_loc=cl_parent) else: cl = Cascade_loc(loc_id, sex_id, year, c, parent_loc=cl_parent) cl.run_dismod() cl.summarize_posterior() cl.draw() cl.predict() return loc_id, 0 else: try: if full_timespan: cl = Cascade_loc(loc_id, sex_id, year, c, timespan=50, parent_loc=cl_parent) else: cl = Cascade_loc(loc_id, sex_id, year, c, parent_loc=cl_parent) cl.run_dismod() cl.summarize_posterior() cl.draw() cl.predict() return loc_id, 0 except Exception as e: logging.exception("Failure running location {}".format(loc_id)) return loc_id, str(e) if __name__ == "__main__": mvid = int(sys.argv[1]) location_id = int(sys.argv[2]) sex = sys.argv[3] y = int(sys.argv[4]) cv_iter = int(sys.argv[5]) try: if sys.argv[6]=="debug": debug = True else: debug = False except: debug = False if sex=='male': sex_id = 0.5 elif sex=='female': sex_id = -0.5 c = Cascade(mvid, reimport=False, cv_iter=cv_iter) try: j = job.Job(os.path.normpath(os.path.join(c.root_dir, '..'))) j.start() except IOError as e: logging.exception(e) except Exception as e: logging.exception(e) year_split_lvl = c.model_version_meta.fix_year.values[0]-1 lt = c.loctree this_lvl = lt.get_nodelvl_by_id(location_id) if location_id == 1: cl_parent = Cascade_loc(location_id, 0, 2000, c, reimport=False) else: cl_parent = Cascade_loc(location_id, sex_id, y, c, reimport=False) num_children = len(lt.get_node_by_id(location_id).children) num_cpus = mp.cpu_count() if not debug: pool = mp.Pool(min(num_cpus, num_children, 10)) # Run child locations arglist = [] for child_loc in lt.get_node_by_id(location_id).children: if this_lvl>=(year_split_lvl-1): full_timespan = False else: full_timespan = True arglist.append(( child_loc.id, sex_id, y, full_timespan, debug)) if debug: '..... RUNNING IN SINGLE PROCESS DEBUG MODE .....' res = map(run_loc, arglist) else: res = pool.map(run_loc, arglist) pool.close() pool.join() errors = ['%s: %s' % (str(r[0]), r[1]) for r in res if r[1] != 0] try: if len(errors) == 0: j.finish() else: error_msg = "; ".join(errors) j.log_error(error_msg) j.failed() except NameError as e: logging.exception(e) except Exception as e: logging.exception(e)
[ "nsidles@uw.edu" ]
nsidles@uw.edu
17a4bc2d55265f97b424078b0d607270b98f569a
32c56293475f49c6dd1b0f1334756b5ad8763da9
/google-cloud-sdk/lib/third_party/kubernetes/client/models/v1_handler.py
8fdb314fd03254108947f916c63f52e75d99f2df
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
bopopescu/socialliteapp
b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494
85bb264e273568b5a0408f733b403c56373e2508
refs/heads/master
2022-11-20T03:01:47.654498
2020-02-01T20:29:43
2020-02-01T20:29:43
282,403,750
0
0
MIT
2020-07-25T08:31:59
2020-07-25T08:31:59
null
UTF-8
Python
false
false
4,438
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.14.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1Handler(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { '_exec': 'V1ExecAction', 'http_get': 'V1HTTPGetAction', 'tcp_socket': 'V1TCPSocketAction' } attribute_map = { '_exec': 'exec', 'http_get': 'httpGet', 'tcp_socket': 'tcpSocket' } def __init__(self, _exec=None, http_get=None, tcp_socket=None): """ V1Handler - a model defined in Swagger """ self.__exec = None self._http_get = None self._tcp_socket = None self.discriminator = None if _exec is not None: self._exec = _exec if http_get is not None: self.http_get = http_get if tcp_socket is not None: self.tcp_socket = tcp_socket @property def _exec(self): """ Gets the _exec of this V1Handler. One and only one of the following should be specified. Exec specifies the action to take. :return: The _exec of this V1Handler. :rtype: V1ExecAction """ return self.__exec @_exec.setter def _exec(self, _exec): """ Sets the _exec of this V1Handler. One and only one of the following should be specified. Exec specifies the action to take. :param _exec: The _exec of this V1Handler. :type: V1ExecAction """ self.__exec = _exec @property def http_get(self): """ Gets the http_get of this V1Handler. HTTPGet specifies the http request to perform. :return: The http_get of this V1Handler. :rtype: V1HTTPGetAction """ return self._http_get @http_get.setter def http_get(self, http_get): """ Sets the http_get of this V1Handler. HTTPGet specifies the http request to perform. :param http_get: The http_get of this V1Handler. :type: V1HTTPGetAction """ self._http_get = http_get @property def tcp_socket(self): """ Gets the tcp_socket of this V1Handler. TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported :return: The tcp_socket of this V1Handler. :rtype: V1TCPSocketAction """ return self._tcp_socket @tcp_socket.setter def tcp_socket(self, tcp_socket): """ Sets the tcp_socket of this V1Handler. TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported :param tcp_socket: The tcp_socket of this V1Handler. :type: V1TCPSocketAction """ self._tcp_socket = tcp_socket def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map(lambda x: x.to_dict() if hasattr(x, 'to_dict') else x, value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item, value.items())) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, V1Handler): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "jonathang132298@gmail.com" ]
jonathang132298@gmail.com
b55fbb662ee45a07998c60bbe7ca4a437076ce1f
acd9ff3b087317a9f1261be1d376af80f12351cc
/snippets/sample.py
a6d2c160fc14edadd40a4273770b23f18dcae3e7
[ "MIT" ]
permissive
tgandor/urban_oculus
6f18f5fd39eae0db9309aebd5b206bea0cdb50e9
069a69ea35fe5072377d9b9cac15d285920d29e8
refs/heads/master
2022-10-03T19:34:37.518871
2022-09-26T23:45:00
2022-09-26T23:45:00
212,092,683
0
0
null
null
null
null
UTF-8
Python
false
false
310
py
# mogrify to successive qualities 50 imgs at a time # works best with val2017 ;) import glob import os imgs = sorted(glob.glob("*.jpg")) for q, img in zip((i for i in range(1, 101) for _ in range(50)), imgs): print(img) os.system(f"mogrify -quality {q} {img}") os.rename(img, f"{q:03d}_{img}")
[ "tomasz.gandor@gmail.com" ]
tomasz.gandor@gmail.com