text
stringlengths
8
6.05M
from __future__ import absolute_import, division, print_function from functools import partial import hydra import torch from easydict import EasyDict as edict from omegaconf import DictConfig, OmegaConf from torch.utils.data import DataLoader import kvt import kvt.augmentation from kvt.registry import ( DATASETS, HOOKS, LIGHTNING_MODULES, LOSSES, METRICS, OPTIMIZERS, SCHEDULERS, TRANSFORMS, ) from kvt.utils import build_from_config def build_dataloaders(config): dataloaders = [] datasets_config = config.dataset.dataset if isinstance(datasets_config, DictConfig): datasets_config = OmegaConf.to_container(datasets_config, resolve=True) if not isinstance(datasets_config, list): datasets_config = [datasets_config] for dataset_config in datasets_config: dataset_config = edict(dataset_config) for split_config in dataset_config.splits: # if isinstance(split_config, DictConfig): # split_config = OmegaConf.to_container(split_config, resolve=True) if isinstance(dataset_config, DictConfig): cfg = edict( { "name": dataset_config.name, "params": OmegaConf.to_container( dataset_config.params, resolve=True ), } ) else: cfg = edict( { "name": dataset_config.name, "params": dataset_config.params, } ) cfg.params.update(split_config) if config.print_config: print("---------------------------------------------------------------") print(f"dataset config: \n {cfg}") split = cfg.params.split is_train = cfg.params.mode == "train" if is_train: batch_size = config.trainer.train.batch_size else: batch_size = config.trainer.evaluation.batch_size # build transform transform_configs = { "split": split, "aug_cfg": config.augmentation.get(split), } for p in ["height", "width"]: if hasattr(config.augmentation, p): transform_configs[p] = getattr(config.augmentation, p) else: print(f"{p} is not in augmentation config") transform = build_from_config( config.dataset.transform, TRANSFORMS, default_args=transform_configs, ) # build dataset dataset = build_from_config( cfg, DATASETS, default_args={"transform": transform, "batch_size": batch_size}, ) dataloader = DataLoader( dataset, shuffle=is_train, batch_size=batch_size, drop_last=False, num_workers=config.dataset.transform.num_preprocessor, pin_memory=True, ) dataloaders.append( { "split": cfg.params.split, "mode": cfg.params.mode, "dataloader": dataloader, } ) return dataloaders def build_model(config): build_model_hook_config = {"name": "DefaultModelBuilderHook"} hooks = config.trainer.hooks if (hooks is not None) and ("build_model" in hooks): build_model_hook_config.update(hooks.build_model) build_model_fn = build_from_config(build_model_hook_config, HOOKS) return build_model_fn(config.trainer.model) def build_optimizer(config, model=None, **kwargs): # for specific optimizers that needs "base optimizer" if config.trainer.optimizer.name == "AGC": # optimizer: instance base_optimizer = build_from_config( config.trainer.optimizer.params.base, OPTIMIZERS, default_args=kwargs ) optimizer = getattr(kvt.optimizers, config.trainer.optimizer.name)( model.parameters(), base_optimizer, model=model, **{k: v for k, v in config.trainer.optimizer.params.items() if k != "base"}, ) elif config.trainer.optimizer.name == "SAM": # optimizer: class base_optimizer = OPTIMIZERS.get(config.trainer.optimizer.params.base.name) optimizer = getattr(kvt.optimizers, config.trainer.optimizer.name)( model.parameters(), base_optimizer, **{k: v for k, v in config.trainer.optimizer.params.items() if k != "base"}, ) else: optimizer = build_from_config( config.trainer.optimizer, OPTIMIZERS, default_args=kwargs ) return optimizer def build_scheduler(config, **kwargs): if config.trainer.scheduler is None: return None scheduler = build_from_config( config.trainer.scheduler, SCHEDULERS, default_args=kwargs ) return scheduler def build_loss(config, **kwargs): return build_from_config(config.trainer.loss, LOSSES, default_args=kwargs) def build_lightning_module(config, **kwargs): return build_from_config( config.trainer.lightning_module, LIGHTNING_MODULES, default_args=kwargs ) def build_callbacks(config): """pytorch_lightning callbacks""" callbacks = [] if config.trainer.callbacks is not None: for callback_name in config.trainer.callbacks: cfg = config.trainer.callbacks.get(callback_name) callback = hydra.utils.instantiate(cfg) callbacks.append(callback) return callbacks def build_logger(config): """pytorch_lightning logger""" logger = None cfg = config.trainer.logger if cfg is not None: logger = hydra.utils.instantiate(cfg) return logger def build_metrics(config): """pytorch_lightning metrics""" metrics = {} if config.trainer.metrics is not None: for name, cfg in config.trainer.metrics.items(): metrics[name] = build_from_config(cfg, METRICS) return edict(metrics) def build_hooks(config): # build default hooks post_forward_hook_config = {"name": "DefaultPostForwardHook"} if "hooks" in config.trainer: hooks = config.trainer.hooks if ("post_forward" in hooks) and (hooks.post_forward is not None): post_forward_hook_config.update(hooks.post_forward) hooks_dict = {} hooks_dict["post_forward_fn"] = build_from_config(post_forward_hook_config, HOOKS) hooks = edict(hooks_dict) return hooks def build_strong_transform(config): strong_transform, p = None, None if hasattr(config.augmentation, "strong_transform"): strong_cfg = config.augmentation.get("strong_transform") p = strong_cfg.p if hasattr(kvt.augmentation, strong_cfg.name): strong_transform = partial( getattr(kvt.augmentation, strong_cfg.name), **strong_cfg.params ) else: raise ValueError(f"kvt.augmentation does not contain {strong_cfg.name}") return strong_transform, p
# To create custom dicts we gotta inherit from the # UserDict class instead of the ususal dict import collections class StrKeyDict(collections.UserDict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def __contains__(self, key): return str(key) in self.data def __setitem__(self, key, item): self.data[str(key)] = item pins = StrKeyDict({'1': 'Pin 1', '13': 'Pin 13'}) print(pins) print('Pin 1 exists:', pins[1]) print('Pin 13 exists:', pins[13]) pins[12] = 'Pin 12' print('Pin 12 now exists:', pins[12])
import xlrd def Apriori(): each() listprep() list2() clear3() list3() tableone() tabletwo() clear() def each(): k=len(data) for i in data: x=0 for j in data[i]: x+=j if(x>=minsupport): support[i]=x print("L1 = >",support) def listprep(): y=[] for i in support: y.append(i) for j in support: if i is not j: x=[i,j] if j not in y: c2.append(x) print("c2 = > ",c2) def list2(): y=0 for j in c2: k=[j] x=0 for i in range(0,len(data[j[0]])): x+=data[j[0]][i]*data[j[1]][i] k.append(x) if x >= minsupport: L2[y]=k y+=1 print("L2 = > ",L2) def clear3(): y=[] for i in L2: y.append(L2[i][0]) for j in L2: if L2[j][0] not in y: k=L2[i][0] l=L2[j][0] if set(k) & set(l): x=[] for i in set(k) | set(l): x.append(i) C3.append(x) print("C3 = > ",C3) def list3(): for i in C3: k=0 y=[i] x=0 for j in range(0,len(data[i[0]])): x += data[i[0]][j] * data[i[1]][j]* data[i[2]][j] y.append(x) L3[k]=y print("L3 = > ",L3) def tableone(): for i in L3: arr=L3[i][0] spprt=L3[i][1] x=[] for j in range(0,len(arr)): x.append(arr[j]) for k in arr: if k not in x: a=[arr[j],k] b=arr y=set(b)-set(a) r=[] for q in y: r.append(q) C4.append([[arr[j],k],[q],spprt]) C4.append([[q],[arr[j],k],spprt]) print("C4 = >",C4) def tabletwo(): y = 0 for i in C4: x=0 j=i[0] if(len(j)>1): for k in range(0, len(data[j[0]])): x += data[j[0]][k] * data[j[1]][k] C4[y].append(i[2]/x) y=y+1 if (len(j) == 1): for k in range(0, len(data[j[0]])): x += data[j[0]][k] C4[y].append(i[2]/x) y=y+1 print("C4 with condidence",C4) def clear(): print("results(with 85% or greater) => ") for i in C4: if(i[3]>= minconf): RESULT.append([i[0],i[1]]) print("\t",i[0]," => ",i[1]) if __name__ == "__main__": data = {} support = {} c2 = [] L2 = {} C3 = [] L3 = {} C4 = [] RESULT = [] minsupport = 63 * 8 / 100 minconf = 85 / 100 print("MINSUPPORT ==> ", minsupport) print("MINCONFIDENCE ==> ", minconf) file_location = "1.xlsx" workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) attribute = sheet.ncols di = sheet.nrows for i in range(0, attribute): data[sheet.cell_value(0, i)] = [] for j in range(1,di): data[sheet.cell_value(0, i)].append(sheet.cell_value(j, i)) print("DATASET = > ", data) Apriori()
# Copyright (c) 2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from glareclient import exc from glareclient.osc.v1 import blobs as osc_blob from glareclient.tests.unit.osc.v1 import fakes from glareclient.v1 import artifacts as api_art import testtools class TestUpload(testtools.TestCase): def setUp(self): self.mock_app = mock.Mock() self.mock_args = mock.Mock() self.mock_manager = mock.Mock() self.mock_manager.artifacts.get.return_value = {'image': {}} super(TestUpload, self).setUp() @mock.patch('glareclient.osc.v1.blobs.progressbar') @mock.patch('glareclient.osc.v1.blobs.sys') @mock.patch('glareclient.osc.v1.blobs.open', create=True) @mock.patch('glareclient.common.utils.get_artifact_id') def test_upload_file_progress(self, mock_get_id, mock_open, mock_sys, mock_progressbar): mock_parsed_args = mock.Mock(name='test-id', id=True, blob_property='image', file='/path/file', progress=True, content_type='application/test', type_name='test-type') mock_get_id.return_value = 'test-id' cli = osc_blob.UploadBlob(self.mock_app, self.mock_args) cli.app.client_manager.artifact = self.mock_manager cli.dict2columns = mock.Mock(return_value=42) self.assertEqual(42, cli.take_action(mock_parsed_args)) cli.dict2columns.assert_called_once_with({'blob_property': 'image'}) upload_args = ['test-id', 'image', mock_progressbar.VerboseFileWrapper.return_value] upload_kwargs = {'content_type': 'application/test', 'type_name': 'test-type'} self.mock_manager.artifacts.upload_blob.\ assert_called_once_with(*upload_args, **upload_kwargs) @mock.patch('glareclient.osc.v1.blobs.sys') @mock.patch('glareclient.osc.v1.blobs.open', create=True) @mock.patch('glareclient.common.utils.get_artifact_id') def test_upload_file_no_progress(self, mock_get_id, mock_open, mock_sys): mock_parsed_args = mock.Mock(name='test-id', id=True, blob_property='image', progress=False, file='/path/file', content_type='application/test', type_name='test-type') mock_get_id.return_value = 'test-id' cli = osc_blob.UploadBlob(self.mock_app, self.mock_args) cli.app.client_manager.artifact = self.mock_manager cli.dict2columns = mock.Mock(return_value=42) self.assertEqual(42, cli.take_action(mock_parsed_args)) cli.dict2columns.assert_called_once_with({'blob_property': 'image'}) upload_args = ['test-id', 'image', mock_open.return_value] upload_kwargs = {'content_type': 'application/test', 'type_name': 'test-type'} self.mock_manager.artifacts.upload_blob.\ assert_called_once_with(*upload_args, **upload_kwargs) @mock.patch('glareclient.osc.v1.blobs.sys') @mock.patch('glareclient.common.utils.get_artifact_id') def test_upload_file_stdin(self, mock_get_id, mock_sys): mock_sys.stdin.isatty.return_value = False mock_parsed_args = mock.Mock(name='test-id', id=True, blob_property='image', progress=False, file=None, content_type='application/test', type_name='test-type') mock_get_id.return_value = 'test-id' cli = osc_blob.UploadBlob(self.mock_app, self.mock_args) cli.app.client_manager.artifact = self.mock_manager cli.dict2columns = mock.Mock(return_value=42) self.assertEqual(42, cli.take_action(mock_parsed_args)) cli.dict2columns.assert_called_once_with({'blob_property': 'image'}) upload_args = ['test-id', 'image', mock_sys.stdin] upload_kwargs = {'content_type': 'application/test', 'type_name': 'test-type'} self.mock_manager.artifacts.upload_blob.\ assert_called_once_with(*upload_args, **upload_kwargs) @mock.patch('glareclient.osc.v1.blobs.sys') def test_upload_file_stdin_isatty(self, mock_sys): mock_sys.stdin.isatty.return_value = True mock_parsed_args = mock.Mock(id='test-id', blob_property='image', progress=False, file=None, content_type='application/test', type_name='test-type') cli = osc_blob.UploadBlob(self.mock_app, self.mock_args) cli.app.client_manager.artifact = self.mock_manager self.assertRaises(exc.CommandError, cli.take_action, mock_parsed_args) class TestBlobs(fakes.TestArtifacts): def setUp(self): super(TestBlobs, self).setUp() self.blob_mock = \ self.app.client_manager.artifact.blobs self.http = mock.MagicMock() class TestDownloadBlob(TestBlobs): def setUp(self): super(TestDownloadBlob, self).setUp() self.blob_mock.call.return_value = \ api_art.Controller(self.http, type_name='images') # Command to test self.cmd = osc_blob.DownloadBlob(self.app, None) self.COLUMNS = ('blob_property', 'id', 'name', 'size', 'status', 'version') def test_download_exception(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--blob-property', 'blob', '--file', None] verify = [('type_name', 'images')] parsed_args = self.check_parser(self.cmd, arglist, verify) with testtools.ExpectedException(SystemExit): self.cmd.take_action(parsed_args) def test_download_blob(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--blob-property', 'blob', '--file', '/path/to/file'] verify = [('type_name', 'images')] parsed_args = self.check_parser(self.cmd, arglist, verify) self.cmd.take_action(parsed_args) def test_download_without_blob_property(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--file', '/path/to/file'] verify = [('type_name', 'images')] parsed_args = self.check_parser(self.cmd, arglist, verify) self.cmd.take_action(parsed_args) def test_download_progress(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--file', '/path/to/file', '--progress'] verify = [('type_name', 'images')] parsed_args = self.check_parser(self.cmd, arglist, verify) self.cmd.take_action(parsed_args) class TestAddLocation(TestBlobs): def setUp(self): super(TestAddLocation, self).setUp() self.blob_mock.call.return_value = \ api_art.Controller(self.http, type_name='images') # Command to test self.cmd = osc_blob.AddLocation(self.app, None) self.COLUMNS = ('blob_property', 'content_type', 'external', 'md5', 'sha1', 'sha256', 'size', 'status', 'url') def test_add_location(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--id', '--url', 'fake_url', '--md5', "35d83e8eedfbdb87ff97d1f2761f8ebf", '--sha1', "942854360eeec1335537702399c5aed940401602", '--sha256', "d8a7834fc6652f316322d80196f6dcf2" "94417030e37c15412e4deb7a67a367dd"] verify = [('type_name', 'images'), ('url', 'fake_url')] parsed_args = self.check_parser(self.cmd, arglist, verify) columns, data = self.cmd.take_action(parsed_args) self.assertEqual(self.COLUMNS, columns) def test_add_dict_location(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--id', '--blob-property', 'nested_templates/blob', '--url', 'fake_url', '--md5', "35d83e8eedfbdb87ff97d1f2761f8ebf", '--sha1', "942854360eeec1335537702399c5aed940401602", '--sha256', "d8a7834fc6652f316322d80196f6dcf2" "94417030e37c15412e4deb7a67a367dd"] verify = [('type_name', 'images'), ('url', 'fake_url')] parsed_args = self.check_parser(self.cmd, arglist, verify) self.app.client_manager.artifact.artifacts.get = \ lambda *args, **kwargs: { 'nested_templates': {'blob': fakes.blob_fixture} } columns, data = self.cmd.take_action(parsed_args) self.app.client_manager.artifact.artifacts.get = fakes.mock_get self.assertEqual(self.COLUMNS, columns) class TestRemoveLocation(TestBlobs): def setUp(self): super(TestRemoveLocation, self).setUp() self.blob_mock.call.return_value = \ api_art.Controller(self.http, type_name='images') # Command to test self.cmd = osc_blob.RemoveLocation(self.app, None) def test_remove_location(self): arglist = ['images', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--id'] verify = [('type_name', 'images'), ('name', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba'), ('id', True)] parsed_args = self.check_parser(self.cmd, arglist, verify) self.assertIsNone(self.cmd.take_action(parsed_args)) def test_remove_dict_location(self): arglist = ['images', '--blob-property', 'nested_templates/blob', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba', '--id'] verify = [('type_name', 'images'), ('name', 'fc15c365-d4f9-4b8b-a090-d9e230f1f6ba'), ('id', True)] parsed_args = self.check_parser(self.cmd, arglist, verify) self.assertIsNone(self.cmd.take_action(parsed_args))
import tensorflow as tf import tensorflow_probability as tfp #from https://github.com/kundajelab/basepair/blob/cda0875571066343cdf90aed031f7c51714d991a/basepair/losses.py#L87 def multinomial_nll(true_counts, logits): """Compute the multinomial negative log-likelihood Args: true_counts: observed count values logits: predicted logit values """ counts_per_example = tf.reduce_sum(true_counts, axis=-1) dist = tfp.distributions.Multinomial(total_count=counts_per_example, logits=logits) return (-tf.reduce_sum(dist.log_prob(true_counts)) / tf.cast(tf.shape(true_counts)[0], dtype=tf.float32))
import time TIME = time.time() p = 2 max_p = 0 max_count = 0 while p <= 1000: count = 0 for a in range(1, int(p/3)): num = p*p/2-p*a den = p-a if num % den == 0: count += 1 if count > max_count: max_count = count max_p = p p += 2 TIME = time.time() - TIME # seconds print("Answer: max p =", max_p) print("Execution time:",str(TIME)[:6],"sec")
#!/bin/python import time commands = {'test':'This is a test', 'check':'This is a check'} while True: gmtime = time.gmtime() prompt = str(gmtime.tm_year) + str(gmtime.tm_mon) + str(gmtime.tm_mday) inp = input(prompt+'>') if inp == 'exit': exit(0) else: if inp.strip() in commands.keys(): print(commands[inp]) else: print('Command not found')
from .locator import Locator, LocatorBy, XPath, LocatorChain from .base import Element from .web_element import WebElement, ElementCollection
print("local changes")
#!/usr/bin/env/ python import subprocess import optparse import re def get_args(): parser = optparse.OptionParser() parser.add_option("-i", "--interface",dest="interface",help="interface to change its MAC address") parser.add_option("-m", "--mac",dest="new_MAC",help="New Mac address") (options,arguments) = parser.parse_args() if not options.interface: #code to handle errors parser.error("[-] Please specify an interface use --help for more info.") elif not options.new_MAC: #code to handle errors parser.error("[-] Please specify an mac use --help for more info.") return options def change_mac(interface,new_mac): print("[+] Changeing MAC address for "+ interface + " to "+ new_mac) subprocess.call(["ifconfig" , interface , "down"]) subprocess.call(["ifconfig" , interface , "hw","ether",new_mac]) subprocess.call(["ifconfig" , interface , "up"]) def get_current_mac(interface): ifconfig_result = subprocess.check_output(["ifconfig",interface]).decode('utf-8') mac_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w",ifconfig_result) if mac_search_result: return mac_search_result.group(0) else: print("[-] Sorry could not read MAC address.") #Gets args from commandline options = get_args() current_mac = get_current_mac(options.interface) print("[-] Current Mac: "+ str(current_mac)) change_mac(options.interface,options.new_MAC) current_mac = get_current_mac(options.interface) if current_mac == options.new_MAC: print("[+] MAC address was succesfuly changed to "+ options.new_MAC) else: print("[-] MAC address couldnt be changed") print("[-] According to standerds MAC should start with and even pair") # v2 no secureity implemented you can execute commands # subprocess.call("ifconfig " + interface +" down" ,shell=True) # subprocess.call("ifconfig "+ interface +" hw ether "+ new_MAC ,shell=True) # subprocess.call("ifconfig "+ interface +" up",shell=True) # v1 # subprocess.call("ifconfig wlan0 down",shell=True) # subprocess.call("ifconfig wlan0 hw ether 00:11:22:33:44:55:66",shell=True) # subprocess.call("ifconfig wlan0 up",shell=True)
# -*- coding: utf-8 -*- """ *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from qgis.PyQt.QtCore import QCoreApplication, QVariant from qgis.core import (QgsProcessing, QgsFeature, QgsFeatureSink, QgsField, QgsFields, QgsProcessingException, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource, QgsProcessingParameterFeatureSink) from qgis import processing from .model import Model class DistrictAssignmentProcessingAlgorithm(QgsProcessingAlgorithm): """ This algorithm is used with US census tract information to create non-gerrymandered congressional and legislative districts. The algorithm uses a relatively standard K Means Clustering algorithm, but the number of census tracts that can be in any given cluster is constrained by the total population of those census tracts to ensure that the population of each cluster is approximately equal. """ # Constants used to refer to parameters and outputs. They will be # used when calling the algorithm from another algorithm, or when # calling from the QGIS console. INPUT = 'INPUT' OUTPUT = 'OUTPUT' def tr(self, string): """ Returns a translatable string with the self.tr() function. """ return QCoreApplication.translate('Processing', string) def createInstance(self): return DistrictAssignmentProcessingAlgorithm() def name(self): """ Returns the algorithm name, used for identifying the algorithm. This string should be fixed for the algorithm, and must not be localised. The name should be unique within each provider. Names should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'district_assignment' def displayName(self): """ Returns the translated algorithm name, which should be used for any user-visible display of the algorithm name. """ return self.tr('District Assignment') def group(self): """ Returns the name of the group this algorithm belongs to. This string should be localised. """ return self.tr('scripts') def groupId(self): """ Returns the unique ID of the group this algorithm belongs to. This string should be fixed for the algorithm, and must not be localised. The group id should be unique within each provider. Group id should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'scripts' def shortHelpString(self): """ Returns a localised short helper string for the algorithm. This string should provide a basic description about what the algorithm does and the parameters and outputs associated with it.. """ return self.tr("Assigns Census Tracts to Districts") def initAlgorithm(self, config=None): """ Here we define the inputs and output of the algorithm, along with some other properties. """ # We add the input vector features source. It can have any kind of # geometry. self.addParameter( QgsProcessingParameterFeatureSource( self.INPUT, self.tr('Input layer'), [QgsProcessing.TypeVectorAnyGeometry] ) ) # We add a feature sink in which to store our processed features (this # usually takes the form of a newly created vector layer when the # algorithm is run in QGIS). self.addParameter( QgsProcessingParameterFeatureSink( self.OUTPUT, self.tr('Output layer') ) ) def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ # Retrieve the feature source and sink. The 'dest_id' variable is used # to uniquely identify the feature sink, and must be included in the # dictionary returned by the processAlgorithm function. source = self.parameterAsSource( parameters, self.INPUT, context ) # If source was not found, throw an exception to indicate that the algorithm # encountered a fatal error. The exception text can be any string, but in this # case we use the pre-built invalidSourceError method to return a standard # helper text for when a source cannot be evaluated if source is None: raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT)) output_fields = QgsFields() output_fields.append(QgsField('id', QVariant.String)) output_fields.append(QgsField('population', QVariant.Int)) output_fields.append(QgsField('district', QVariant.Int)) (sink, dest_id) = self.parameterAsSink( parameters, self.OUTPUT, context, output_fields, source.wkbType(), source.sourceCrs() ) # Send some information to the user feedback.pushInfo('CRS is {}'.format(source.sourceCrs().authid())) # If sink was not created, throw an exception to indicate that the algorithm # encountered a fatal error. The exception text can be any string, but in this # case we use the pre-built invalidSinkError method to return a standard # helper text for when a sink cannot be evaluated if sink is None: raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT)) # Compute the number of steps to display within the progress bar and # get features from source # total = 100.0 / source.featureCount() if source.featureCount() else 0 def get_census_tracts(): return [ { 'id': feature['GEOID_Data'], 'center': get_location(feature), 'population': feature['B01001e1'] } for feature in source.getFeatures() ] def get_location(feature): return { 'latitude': float(feature['INTPTLAT']), 'longitude': float(feature['INTPTLON']) } ''' def get_target_district_population(census_tracts, number_of_districts): total_population = sum([tract['population'] for tract in census_tracts.values()]) return total_population / number_of_districts def get_all_tract_centers(census_tracts): return [tract['center'] for tract in census_tracts.values()] def initialize_districts(tract_centers, number_of_districts, target_district_population): For each district: (1) Randomly assign one of the census tracte locations to be the initial district center (2) Assign the target district population to the district (3) Create an empty list for census tracts assigned to district centers = random.sample(tract_centers, number_of_districts) return { district: { 'center': centers[district - 1], 'population': target_district_population, 'assigned_census_tracts': [] } for district in range(1, number_of_districts + 1) } def initialize_tract_assignments(census_tracts): Assign all census tracts to non-existent district 0 return { id: { 'old_assignment': 0, 'new_assignment': 0 } for id in census_tracts.keys() } def locate_state_center(census_tracts): locations = [tract['center'] for tract in census_tracts.values()] state_center_latitude = sum([location['latitude'] for location in locations]) / len(locations) state_center_longitude = sum([location['longitude'] for location in locations]) / len(locations) return { 'latitude': state_center_latitude, 'longitude': state_center_longitude } def locate_center(assigned_census_tracts): locations = [list(tract.values())[0]['center'] for tract in assigned_census_tracts] if len(locations) == 0: return None new_center_latitude = sum([location['latitude'] for location in locations]) / len(locations) new_center_longitude = sum([location['longitude'] for location in locations]) / len(locations) return { 'latitude': new_center_latitude, 'longitude': new_center_longitude } def reset_district_info(districts, target_district_population): for id in districts.keys(): new_center = locate_center(districts[id]['assigned_census_tracts']) if new_center: districts[id]['center'] = new_center districts[id]['population'] = target_district_population districts[id]['assigned_census_tracts'] = [] return districts def get_squared_distance(location_1, location_2): squared_distance = (location_1['latitude'] - location_2['latitude'])**2 + (location_1['longitude'] - location_2['longitude'])**2 return squared_distance def get_closest_district(districts, location, reassignment_id = None): min_distance = math.inf for id in districts.keys(): district_location = districts[id]['center'] distance = get_squared_distance(district_location, location) if distance < min_distance and id != reassignment_id: closest_district = id min_distance = distance return closest_district def get_assignment_by_tract(census_tracts, districts, census_tract_district_assignment): for id, tract in census_tracts.items(): closest_district = get_closest_district(districts, tract['center']) census_tract_district_assignment[id]['new_assignment'] = closest_district districts[closest_district]['population'] -= tract['population'] districts[closest_district]['assigned_census_tracts'].append({id: tract}) return districts, census_tract_district_assignment def adjust_overpopulation(census_tracts, districts, census_tract_district_assignment, district_id, tracts_available_for_assignment): furthest_census_tracts = find_furthest_census_tracts(districts, district_id) while districts[district_id]['population'] < -2500 and len(furthest_census_tracts) > 0: #feedback.pushInfo(f"{district_id}: {districts[district_id]['population']}") new_assigned_tract = furthest_census_tracts.pop(0) new_assigned_tract_id = new_assigned_tract['tract_id'] if new_assigned_tract_id in tracts_available_for_assignment: new_assigned_tract_center = census_tracts[new_assigned_tract_id]['center'] new_district_id = get_closest_district(districts, new_assigned_tract_center, reassignment_id = district_id) districts, census_tract_district_assignment = reassign_tract(census_tracts, districts, census_tract_district_assignment, district_id, new_district_id, new_assigned_tract_id) tracts_available_for_assignment.remove(new_assigned_tract_id) return districts, census_tract_district_assignment, tracts_available_for_assignment def adjust_underpopulation(census_tracts, districts, census_tract_district_assignment, district_id, tracts_available_for_assignment): nearest_census_tracts = find_nearest_census_tracts(census_tracts, districts, census_tract_district_assignment, district_id) while districts[district_id]['population'] > 2500 and len(nearest_census_tracts) > 0: #feedback.pushInfo(f"Underpop: {district_id}: {districts[district_id]['population']}") new_assigned_tract = nearest_census_tracts.pop(0) new_assigned_tract_id = new_assigned_tract['tract_id'] if new_assigned_tract_id in tracts_available_for_assignment: old_district = census_tract_district_assignment[new_assigned_tract_id]['new_assignment'] districts, census_tract_district_assignment = reassign_tract(census_tracts, districts, census_tract_district_assignment, old_district, district_id, new_assigned_tract_id) tracts_available_for_assignment.remove(new_assigned_tract_id) return districts, census_tract_district_assignment, tracts_available_for_assignment def find_furthest_census_tracts(districts, district_id): furthest_census_tracts = [] for tract in districts[district_id]['assigned_census_tracts']: tract_id = list(tract.keys())[0] tract_center = tract[tract_id]['center'] district_center = districts[district_id]['center'] furthest_census_tracts.append({ 'tract_id': tract_id, 'distance': get_squared_distance(tract_center, district_center) }) furthest_census_tracts.sort(key = lambda x: x['distance'], reverse=True) return furthest_census_tracts def find_nearest_census_tracts(census_tracts, districts, census_tract_district_assignment, district_id): nearest_census_tracts = [] for tract_id, tract in census_tract_district_assignment.items(): if tract['new_assignment'] != district_id: nearest_census_tracts.append( { 'tract_id': tract_id, 'distance': get_squared_distance(census_tracts[tract_id]['center'], districts[district_id]['center']) } ) nearest_census_tracts.sort(key = lambda x: x['distance']) return nearest_census_tracts def reassign_tract(census_tracts, districts, census_tract_district_assignment, old_district_id, new_district_id, tract_id): tract = {tract_id: census_tracts[tract_id]} tract_population = tract[tract_id]['population'] census_tract_district_assignment[tract_id]['new_assignment'] = new_district_id districts[new_district_id]['assigned_census_tracts'].append(tract) districts[old_district_id]['assigned_census_tracts'].remove(tract) districts[new_district_id]['population'] -= tract_population districts[old_district_id]['population'] += tract_population return districts, census_tract_district_assignment def get_district_order(districts, state_center): district_order = [] for id, district in districts.items(): distance = get_squared_distance(district['center'], state_center) district_order.append({ 'id': id, 'distance': distance }) district_order.sort(key = lambda x: x['distance'], reverse=True) return district_order def get_tracts_available_for_assignment(census_tracts, census_tract_district_assignment, furthest_district_id): return [id for id in census_tracts.keys() if census_tract_district_assignment[id]['new_assignment'] != furthest_district_id] def population_adjustment(census_tracts, districts, census_tract_district_assignment, state_center): district_order = get_district_order(districts, state_center) tracts_available_for_assignment = get_tracts_available_for_assignment(census_tracts, census_tract_district_assignment, district_order[0]['id']) for district in district_order: id = district['id'] if districts[id]['population'] < 0: districts, census_tract_district_assignment, tracts_available_for_assignment = adjust_overpopulation(census_tracts, districts, census_tract_district_assignment, id, tracts_available_for_assignment) else: districts, census_tract_district_assignment, tracts_available_for_assignment = adjust_underpopulation(census_tracts, districts, census_tract_district_assignment, id, tracts_available_for_assignment) for tract_id, assignments in census_tract_district_assignment.items(): if tract_id in tracts_available_for_assignment and assignments['new_assignment'] == id: tracts_available_for_assignment.remove(tract_id) for district in district_order: feedback.pushInfo(f"{district['id']}: {districts[district['id']]['population']}") return districts, census_tract_district_assignment def get_differences(census_tract_district_assignment): differences = 0 for tract in census_tract_district_assignment.values(): if tract['old_assignment'] != tract['new_assignment']: differences += 1 tract['old_assignment'] = tract['new_assignment'] return differences, census_tract_district_assignment def assign_census_tracts(census_tracts, districts, census_tract_district_assignment): districts, census_tract_district_assignment = get_assignment_by_tract(census_tracts, districts, census_tract_district_assignment) differences, census_tract_district_assignment = get_differences(census_tract_district_assignment) return districts, census_tract_district_assignment, differences def k_means(census_tracts, tract_centers, number_of_districts, target_district_population): districts = initialize_districts(tract_centers, number_of_districts, target_district_population) census_tract_district_assignment = initialize_tract_assignments(census_tracts) #county_order = initialize_county_order(census_tracts) iteration_number = 1 differences = 1 while differences > 0 and iteration_number < 100: if iteration_number > 1: districts = reset_district_info(districts, target_district_population) feedback.pushInfo(f'Iteration number {iteration_number}: {differences} differences') districts, census_tract_district_assignment, differences = assign_census_tracts(census_tracts, districts, census_tract_district_assignment) iteration_number += 1 return districts, census_tract_district_assignment number_of_districts = 8 # NEED TO FIGURE OUT HOW TO IMPORT # OF DISTRICTS TO AUTOMATE DIFFERENT STATES # Run the K-Means Analysis census_tracts = get_census_tracts() tract_centers = get_all_tract_centers(census_tracts) state_center = locate_state_center(census_tracts) target_district_population = get_target_district_population(census_tracts, number_of_districts) districts, census_tract_district_assignment = k_means(census_tracts, tract_centers, number_of_districts, target_district_population) districts, census_tract_district_assignment = population_adjustment(census_tracts, districts, census_tract_district_assignment, state_center) ''' feedback.pushInfo('pre-census_tracts') #features = [feature for feature in source.getFeatures] census_tracts = get_census_tracts() feedback.pushInfo('features done') number_of_districts = 8 # NEED TO FIGURE OUT HOW TO IMPORT # OF DISTRICTS TO AUTOMATE DIFFERENT STATES feedback.pushInfo('pre-model') model = Model(features, number_of_districts) census_tract_district_assignment = {tract.id: tract.new_assignment for tract in model.census_tracts} feedback.pushInfo('post-model') # Create the Output Sink for feature in source.getFeatures(): f = QgsFeature() f.setFields(output_fields) f.setGeometry(feature.geometry()) f['id'] = feature['GEOID_Data'] f['population'] = feature['B01001e1'] f['district'] = census_tract_district_assignment[f['id']] sink.addFeature(f, QgsFeatureSink.FastInsert) ''' for current, feature in enumerate(features): # Stop the algorithm if cancel button has been clicked if feedback.isCanceled(): break # Add a feature in the sink sink.addFeature(feature, QgsFeatureSink.FastInsert) # Update the progress bar feedback.setProgress(int(current * total)) # To run another Processing algorithm as part of this algorithm, you can use # processing.run(...). Make sure you pass the current context and feedback # to processing.run to ensure that all temporary layer outputs are available # to the executed algorithm, and that the executed algorithm can send feedback # reports to the user (and correctly handle cancellation and progress reports!) if False: buffered_layer = processing.run("native:buffer", { 'INPUT': dest_id, 'DISTANCE': 1.5, 'SEGMENTS': 5, 'END_CAP_STYLE': 0, 'JOIN_STYLE': 0, 'MITER_LIMIT': 2, 'DISSOLVE': False, 'OUTPUT': 'memory:' }, context=context, feedback=feedback)['OUTPUT'] # Return the results of the algorithm. In this case our only result is # the feature sink which contains the processed features, but some # algorithms may return multiple feature sinks, calculated numeric # statistics, etc. These should all be included in the returned # dictionary, with keys matching the feature corresponding parameter # or output names. ''' return {self.OUTPUT: dest_id}
# import os import cloudinary.uploader import cloudinary import datetime import math # import random import aiofiles from settings import ( templates, BASE_HOST, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET # , UPLOAD_FOLDER ) from starlette.responses import RedirectResponse from starlette.authentication import requires from tortoise.query_utils import Q from tortoise.transactions import in_transaction from utils import pagination from ads.forms import ( AdForm, AdEditForm, ReviewForm, ReviewEditForm, RentForm ) from models import ( Ad, User, Image, Review, Rent, Notification, ADMIN ) async def ads_all(request): """ All ads """ page_query = pagination.get_page_number(url=request.url) count = await Ad.all().count() paginator = pagination.Pagination(page_query, count) results = ( await Ad.all() .prefetch_related("user", "ad_image", "ad") .limit(paginator.page_size) .offset(paginator.offset()) .order_by('-id') ) page_controls = pagination.get_page_controls( url=request.url, current_page=paginator.current_page(), total_pages=paginator.total_pages() ) return templates.TemplateResponse( "ads/ads.html", { "request": request, "results": results, "page_controls": page_controls }, ) async def ad(request): """ Single ad """ id = request.path_params["id"] path = request.url.path results = await Ad.get(id=id).prefetch_related("user", "ad_rent") # update ad views per session session_key = 'viewed_ad_{}'.format(results.id) if not request.session.get(session_key, False): results.view += 1 await results.save() request.session[session_key] = True image_results = await Image.all().filter(ad_image_id=id) review_results = (await Review.all() .prefetch_related("review_user", "ad") .filter(ad__id=id) .order_by("-id") ) # if no reviews try: review_avg = sum(r.review_grade for r in review_results) / \ len(review_results) except ZeroDivisionError: review_avg = None # proccesing form for booking ad data = await request.form() form = RentForm(data) if request.method == "POST" and form.validate(): session_user = request.user.username result = await User.get(username=session_user) start = form.start_date.data end = form.end_date.data try: between = await Rent.filter( start_date__lte=end, end_date__gte=start, ad_rent_id=id ) now = datetime.datetime.now().date() diff = (now - start).total_seconds() if diff > 0: rent_error = "Both dates can't be in the past." days = (end - start).days if days < 1: rent_error = "The minimum rental period is one day." if any(between): rent_error = "Already rented in that time." return templates.TemplateResponse( "ads/ad.html", { "request": request, "item": results, "path": path, "images": image_results, "review_results": review_results, "review_count": len(review_results), "review_avg": review_avg, "form": form, "rent_error": rent_error }, ) except: query = Rent( start_date=form.start_date.data, end_date=form.end_date.data, client_id=result.id, ad_rent_id=results.id, ) await query.save() # notification to ad owner notification_query = Notification( message=f"{results.title} booked by {session_user}", created=datetime.datetime.now(), is_read=0, sender_id=result.id, recipient_id=results.user.id ) await notification_query.save() return RedirectResponse(BASE_HOST + path, status_code=302) return templates.TemplateResponse( "ads/ad.html", { "request": request, "item": results, "path": path, "images": image_results, "review_results": review_results, "review_count": len(review_results), "review_avg": review_avg, "form": form }, ) @requires("authenticated") async def ad_create(request): """ Ad create form """ session_user = request.user.username results = await User.get(username=session_user) data = await request.form() form = AdForm(data) title = form.title.data if request.method == "POST" and form.validate(): query = Ad( title=title, slug="-".join(title.lower().split()), content=form.content.data, created=datetime.datetime.now(), view=0, price=form.price.data, city=form.city.data, address=form.address.data, user_id=results.id ) await query.save() return RedirectResponse(url="/ads/images", status_code=302) return templates.TemplateResponse( "ads/ad_create.html", {"request": request, "form": form} ) @requires("authenticated") async def ad_images(request): return templates.TemplateResponse( "ads/images.html", { "request": request, "BASE": BASE_HOST } ) async def write_file(path, body): async with aiofiles.open(path, 'wb') as f: await f.write(body) f.close() @requires("authenticated") async def upload(request): """ upload images to Cloudinary because Heroku filesystem is not suitable \ for files upload. More info on link https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted """ result = await Ad.all() # last inserted ad id aid = result[-1].id data = await request.form() iter_images = data.multi_items() num_of_images = len([i for i in iter_images if i[1] != '']) # list of images paths images = [data["images" + str(i)] for i in range(num_of_images)] # save images path and last inserted ad id to db for item in images: async with in_transaction() as conn: await conn.execute_query( f"INSERT INTO image (path, ad_image_id) \ VALUES ('{item}', {aid});" ) return RedirectResponse(url="/ads/", status_code=302) """ - uncomment for Dropzone upload to filesystem @requires("authenticated") async def upload(request): result = await Ad.all() # last inserted ad id aid = result[-1].id data = await request.form() # convert multidict to list of items for multifile upload iter_images = data.multi_items() # read item and convert to bytes byte_images = [await item[1].read() for item in iter_images] list_of_paths = [] # write bytes to file in filesystem # name of file with random for upload_file in byte_images: file_path = f"{UPLOAD_FOLDER}/{random.randint(100,100000)}.jpeg" list_of_paths.append(file_path) await write_file(file_path, upload_file) # store file paths to db and link to single ad for item in list_of_paths: async with in_transaction() as conn: await conn.execute_query( f"INSERT INTO image (path, ad_image_id) \ VALUES (\"{item}\", {aid});" ) return RedirectResponse(url="/ads/", status_code=302) """ @requires("authenticated") async def ad_edit(request): """ Ad edit form """ id = request.path_params["id"] session_user = request.user.username results = await User.get(username=session_user) ad = await Ad.get(id=id) images = await Image.all().filter(ad_image_id=ad.id) data = await request.form() form = AdEditForm(data) new_form_value, form.content.data = form.content.data, ad.content title = form.title.data if request.method == "POST" and form.validate(): query = Ad( id=ad.id, title=title, slug="-".join(title.lower().split()), content=new_form_value, created=datetime.datetime.now(), view=ad.view, price=form.price.data, city=form.city.data, address=form.address.data, user_id=results.id, ) await query.save() return RedirectResponse(url=f"/ads/image-edit/{ad.id}", status_code=302 ) return templates.TemplateResponse( "ads/ad_edit.html", { "request": request, "form": form, "ad": ad, "images": images, } ) @requires("authenticated") async def image_edit(request): aid = request.path_params["id"] # count remaining images img_count = await Image.all().filter(ad_image_id=aid).count() return templates.TemplateResponse( "ads/image_edit.html", { "request": request, "BASE": BASE_HOST, "aid": aid, "img_count": img_count } ) @requires("authenticated") async def edit_upload(request): # edited ad id aid = int((request.url.path).split('/')[-1]) img_count = await Image.all().filter(ad_image_id=aid).count() data = await request.form() # list of remaining images paths images = [data["images" + str(i)] for i in range(3-img_count)] # save images path and last inserted ad id to db for item in images: async with in_transaction() as conn: await conn.execute_query( f"INSERT INTO image (path, ad_image_id) \ VALUES ('{item}', {aid});" ) return RedirectResponse( BASE_HOST + f"/ads/edit/{aid}", status_code=302 ) """ - uncomment for Dropzone upload to filesystem @requires("authenticated") async def edit_upload(request): if request.method == "POST": # edited ad id aid = int((request.url.path).split('/')[-1]) data = await request.form() # convert multidict to list of items for multifile upload iter_images = data.multi_items() # read item and convert to bytes byte_images = [await item[1].read() for item in iter_images] list_of_paths = [] # write bytes to file in filesystem # name of file with random for upload_file in byte_images: file_path = f"{UPLOAD_FOLDER}/{random.randint(100,100000)}.jpeg" list_of_paths.append(file_path) await write_file(file_path, upload_file) # store file paths to db and link to single ad for item in list_of_paths: print(item) async with in_transaction() as conn: await conn.execute_query( f"INSERT INTO image (path, ad_image_id) \ VALUES ('{item}', {aid});" ) return RedirectResponse(BASE_HOST + f"/ads/edit/{aid}#loaded", status_code=302 ) """ @requires("authenticated") async def image_delete(request): """ Delete image on edit """ id = request.path_params["id"] form = await request.form() aid = form["aid"] if request.method == "POST": # delete related image from filesystem # uncomment for Dropzone upload to filesystem # img = await Image.get(id=id) # os.remove(img.path) img = await Image.get(id=id) public_id = (img.path).split('/')[-1].split('.')[0] cloudinary.config( cloud_name="rkl", api_key=CLOUDINARY_API_KEY, api_secret=CLOUDINARY_API_SECRET ) cloudinary.uploader.destroy(public_id) await Image.get(id=id).delete() return RedirectResponse(url=f"/ads/edit/{aid}", status_code=302) @requires("authenticated") async def ad_delete(request): """ Delete ad """ id = request.path_params["id"] if request.method == "POST": # delete images from filesystem images = await Image.all().filter(ad_image_id=id) # for img in images: # os.remove(img.path) cloudinary.config( cloud_name="rkl", api_key=CLOUDINARY_API_KEY, api_secret=CLOUDINARY_API_SECRET ) public_ids = [ (img.path).split('/')[-1].split('.')[0] for img in images ] cloudinary.api.delete_resources(public_ids) await Ad.get(id=id).delete() if request.user.username == ADMIN: return RedirectResponse(url="/accounts/dashboard", status_code=302) return RedirectResponse(url="/accounts/profile", status_code=302) @requires("authenticated") async def review_create(request): """ Review form """ id = int(request.query_params['next'].split('/')[2]) next = request.query_params['next'] results = await Ad.get(id=id).prefetch_related("user") session_user = request.user.username data = await request.form() form = ReviewForm(data) result = await User.get(username=session_user) if request.method == "POST" and form.validate(): query = Review( content=form.content.data, created=datetime.datetime.now(), review_grade=form.grade.data, ad_id=results.id, review_user_id=result.id, ) await query.save() return RedirectResponse(BASE_HOST + next, status_code=302) return templates.TemplateResponse( "ads/review_create.html", { "request": request, "form": form, "next": next } ) @requires("authenticated") async def review_edit(request): """ Review edit form """ id = request.path_params["id"] review = await Review.get(id=id) data = await request.form() form = ReviewEditForm(data) new_form_value, form.content.data = form.content.data, review.content if request.method == "POST" and form.validate(): query = Review( id=review.id, content=new_form_value, created=datetime.datetime.now(), review_grade=form.grade.data, ad_id=review.ad_id, review_user_id=review.review_user_id, ) await query.save() if request.user.username == ADMIN: return RedirectResponse(url="/accounts/dashboard", status_code=302) return RedirectResponse(url="/accounts/profile", status_code=302) return templates.TemplateResponse( "ads/review_edit.html", { "request": request, "form": form, "review": review } ) @requires("authenticated") async def review_delete(request): """ Delete review """ id = request.path_params["id"] if request.method == "POST": await Review.get(id=id).delete() if request.user.username == ADMIN: return RedirectResponse(url="/accounts/dashboard", status_code=302) return RedirectResponse(url="/accounts/profile", status_code=302) async def search(request): """ Search questions """ try: page_query = pagination.get_page_number(url=request.url) q = request.query_params['q'] count = ( await Ad.all() .prefetch_related("user", "ad_image", "ad") .filter(Q(title__icontains=q) | Q(content__icontains=q) | Q(city__icontains=q) | Q(address__icontains=q) | Q(price__icontains=q) | Q(user__username__icontains=q)) .distinct() .count() ) paginator = pagination.Pagination(page_query, count) results = ( await Ad.all() .prefetch_related("user", "ad_image", "ad") .filter(Q(title__icontains=q) | Q(content__icontains=q) | Q(city__icontains=q) | Q(address__icontains=q) | Q(price__icontains=q) | Q(user__username__icontains=q)) .distinct() .limit(paginator.page_size) .offset(paginator.offset()) ) page_controls = pagination.get_page_controls( url=request.url, current_page=paginator.current_page(), total_pages=paginator.total_pages() ) except KeyError: page_query = pagination.get_page_number(url=request.url) count = ( await Ad.all() .prefetch_related("user", "ad_image", "ad_rent", "ad") .count() ) paginator = pagination.Pagination(page_query, count) results = ( await Ad.all() .prefetch_related("user", "ad_image", "ad_rent", "ad") .limit(paginator.page_size) .offset(paginator.offset()) ) page_controls = pagination.get_page_controls( url=request.url, current_page=paginator.current_page(), total_pages=paginator.total_pages() ) return templates.TemplateResponse( "ads/search.html", { "request": request, "results": results, "page_controls": page_controls, "count": count } ) async def filter_search(request): """ Filter search questions by city and available ads (not rented ads in required time) """ # ads in required time try: city = request.query_params["city"] start = request.query_params["start"] end = request.query_params["end"] if start > end: return RedirectResponse(url="/") between = await Rent.filter( start_date__lte=datetime.datetime.strptime(end, "%Y-%m-%d").date(), end_date__gte=datetime.datetime.strptime(start, "%Y-%m-%d").date(), ).values_list() rented = list(set([i[-1] for i in between])) print(rented) if rented: page_query = pagination.get_page_number(url=request.url) count = ( await Ad.all() .prefetch_related("user", "ad_image", "ad", "ad_rent") .filter(city=city.title(), id__not_in=rented) .count() ) paginator = pagination.Pagination(page_query, count) results = ( await Ad.all() .prefetch_related("user", "ad_image", "ad", "ad_rent") .filter(city=city.title(), id__not_in=rented) .limit(paginator.page_size) .offset(paginator.offset()) ) page_controls = pagination.get_page_controls( url=request.url, current_page=paginator.current_page(), total_pages=paginator.total_pages() ) # if ad not in rented list (never rented) # return ads by city filter else: page_query = pagination.get_page_number(url=request.url) count = ( await Ad.all() .prefetch_related("user", "ad_image", "ad", "ad_rent") .filter(city=city.title()) .count() ) paginator = pagination.Pagination(page_query, count) results = ( await Ad.all() .prefetch_related("user", "ad_image", "ad", "ad_rent") .filter(city=city.title()) .limit(paginator.page_size) .offset(paginator.offset()) ) page_controls = pagination.get_page_controls( url=request.url, current_page=paginator.current_page(), total_pages=paginator.total_pages() ) # if form is empty return all ads except KeyError: page_query = pagination.get_page_number(url=request.url) count = ( await Ad.all() .prefetch_related("user", "ad_image", "ad", "ad_rent") .count() ) paginator = pagination.Pagination(page_query, count) results = ( await Ad.all() .prefetch_related("user", "ad_image", "ad", "ad_rent") .limit(paginator.page_size) .offset(paginator.offset()) ) page_controls = pagination.get_page_controls( url=request.url, current_page=paginator.current_page(), total_pages=paginator.total_pages() ) return templates.TemplateResponse( "ads/filter_search.html", { "request": request, "results": results, "page_controls": page_controls, "count": count } ) async def maps(request): """ Map view """ city = request.path_params["city"] results = await Ad.all() return templates.TemplateResponse( "ads/map.html", { "request": request, "results": results, "city": city } )
# Generated by Django 3.2.6 on 2021-09-15 03:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quizes', '0003_auto_20210914_1343'), ] operations = [ migrations.AlterField( model_name='quiz', name='difficulty', field=models.CharField(choices=[('fácil', 'fácil'), ('medio', 'medio'), ('alta', 'alta')], max_length=6), ), ]
import sqlite3 import pandas as pd import xlsxwriter conn = sqlite3.connect("books.db") c = conn.cursor() def get_top_rated(): '''Find top 10 books with the highest rating''' c.execute("SELECT * FROM books WHERE rating = 5 LIMIT 10") return c.fetchall() # def get_average_price(): # '''Find average price of all books in the DB''' # prices = c.execute("SELECT price FROM books").fetchall() # total = 0 # for x in prices: # total += x[0] # average = round(total/len(prices), 2) # return f"{average} GBP" def get_best_price(): '''Find top 10 books with the lowest prices''' c.execute("SELECT * FROM books ORDER BY price LIMIT 10") return c.fetchall() def get_recommended(): '''Find 10 most affordable top-rated books''' c.execute("SELECT * FROM books WHERE rating = 5 ORDER BY price LIMIT 10") return c.fetchall() def create_df(data_fn): '''Create a dataframe''' return pd.DataFrame({ "Title": [x[0] for x in data_fn], "Price": [x[1] for x in data_fn], "Raiting": [x[2] for x in data_fn] }) def write_data_to_excel(): '''Writes dataframes into an Excel file''' recommended_df = create_df(get_recommended()) top_rated_df = create_df(get_top_rated()) best_price_df = create_df(get_best_price()) with pd.ExcelWriter("books_stats.xlsx", engine="xlsxwriter") as writer: recommended_df.to_excel(writer, sheet_name="Top 10", index=False, startrow=1) top_rated_df.to_excel(writer, sheet_name="Top 10", index=False, startrow=1, startcol=4) best_price_df.to_excel(writer, sheet_name="Top 10", index=False, startrow=1, startcol=8) # Adding headings above the dataframes workbook = xlsxwriter.Workbook(writer) merge_format = workbook.add_format() worksheet = writer.sheets["Top 10"] worksheet.merge_range("A1:C1", "RECOMMENDED", merge_format) worksheet.merge_range("E1:G1", "TOP RATED", merge_format) worksheet.merge_range("I1:K1", "BEST PRICE", merge_format) write_data_to_excel()
def Main(): cart =[] cart.append(dict(item="Water", price=2, qty=2)) cart.append(dict(item="Papaya", price=3, qty=1)) cart.append(dict(item="Stake", price=36, qty=4)) t = Template("$qty x $item = $price) total = 0 print("Cart:") for data in cart: print(t.substitute(data)) total+=data["price"] print("Total:"+str(total)) if __name__=='__main__': Main()
# -*- coding: utf-8 -*- """ Middleware custom to developer.ubuntu.com """ from django.contrib.sessions.middleware import SessionMiddleware from django.conf import settings class CacheFriendlySessionMiddleware(SessionMiddleware): """ To provide effective caching of public pages, remove the sessionid and csrf token from the Cookie to that Vary: Cookie doesn't cache pages per-user """ def process_response(self, request, response): response = super(CacheFriendlySessionMiddleware, self).process_response(request, response) #Don't do anything if it's a redirect, not found, or error if response.status_code != 200: return response #You have access to request.user in this method if not hasattr(request, 'user') or not request.user.is_authenticated(): response.delete_cookie(settings.SESSION_COOKIE_NAME) response.delete_cookie(settings.CSRF_COOKIE_NAME) return response
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 09:58:24 2019 @author: spenc """ #Spencer Palladino #Homework 7 import pandas as pd import numpy as np import matplotlib.pyplot as plt import numpy.random as npr import statsmodels.api as sm import statsmodels.formula.api as smf from sklearn.linear_model import LinearRegression from sklearn.linear_model import Lasso collegedata = pd.read_csv('C:/Users/spenc/Downloads/data/MERGED2015_16_PP.csv', usecols = ['C200_4','CONTROL','AVGFACSAL','INC_PCT_LO','INC_PCT_M1', 'INC_PCT_M2','INC_PCT_H1','INC_PCT_H2','SATVRMID','SATMTMID', 'UGDS_WOMEN','UGDS_WHITE','ADM_RATE','PFTFAC','TUITIONFEE_IN']) collegedata=collegedata[collegedata!= 'PrivacySuppressed'] collegedata.dropna(inplace=True) collegedata.astype(float) #get data to be less messy. Python handles NA values poor #Question 1 #a y = collegedata.C200_4 x1 = collegedata.CONTROL results = sm.OLS(y,x1).fit() results.summary() x2 = collegedata.AVGFACSAL results = sm.OLS(y,x2).fit() results.summary() x3 = collegedata.INC_PCT_LO.astype(float) #for some reason these still were not floats results = sm.OLS(y,x3).fit() results.summary() x4 = collegedata.INC_PCT_M1.astype(float) results = sm.OLS(y,x4).fit() results.summary() x5 = collegedata.INC_PCT_M2.astype(float) results = sm.OLS(y,x5).fit() results.summary() x6 = collegedata.INC_PCT_H1.astype(float) results = sm.OLS(y,x6).fit() results.summary() x7 = collegedata.INC_PCT_H2.astype(float) results = sm.OLS(y,x7).fit() results.summary() x8 = collegedata.SATVRMID results = sm.OLS(y,x8).fit() results.summary() x9 = collegedata.SATMTMID results = sm.OLS(y,x9).fit() results.summary() x10 = collegedata.UGDS_WOMEN results = sm.OLS(y,x10).fit() results.summary() x11 = collegedata.UGDS_WHITE results = sm.OLS(y,x11).fit() results.summary() x12 = collegedata.ADM_RATE results = sm.OLS(y,x12).fit() results.summary() x13 = collegedata.PFTFAC results = sm.OLS(y,x13).fit() results.summary() x14 = collegedata.TUITIONFEE_IN results = sm.OLS(y,x14).fit() results.summary() #b linmod = smf.ols(formula = 'y~x1+x2+x3+x4+x5+x6+x8+x9+x10+x11+x12+x13+x14' ,data=collegedata, missing='drop').fit() linmod.summary() #c def forward_selection(data, target, significance_level=0.05): initial_features = data.columns.tolist() best_features = [] while (len(list(initial_features))>0): remaining_features = list(set(initial_features)-set(best_features)) new_pval = pd.Series(index=remaining_features) for new_column in remaining_features: model = sm.OLS(target, sm.add_constant(data[best_features+[new_column]])).fit() new_pval[new_column] = model.pvalues[new_column] min_p_value = new_pval.min() if(min_p_value<significance_level): best_features.append(new_pval.idxmin()) else: break return best_features #Could not figure out how to do step in Python so I found this online df=pd.concat([x1,x2,x3,x4,x5,x6,x8,x9,x10,x11,x12,x13,x14], axis=1, ignore_index=True) #make frame of predicting variables forward_selection(df, y, significance_level=0.05) #d #Using forward selection, it would appear that x2,x3,x4,x8,x9,x10,x11,x12,x14 #are good variables to predict C200_4. Normally I would like to verify this with other #step directions but I am unable to find out how to do that.The output is the just #the columns in the df fram that are significant in predicting y. #Question 2 collegedata = pd.read_csv('C:/Users/spenc/Downloads/data/MERGED2007_08_PP.csv', usecols = ['CONTROL','AVGFACSAL','INC_PCT_LO','INC_PCT_M1', 'INC_PCT_M2','INC_PCT_H1','INC_PCT_H2','SATVRMID','SATMTMID', 'UGDS_WOMEN','ADM_RATE','PFTFAC','TUITIONFEE_IN','MD_EARN_WNE_P10']) collegedata=collegedata[collegedata != 'PrivacySuppressed'] collegedata.dropna(inplace=True) collegedata.astype(float) #finished importing old data set y = collegedata.MD_EARN_WNE_P10.astype(float) / collegedata.TUITIONFEE_IN.astype(float) #gets new y value x1 = collegedata.CONTROL results = sm.OLS(y,x1).fit() results.summary() x2 = collegedata.AVGFACSAL results = sm.OLS(y,x2).fit() results.summary() x3 = collegedata.INC_PCT_LO.astype(float) #for some reason these still were not floats results = sm.OLS(y,x3).fit() results.summary() x4 = collegedata.INC_PCT_M1.astype(float) results = sm.OLS(y,x4).fit() results.summary() x5 = collegedata.INC_PCT_M2.astype(float) results = sm.OLS(y,x5).fit() results.summary() x6 = collegedata.INC_PCT_H1.astype(float) results = sm.OLS(y,x6).fit() results.summary() x7 = collegedata.INC_PCT_H2.astype(float) results = sm.OLS(y,x7).fit() results.summary() x8 = collegedata.SATVRMID results = sm.OLS(y,x8).fit() results.summary() x9 = collegedata.SATMTMID results = sm.OLS(y,x9).fit() results.summary() x10 = collegedata.UGDS_WOMEN results = sm.OLS(y,x10).fit() results.summary() x12 = collegedata.ADM_RATE results = sm.OLS(y,x12).fit() results.summary() x13 = collegedata.PFTFAC results = sm.OLS(y,x13).fit() results.summary() #b linmod = smf.ols(formula = 'y~x1+x2+x3+x4+x5+x6+x8+x9+x10+x12+x13' ,data=collegedata, missing='drop').fit() linmod.summary() #c df=pd.concat([x1,x2,x3,x4,x5,x6,x8,x9,x10,x12,x13], axis=1, ignore_index=True) #make frame of predicting variables forward_selection(df, y, significance_level=0.05) #d #Using forward selection, it would appear that x1,x2,x3,x6,x8,x9 #are good variables to predict VALUE (y). Normally I would like to verify this with other #step directions but I am unable to find out how to do that. The output is the just #the columns in the df fram that are significant in predicting y.
from json import JSONEncoder class Person: def __init__(self, first_name, last_name, age): if not isinstance(age, int): raise TypeError("age must be an integer") self.first_name = first_name self.last_name = last_name self.age = age def __str__(self) -> str: return '{} {} - {} years old'.format(self.first_name, self.last_name, self.age) class PersonEncoder(JSONEncoder): def default(self, o): return o.__dict__
class App(object): @classmethod def get_store_id(cls, db, appid): sql = "SELECT store_id FROM app WHERE app.id=%s" r = db.execute(sql, appid) app = r.fetchone() if app and "store_id" in app: return app["store_id"] else: return 0
from django import forms from bbs.models import User, UserInfo from django.core.validators import RegexValidator class RegisterForm(forms.Form): name = forms.CharField(max_length=20, error_messages={'required': u'昵称不能为空'}, widget=forms.TextInput(attrs={'class': 'acct_name', 'placeholder': u'昵称'})) acct = forms.CharField(min_length=5, error_messages={'required': u'用户名不能为空', 'min_length': u'最少为5个字符'}, validators=[RegexValidator(r'^(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]{5,}$', "用户名至少包含一个字母")], widget=forms.TextInput(attrs={'class': 'acct_user', 'placeholder': u'用户名'})) password = forms.CharField(min_length=8, error_messages={'required': u'密码不能为空', 'min_length': u'最少为8个字符'}, widget=forms.PasswordInput(attrs={'class': 'acct_password', 'placeholder': u'密码'})) def clean_name(self): cd = self.cleaned_data is_exsit = UserInfo.objects.filter(name__exact=cd['name']) if is_exsit: raise forms.ValidationError(message='昵称已存在', code='invalid') return cd['name'] def clean_acct(self): cd = self.cleaned_data is_exsit = User.objects.filter(username__exact=cd['acct']) if is_exsit: raise forms.ValidationError(message='用户名已存在', code='invalid') return cd['acct'] class LoginForm(forms.Form): acct = forms.CharField(min_length=5, error_messages={'required': u'用户名不能为空', 'min_length': u'最少为5个字符'}, widget=forms.TextInput(attrs={'class': 'acct_name', 'placeholder': u'用户名、手机号或邮箱'})) password = forms.CharField(min_length=8, error_messages={'required': u'密码不能为空', 'min_length': u'最少为8个字符'}, widget=forms.PasswordInput(attrs={'class': 'acct_password', 'placeholder': u'密码'})) remember = forms.BooleanField(required=False, initial=False, widget=forms.CheckboxInput(attrs={"value": "true", "checked": "checked"})) def clean_acct(self): cd = self.cleaned_data is_exsit = User.objects.filter(username__exact=cd['acct']) if is_exsit is None: raise forms.ValidationError(message='用户名不存在', code='invalid') return cd['acct']
# Generated by Django 2.0.7 on 2018-10-09 06:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('rocky', '0012_poetry_poetrycomment'), ] operations = [ migrations.AddField( model_name='contentcomment', name='owner', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='chapter_commener', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='diary', name='owner', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='diary_author', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='notice', name='end_time', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='End_time'), ), migrations.AddField( model_name='notice', name='owner', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='notic_author', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='poetrycomment', name='owner', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='poetry_commener', to=settings.AUTH_USER_MODEL), ), ]
# imports from flask import Flask, jsonify, request # create the application app = Flask(__name__) @app.route('/test', methods=['GET']) def test(): if request.method == 'GET': return jsonify({"dude": "hello dude"}) if __name__ == "__main__": app.run(debug = True)
import os class Downloader: def __init__(self): pass def run(self): for link in self.read_file(): command = "wget " + link self.command_line(command) def read_file(self): links = [] with open("links.txt", "r+") as fp: for line in fp: links.append(line) return links def command_line(self, command): os.system(command) if __name__ == "__main__": Downloader().run()
# import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2 import numpy as np if __name__ == '__main__': def onMouse(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: # draw circle here (etc...) b,g,r = image[y, x] b = int(b) g = int(g) r = int(r) print(r) print(g) print(b) #print('pixel') #print(pixel) #pixel = np.uint8([[pixel]]) #hsv = cv2.cvtColor(pixel, cv2.COLOR_BGR2HSV) #print('hsv') #print(hsv) def grayscale(): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow('gray', gray) # fileName = input("File Name:") # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() rawCapture = PiRGBArray(camera) # allow the camera to warmup time.sleep(0.2) # grab an image from the camera print("Capturing Image...") try: camera.capture(rawCapture, format="bgr") image = rawCapture.array image = cv2.cvtColor( image, cv2.COLOR_BGR2RGB ) small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) print(image.size) # image = cv2.cvtColor( image, cv2.COLOR_BGR2RGB ) except: print("Failed to capture") # save the image to the disk # print("Saving image "+fileName) # display the image on screen and wait for a keypress # display the image on screen and wait for a keypress cv2.imshow('Image', small) grayscale() cv2.setMouseCallback('Image', onMouse) # yellow boundary = ([20, 100, 100], [30, 255, 255]) print(boundary[0]) lower = np.array(boundary[0], dtype = "uint8") upper = np.array(boundary[1], dtype = "uint8") hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV) # Apply the cv2.inrange method to create a mask mask = cv2.inRange(hsv, lower, upper) # Apply the mask on the image to extract the original color frame = cv2.bitwise_and(small, small, mask=mask) cv2.imshow("images", np.hstack([small, frame])) cv2.waitKey(0) #try: # cv2.imshow("Image", image) #except Exception, e: # print e cv2.waitKey(0) cv2.destroyAllWindows()
import click import os import json base_path = "./" @click.command() @click.argument('path') @click.argument('root_name') def cli(path, root_name): """This command traverses the dokka directory and look for .md files to map the hierarchy of files """ global base_path base_path = path directory_map = directory_tree_to_map(path, root_name) sidebar = sidebar_map(directory_map) json_dump = json.dumps(sidebar, indent=2, sort_keys=False) with open("sidebars.js", "w") as sidebar_file: sidebar_file.write("module.exports = ") sidebar_file.write(json_dump) def sidebar_map(content_map): docs_list = list() docs_list.append(content_map) return {"docs": docs_list} def folders_and_items(path): directory_files = os.listdir(path) directory_paths = list(map(lambda x: os.path.join(path, x), directory_files)) folders_path = list(filter(lambda x: os.path.isdir(x), directory_paths)) items_path = [item for item in directory_paths if item not in folders_path] folders = list(map(os.path.basename, folders_path)) items = list(map(os.path.basename, items_path)) return folders_path, items_path def get_docussauros_id(file_path): path_without_base = file_path.replace(base_path, "", 1) if path_without_base.startswith("/"): path_without_base = path_without_base[1:] return remove_extension(path_without_base) def remove_extension(path): return path.rsplit(".", 1)[0] def directory_tree_to_map(path, label): directory_map = {} directory_map['label'] = label directory_map['type'] = "category" folders_path, items_path = folders_and_items(path) cleaned_items = list(filter(is_markdown, items_path)) items = list(map(get_docussauros_id, cleaned_items)) items.sort() for folder_path in folders_path: folder_name = os.path.basename(folder_path) items.append(directory_tree_to_map(folder_path, folder_name)) directory_map['items'] = organize_items(items, label) return directory_map def organize_items(items, label): for item in items: if str(item).endswith("index"): items.remove(item) items.insert(0, item) elif str(item).endswith(label): if str(items[0]).endswith("index"): items.remove(item) items.insert(1, item) else: items.remove(item) items.insert(0, item) return items def is_markdown(file_path): return file_path.endswith(".md") def is_index_file(file_path): return file_path.endswith("index.md")
# -*- coding: utf-8 -*- from typing import List class Solution: def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: if mat == target: return True for _ in range(3): self.rotate(mat) if mat == target: return True return False def rotate(self, mat: List[List[int]]): n = len(mat) for i in range(n): for j in range(i + 1): mat[i][j], mat[j][i] = mat[j][i], mat[i][j] for i in range(n): for j in range(n // 2): mat[i][j], mat[i][n - j - 1] = mat[i][n - j - 1], mat[i][j] if __name__ == "__main__": solution = Solution() assert solution.findRotation( [ [0, 1], [1, 0], ], [ [1, 0], [0, 1], ], ) assert not solution.findRotation( [ [0, 1], [1, 1], ], [ [1, 0], [0, 1], ], ) assert solution.findRotation( [ [0, 0, 0], [0, 1, 0], [1, 1, 1], ], [ [1, 1, 1], [0, 1, 0], [0, 0, 0], ], )
#!/usr/bin/python3.4 # -*-coding:Utf-8 from aff_float import aff_float as trunc_float print(trunc_float(3.8966))
from ephemeral.engine.src.main.driver.task_driver import get_input_function from ephemeral.build_api.lib_function import LibFunction from ephemeral.build_api.job_task import JobTask class JobBuilder(object): def __init__(self, job_name): self.job_name = job_name self.input_task = None self.input_data = None self._tasks = [] def _add_task(self, task: JobTask): self._tasks.append(task) def create_input_task(self, data, name='in') -> JobTask: if self.input_data: raise ValueError('Input task has already been created!') self.input_data = data input_function = LibFunction('input', get_input_function()) input_task = JobTask(name=name, type='input', lib_function=input_function, parent=None) input_task.set_task_created_callback(self._task_created) self.input_task = input_task self._add_task(input_task) return input_task def _task_created(self, task: JobTask): """ Called when a task is created for this job. Validate, add to job tasks, and return the task if valid :param task: :return: the task if valid """ # TODO: Make sure the task is valid. check to make sure task name is unique in this job context # TODO: Map input keys from previous task to this task # Set the callback to be called when a new task is created from this task task.set_task_created_callback(self._task_created) self._add_task(task) # Add to task collection return task def print_tasks(self): for t in self._tasks: print(t.to_dict())
# Generated by Django 2.2.18 on 2021-09-03 06:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('form_test', '0005_auto_20210903_1208'), ] operations = [ migrations.AlterField( model_name='consentdatemodel', name='data_categories_to_fetch', field=models.CharField(choices=[('everything', 'Everything'), ('only non-sensitive data', 'Only Non-Sensitive Data')], max_length=100), ), ]
import configparser # CONFIG config = configparser.ConfigParser() config.read('dwh.cfg') # ACESS INFO FROM CONFIG FILE arn = config['IAM_ROLE']['ARN'] log_data = config['S3']['LOG_DATA'] log_json_path = config['S3']['LOG_JSONPATH'] song_data = config['S3']['SONG_DATA'] region = config['GEO']['REGION'] # COPY STAGING TABLES FROM S3 #--------------------------------------------------------------------------------------------- staging_log_copy = (""" copy staging_log from {} iam_role {} json {} """).format(log_data, arn, log_json_path) # Load from JSON Data Using the 'auto' Option staging_song_copy = (""" copy staging_song from {} iam_role {} json 'auto' """).format(song_data, arn) #--------------------------------------------------------------------------------------------- # INSERT TABLES #---------------------------------------------------------------------------------------------- songplay_table_insert = (""" INSERT INTO fact_songplay ( start_time, user_id, level, song_id, artist_id, session_id, location, user_agent) SELECT DISTINCT TIMESTAMP 'epoch' + sl.ts/1000 \ * INTERVAL '1 second' as start_time, sl.userId as user_id, sl.level as level, ss.song_id as song_id, ss.artist_id as artist_id, sl.sessionId as session_id, sl.location as location, sl.userAgent as user_agent FROM staging_log AS sl JOIN staging_song AS ss ON (sl.artist = ss.artist_name) WHERE sl.page = 'NextSong'; """) song_table_insert = (""" INSERT INTO dim_song ( song_id, title, artist_id, year, duration) SELECT DISTINCT ss.song_id AS song_id, ss.title AS title, ss.artist_id AS artist_id, ss.year AS year, ss.duration AS duration FROM staging_song AS ss; """) user_table_insert = (""" INSERT INTO dim_user ( user_id, first_name, last_name, gender, level) SELECT DISTINCT sl.userId AS user_id, sl.firstName AS first_name, sl.lastName AS last_name, sl.gender AS gender, sl.level AS level FROM staging_log AS sl WHERE sl.page = 'NextSong'; """) artist_table_insert = (""" INSERT INTO dim_artist ( artist_id, name, location, latitude, longitude) SELECT DISTINCT ss.artist_id AS artist_id, ss.artist_name AS name, ss.artist_location AS location, ss.artist_latitude AS latitude, ss.artist_longitude AS longitude FROM staging_song AS ss; """) time_table_insert = (""" INSERT INTO dim_time ( start_time, hour, day, week, month, year, weekday) SELECT DISTINCT TIMESTAMP 'epoch' + sl.ts/1000 \ * INTERVAL '1 second' AS start_time, EXTRACT(hour FROM start_time) AS hour, EXTRACT(day FROM start_time) AS day, EXTRACT(week FROM start_time) AS week, EXTRACT(month FROM start_time) AS month, EXTRACT(year FROM start_time) AS year, EXTRACT(week FROM start_time) AS weekday FROM staging_log AS sl WHERE sl.page = 'NextSong'; """) #--------------------------------------------------------------------------------- #LIST copy_table_queries = [staging_log_copy,staging_song_copy] insert_table_queries = [songplay_table_insert, user_table_insert, song_table_insert, artist_table_insert, time_table_insert]
from ipfs import create_app import logging if __name__ == '__main__': app = create_app() app.logger.addHandler(logging.StreamHandler()) app.run('0.0.0.0', 4444)
import pandas as pd from Bio import Entrez from Bio.Entrez import efetch from tqdm import tqdm Entrez.email = "Your.Name@example.org" def get_from_pubmed(df, text_column: str = "abstracts", labels_column: str = "labels"): pubmed_id_column = "PMID" df[labels_column] = 1 df.loc[df["Status"] == "Excluded", labels_column] = 0 df[text_column] = "" for pubmed_id in tqdm(df[pubmed_id_column].tolist()): try: handle = efetch( db="pubmed", id=pubmed_id, retmode="text", rettype="abstract" ) df.loc[df[pubmed_id_column] == pubmed_id, text_column] = handle.read() except Exception as E: print(E, pubmed_id) df.loc[df[pubmed_id_column] == pubmed_id, text_column] = "empty" return df[[text_column, labels_column]] def prepare_fluoride_dataset( df: pd.DataFrame, text_column: str = "abstracts", labels_column: str = "labels" ): """This function creates a dataframe in a shape that is later on accepted by the DAE model. :param df: :param text_column: contains data from Title and Abstract columns :param labels_column: contains numerized data from 'Included' column :return: """ df[text_column] = df["Title"].fillna("") + "." + df["Abstract"].fillna("") df[labels_column] = 1 df.loc[df["Included"] == "EXCLUDED", labels_column] = 0 return df[[text_column, labels_column]] if __name__ == "__main__": input_folder = "../../data/raw/SWIFT/" output_folder = "../../data/processed/" datasets = { "Fluoride.tsv": prepare_fluoride_dataset, "BPA.tsv": get_from_pubmed, "Transgenerational.tsv": get_from_pubmed, "PFOS-PFOA.tsv": get_from_pubmed, } for filename, parsing_function in datasets.items(): print(filename) input_data = f"{input_folder}/{filename}" output_data = f"{output_folder}/{filename}" df = pd.read_csv(input_data, sep="\t") df = parsing_function(df) df.to_csv(output_data, sep="\t", index=False)
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import sys import math def init(): glClearColor(1.0,1.0,1.0,0.0) glColor3f(1.0,0.0,0.0) glPointSize(3.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0,600.0,0.0,600.0) def readinput(): global r,xc,yc r=input("Enter radius of circle : ") xc=input("Enter x coordinate of center : ") yc=input("Enter y coordinate of center : ") def drawcircle(r,xc,yc): pk=3-2*r setpixel(0,r) x,y=0,r while(x<y): if pk<0: pk1=pk+6+4*x x=x+1 y=y pk=pk1 if pk>0: pk2=pk+10+4*(x-y) x=x+1 y=y-1 pk=pk2 setpixel(xc+x,yc+y) setpixel(xc+x,yc-y) setpixel(xc-x,yc+y) setpixel(xc-x,yc-y) setpixel(xc+y,yc+x) setpixel(xc+y,yc-x) setpixel(xc-y,yc+x) setpixel(xc-y,yc-x) def display(): glClear(GL_COLOR_BUFFER_BIT) drawcircle(r,xc,yc) def setpixel(x,y): glBegin(GL_POINTS) glVertex2f(x,y) glEnd() glFlush() def main(): glutInit(sys.argv) glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB) glutInitWindowSize(600,600) glutInitWindowPosition(100,100) glutCreateWindow("BRESENHAMS CIRCLE ALgo ") readinput() glutDisplayFunc(display) init() glutMainLoop() main()
from utils.augmentation import Compose, ConvertFromInts, ToAbsoluteCoords, \ PhotometricDistort, Expand, RandomSampleCrop, RandomMirror, \ ToPercentCoords, Resize, SubtractMeans from make_datapath import make_datapath_list from extract_inform_annotation import Anno_xml from lib import * class DataTransform(): def __init__(self, input_size = 300, corlor_mean = (104, 117, 123)): self.input_size = input_size self.corlor_mean = corlor_mean self.data_transform= { 'train': Compose([ ConvertFromInts(), #convert image from int to float 32bit ToAbsoluteCoords(), #back annotation to normal type PhotometricDistort(), #change color Expand(self.corlor_mean), RandomSampleCrop(), RandomMirror(), ToPercentCoords(), Resize(self.input_size), SubtractMeans(self.corlor_mean) ]), 'val': Compose([ ConvertFromInts(), Resize(self.input_size), SubtractMeans(self.corlor_mean) ]) } def __call__(self, img, phase, boxes, labels): return self.data_transform[phase](img, boxes, labels) if __name__ == '__main__': classes = ['aeroplane','bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] #prepare train, valid, annotation list rootpath = './data/VOCdevkit/VOC2012/' train_img_list, train_annotation_list, val_img_list, val_annotation_list = make_datapath_list(rootpath) #read image img_file_path = train_img_list[0] img = cv2.imread(img_file_path) height, width, channels = img.shape #annotation infor trans_anno = Anno_xml(classes) anno_info_list = trans_anno(train_annotation_list[0], width, height) #plot original image plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() #prepare data_transform corlor_mean = (104, 117, 123) input_size = 300 transform = DataTransform(input_size, corlor_mean) #transform image phase = 'train' img_transformed, boxes, labels = transform(img, phase, anno_info_list[:,:4], anno_info_list[:,4]) plt.imshow(cv2.cvtColor(img_transformed, cv2.COLOR_BGR2RGB)) plt.show() #transform image phase = 'val' img_transformed, boxes, labels = transform(img, phase, anno_info_list[:,:4], anno_info_list[:,4]) plt.imshow(cv2.cvtColor(img_transformed, cv2.COLOR_BGR2RGB)) plt.show()
../gasp/slt_calibration_science_calibration_1day_180S.py
from django.conf.urls import patterns, include, url from django.contrib import admin from books import views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^search/', views.search), url(r'^delete/', views.delete), url(r'^$', views.table), url(r'^information/', views.bookinformation), url(r'^authorinformation/', views.authorinformation), url(r'^add/', views.add), url(r'^author/', views.author), url(r'^addauthor/', views.add_author), )
ls myp %myp cd Desktop/myproj/haar\ py\ tests ls run classifier.py haarcascade_russian_plate_number.xml images/2715DTZ.jpg run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG roi cv2.calcHist([roi], [0], None, [256], [0, 256]) hist = cv2.calcHist([roi], [0], None, [256], [0, 256]) from matplotlib import pyplot as plt plt.hist(roi.ravel(), 256, [0, 256]); plt.show(); _, otsu = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) cv2.imshow("roi", otsu);cv2.waitKey(0); cv2.imshow("roi", otsu);cv2.waitKey(0); otsu_bkup = otsu cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) im2, contours, hierarchy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours, hierarchy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(otsu, contours, -1, (0, 255, 0), 3) contours, hierarchy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours, hierarchy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cv2.imshow("roi", otsu);cv2.waitKey(0); import numpy as np mask = np.zeros(otsu.shape, np.uint8) for cnt in contours: if 200<cv2.contourArea(cn exit ; X): vdk cv2.imshow("roi", otsu);cv2.waitKey(0); cv2.imshow("roi", otsu_bkup);cv2.waitKey(0); _, otsu = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) cv2.imshow("roi", otsu);cv2.waitKey(0); contours, hierarchy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: if 200<cv2.contourArea(cnt)<5000: cv2.drawContours(img, [cnt], 0, 255, 2) cv2.drawContours(mask, [cnt], 0, 255, -1) cv2.imshow("roi", img);cv2.waitKey(0); cv2.imshow("roi", img);cv2.waitKey(0); cv2.imshow("roi", mask);cv2.waitKey(0); cv2.imshow("roi", mask);cv2.waitKey(0); contours ar = [] for cnt in contours: ar.append(cv2.contourArea(cnt)) ar plt.hist(ar, 256, [0, 256]); plt.show(); np.mean(ar) m = np.mean(ar) np.where(ar>0.8*m and ar<1.2*m) np.where(ar>0.8*m) np.where(ar>0.8*m && ar < 1.2*m) np.where(ar>0.8*m and ar < 1.2*m) np.where(ar>0.8*m & ar < 1.2*m) np.where((ar>0.8*m) & (ar < 1.2*m)) np.where((ar>0.6*m) & (ar < 1.6*m)) np.where((ar>0.6*m) & (ar < 3*m)) ar[np.where((ar>0.6*m) & (ar < 3*m))] ar[np.where((ar>0.6*m) & (ar < 3*m))[0]] ar = np.array(ar) ar[np.where((ar>0.6*m) & (ar < 3*m))[0]] t=np.where((ar>0.6*m) & (ar < 3*m)) contours[t] t=np.where((ar>0.6*m) & (ar < 3*m))[0] contours[t] contours = np.array(contours) contours[t] contoursFil = contours[t] cv2.drawContours(otsu, contoursFil, -1, (0, 255, 0), 3) cv2.drawContours(otsu, contoursFil, -1, (0, 255, 0), 3) cv2.imshow("roi", otsu);cv2.waitKey(0); img2 = np.zeros(mask.shape, dtype=np.uint8) cv2.drawContours(img2, contoursFil, -1, (0, 255, 0), 3) cv2.imshow("roi", img2);cv2.waitKey(0); cv2.drawContours(img2, contoursFil, -1, 255, 3) cv2.imshow("roi", img2);cv2.waitKey(0); t=np.where((ar>0.6*m) & (ar < 2*m))[0] len(t) cv2.drawContours(img2, contours[t], -1, 255, 3) cv2.imshow("roi", img2);cv2.waitKey(0); img2 = np.zeros(mask.shape, dtype=np.uint8) cv2.drawContours(img2, contours[t], -1, 255, 3) cv2.imshow("roi", img2);cv2.waitKey(0); %history %history > hist.py ls export('history', 'hist.py') import sys export('history', 'hist.py') %history -f hist.py ls cv2.imshow("roi", img2);cv2.waitKey(0); cnt cv2.moments(cnt) np.mean(cnt) np.mean(cnt[0,:]) cnt np.mean(cnt[:, 0]) np.mean(cnt[:, 1]) np.mean(cnt[:, ]) cnt[0] cnt[:,0] cnt[:,1] cnt[:][0] cnt[:][1] cnt[0] cnt[1] cnt[1][0] cnt[1][0][0] cnt[:][0][0] cnt[2][0][0] cnt[3][0][0] cnt cnt[:] cnt[:,0,0] np.mean(cnt[:,0,0]) cnt[:,0,1] cv2.kmeans(otsu, 2) cv2.kmeans(otsu, 2, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER), 10, 1.0) cv2.kmeans(otsu, 2, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), 10,cv2.KMEANS_RANDOM_CENTERS) cv2.kmeans(otsu, 2, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), 10,cv2.KMEANS_RANDOM_CENTERS) cv2.KMEANS_RANDOM_CENTERS cv2.kmeans(otsu, 2, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), 10,int(cv2.KMEANS_RANDOM_CENTERS)) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) cv2.kmeans(np.float32(otsu), 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) cv2.kmeans(np.float32(otsu), 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ret, label, center = cv2.kmeans(np.float32(otsu), 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ret, label, center = cv2.kmeans(np.float32(otsu), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) label ret, label, center = cv2.kmeans(np.float32(otsu), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) otsu == 255 np.where(otsu == 255) np.where(otsu == 0) otsu cnt[1][0] _, otsu = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) np.where(otsu == 0) zip(np.where(otsu == 0)) zip(np.where(otsu == 0)[0], n) t = np.where(otsu == 255) zip(t[0], t[1]) ret, label, center = cv2.kmeans(np.float32(zip(t[0], t[1]), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ) points = zip(t[0], t[1]) ret, label, center = cv2.kmeans(np.float32(zip(t[0], t[1]), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ) ret, label, center = cv2.kmeans(np.float32(points), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ret label a = otsu(label.ravel() == 0) a = otsu[label.ravel() == 0] a = points[label.ravel() == 0] points = np.float32(points) a = points[label.ravel() == 0] b = points[label.ravel() == 1] A = a B = b plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() ret, label, center = cv2.kmeans(np.float32(zip(t[1], t[0]), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ) ret, label, center = cv2.kmeans(np.float32(zip(t[1], t[0])), 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) A = points[label.ravel() == 0] points = np.float32(zip(t[1], t[0])) ret, label, center = cv2.kmeans(points, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) A = points[label.ravel() == 0] B = points[label.ravel == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() B A points = np.float32(zip(t[0], t[1)) ;) points = np.vstack(t[0], t[1]) points = np.vstack(t) points points = np.float32(points) cv2.kmeans(np.float32(otsu), 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) ret, label, center = cv2.kmeans(points, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) A = A = points[label.ravel() == 0] B = points[label.ravel == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() B A points points = np.vstack((t[1], t[0])) ret, label, center = cv2.kmeans(points, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) points = np.float32(points) ret, label, center = cv2.kmeans(points, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) A = points[label.ravel() == 0] B = points[label.ravel == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() A B points np.vstack points = zip(t[1], t[0]) ret, label, center = cv2.kmeans(points, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) points = np.float32(points) ret, label, center = cv2.kmeans(points, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() A B A = points[label.ravel() == 0] B = points[label.ravel == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() label A B points label == 0 A = points[label.ravel() == 0] A B = points[label.ravel() == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() ret, label, center = cv2.kmeans(points, 3, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) A = points[label.ravel() == 0] B = points[label.ravel() == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() ret, label, center = cv2.kmeans(points, 10, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) A = points[label.ravel() == 0] B = points[label.ravel() == 1] plt.scatter(A[:,0],A[:,1]) plt.scatter(B[:,0],B[:,1],c = 'r') plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's') plt.xlabel('Height'),plt.ylabel('Weight') plt.show() run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG r run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG roi.copy() run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/7215BGN.JPG run classifier.py haarcascade_russian_plate_number.xml images/9773BNB.jpg run classifier.py haarcascade_russian_plate_number.xml images/9588DWV.jpg run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG run classifier.py haarcascade_russian_plate_number.xml images/9588DWV.jpg run classifier.py haarcascade_russian_plate_number.xml images/9588DWV.jpg run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG run classifier.py haarcascade_russian_plate_number.xml images/3028BYS.JPG cls ls cd .. cd lprs_trial/ ls run lprs.py xmls/haarcascade_russian_plate_number.xml images/3028BYS.JPG run lprs.py xmls/haarcascade_russian_plate_number.xml images/* xport('history', 'hist.py') run lprs.py xmls/haarcascade_russian_plate_number.xml images/* run lprs.py xmls/haarcascade_russian_plate_number.xml images/* run lprs.py xmls/haarcascade_russian_plate_number.xml images/* mva 0.86/1.62 run lprs.py xmls/haarcascade_russian_plate_number.xml images/* mva run lprs.py xmls/haarcascade_russian_plate_number.xml images/* mva np.mean(mva) run lprs.py xmls/haarcascade_russian_plate_number.xml images/* run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run svm.py run svm.py svm.predict(testData[0]) testData[0] ls cv2.imshow("roi", img);cv2.waitKey(0); run svm.py cv2.imshow("roi", img);cv2.waitKey(0); img img==255 img==1 np.where(img == 255) np.where(img == 1) np.where(img == 3) np.where(img == 0) np.where(img == 256) img.shape i len(cells) cells[0] len(cells[0]) len(cells[0][0]) len(cells[0][0][0]) len(cells[0][0][0][0]) cv2.resize(temp, (20, 20)) run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg rm -r 0.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg svm.predict(temp) temp svm.predict(temp) cells cells[0] cells[0][0] cells[0][0][0] len(cells[0][0][0]) svm svm svm.predict(temp) temp cv2.imwrite("output/temp.jpg", temp) import pytesseract pytesseract.image_to_string(temp) pytesseract.image_to_string(temp) t1 = cv2.imread("output/temp.jpg",0) pytesseract.image_to_string(t1) t1 = cv2.imread("output/temp.jpg") pytesseract.image_to_string(t1) t1 = cv2.imread("output/temp.jpg") t1 from PIL import Image pytesseract.image_to_string(Image.open("output/temp.jpg")) pytesseract.image_to_string(Image.open("output/1.jpg")) pytesseract.image_to_string(Image.open("output/2.jpg")) cv2.imwrite("output/temp.jpg", temp) cv2.imshow("roi", temp);cv2.waitKey(0); cv2.imshow("roi", temp);cv2.waitKey(0); cv2.imshow("roi", temp);cv2.waitKey(0); t1 cv2.imshow("roi", t1);cv2.waitKey(0); cv2.imwrite("output/temp.jpg", otsu) pytesseract.image_to_string(Image.open("output/temp.jpg")) cv2.imshow("roi", otsu);cv2.waitKey(0); cv2.imwrite("output/temp.jpg", otsuBkup) cv2.imshow("roi", otsuBkup);cv2.waitKey(0); temp t1 cv2.imshow("roi", t1);cv2.waitKey(0); kernel = np.ones((5, 5), np.uint8) er = cv2.erode(img, kernel, iterations=1) cv2.imshow("roi", er);cv2.waitKey(0); er = cv2.erode(t1, kernel, iterations=1) cv2.imshow("roi", er);cv2.waitKey(0); er = cv2.erode(t1, np.ones((3, 3), np.uint8), iterations=1) cv2.imshow("roi", er);cv2.waitKey(0); run lprs.py xmls/haarcascade_russian_plate_number.xml images/ cv2.imshow("roi_"+str(idx), temp);cv2.waitKey(0); er = cv2.erode(t1, np.ones((3, 3), np.uint8), iterations=1) run lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run python/lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg run python/lprs.py xmls/haarcascade_russian_plate_number.xml images/9588DWV.jpg hist = cv2.calcHist([roi], [0], None, [256], [0, 256]) %history -f python/histTrial.py
import argparse import sigpy as sp import scipy.ndimage as ndimage_c import numpy as np import sys sys.path.append("./sigpy_e/") import sigpy_e.cfl as cfl import sigpy_e.ext as ext import sigpy_e.reg as reg from sigpy_e.linop_e import NFTs,Diags,DLD,Vstacks import sigpy.mri as mr import os import logging ## IO parameters parser = argparse.ArgumentParser(description='XD-GRASP recon.') parser.add_argument('--res_scale', type=float, default=.75, help='scale of resolution, full res == .75') parser.add_argument('--fov_x', type=float, default=1, help='scale of FOV x, full res == 1') parser.add_argument('--fov_y', type=float, default=1, help='scale of FOV y, full res == 1') parser.add_argument('--fov_z', type=float, default=1, help='scale of FOV z, full res == 1') parser.add_argument('--lambda_TV', type=float, default=5e-2, help='TV regularization, default is 0.05') parser.add_argument('--outer_iter', type=int, default=25, help='Num of Iterations.') parser.add_argument('--vent_flag', type=int, default=0, help='output jacobian determinant and specific ventilation') parser.add_argument('--n_ref_vent', type=int, default=0, help='reference frame for ventilation') parser.add_argument('--device', type=int, default=0, help='Computing device.') parser.add_argument('fname', type=str, help='Prefix of raw data and output(_mrL).') args = parser.parse_args() # res_scale = args.res_scale fname = args.fname lambda_TV = args.lambda_TV device = args.device outer_iter = args.outer_iter fov_scale = (args.fov_x, args.fov_y, args.fov_z) vent_flag = args.vent_flag n_ref_vent = args.n_ref_vent ## data loading data = np.load(os.path.join(fname, 'bksp.npy')) traj = np.real(np.load(os.path.join(fname, 'bcoord.npy'))) dcf = np.sqrt(np.load(os.path.join(fname,'bdcf.npy'))) nf_scale = res_scale nf_arr = np.sqrt(np.sum(traj[0,0,:,:]**2,axis = 1)) nf_e = np.sum(nf_arr<np.max(nf_arr)*nf_scale) scale = fov_scale traj[...,0] = traj[...,0]*scale[0] traj[...,1] = traj[...,1]*scale[1] traj[...,2] = traj[...,2]*scale[2] traj = traj[...,:nf_e,:] data = data[...,:nf_e] dcf = dcf[...,:nf_e] nphase,nCoil,npe,nfe = data.shape tshape = (np.int(np.max(traj[...,0])-np.min(traj[...,0])) ,np.int(np.max(traj[...,1])-np.min(traj[...,1])) ,np.int(np.max(traj[...,2])-np.min(traj[...,2]))) ### calibration ksp = np.reshape(np.transpose(data,(1,0,2,3)),(nCoil,nphase*npe,nfe)) dcf2 = np.reshape(dcf**2,(nphase*npe,nfe)) coord = np.reshape(traj,(nphase*npe,nfe,3)) mps = ext.jsens_calib(ksp,coord,dcf2,device = sp.Device(0),ishape = tshape) S = sp.linop.Multiply(tshape, mps) ### recon PFTSs = [] for i in range(nphase): FTs = NFTs((nCoil,)+tshape,traj[i,...],device=sp.Device(device)) W = sp.linop.Multiply((nCoil,npe,nfe,),dcf[i,:,:]) FTSs = W*FTs*S PFTSs.append(FTSs) PFTSs = Diags(PFTSs,oshape=(nphase,nCoil,npe,nfe,),ishape=(nphase,)+tshape) ## preconditioner wdata = data*dcf[:,np.newaxis,:,:] tmp = PFTSs.H*PFTSs*np.complex64(np.ones((nphase,)+tshape)) L=np.mean(np.abs(tmp)) ## reconstruction q2 = np.zeros((nphase,)+tshape,dtype=np.complex64) Y = np.zeros_like(wdata) q20 = np.zeros_like(q2) res_norm = np.zeros((outer_iter,1)) logging.basicConfig(level=logging.INFO) sigma = 0.4 tau = 0.4 for i in range(outer_iter): Y = (Y + sigma*(1/L*PFTSs*q2-wdata))/(1+sigma) q20 = q2 q2 = np.complex64(ext.TVt_prox(q2-tau*PFTSs.H*Y,lambda_TV)) res_norm[i] = np.linalg.norm(q2-q20)/np.linalg.norm(q2) logging.info('outer iter:{}, res:{}'.format(i,res_norm[i])) np.save(os.path.join(fname, 'prL.npy'), q2) #np.save(os.path.join(fname, 'prL_residual_{}.npy'.format(lambda_TV)), res_norm) #q2 = np.load(os.path.join(fname, 'prL.npy')) # jacobian determinant & specific ventilation if vent_flag==1: print('Jacobian Determinant and Specific Ventilation...') jacs = [] svs = [] q2 = np.abs(np.squeeze(q2)) q2 = q2/np.max(q2) for i in range(nphase): jac, sv = reg.ANTsJac(np.abs(q2[n_ref_vent]), np.abs(q2[i])) jacs.append(jac) svs.append(sv) jacs = np.asarray(jacs) svs = np.asarray(svs) np.save(os.path.join(fname, 'jac_prl.npy'), jacs) np.save(os.path.join(fname, 'sv_prl.npy'), svs)
from setuptools import setup, find_packages from codecs import open from os import path # Get the long description from the README file here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() # Get the installation requirements from install_requires.txt file with open(path.join(here, 'reqs_install.dep'), encoding='utf-8') as f: install_requires = f.readlines() setup( name='ruler', version='2.0.0', description='Humane grammar library', long_description=long_description, url='https://github.com/yanivmo/ruler', author='Yaniv Mordekhay', author_email='yaniv@linuxmail.org', license='MIT', # Add all packages under src packages=find_packages('src'), # src is the root directory for all the packages package_dir={'': 'src'}, install_requires=install_requires, # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='regex parsing grammar' )
import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QColor, QPainter from PyQt5.QtCore import Qt, QRect, QPoint, QTimer class AppDemo(QWidget): def __init__(self): super().__init__() self.resize(1200,800) self.color = QColor(Qt.red) self.rect_circle = QRect(0,0,50,50) self.rect_circle.moveCenter(QPoint(self.width() / 2, self.rect_circle.height() / 2)) self.step = QPoint(0,5) self.y_direction = 1 timer = QTimer(self, interval=10) timer.timeout.connect(self.update_position) timer.start() def paintEvent(self, event): bounce = QPainter(self) bounce.setPen(Qt.black) bounce.setBrush(Qt.red) bounce.drawEllipse(self.rect_circle) def update_position(self): if self.rect_circle.bottom() > self.height() and self.y_direction == 1: self.y_direction = -1 if self.rect_circle.top() < 0 and self.y_direction == -1: self.y_direction = 1 self.rect_circle.translate(self.step * self.y_direction) self.update() if __name__ == '__main__': app = QApplication(sys.argv) demo = AppDemo() demo.show() sys.exit(app.exec_())
### this is the edit part print('this is the child branch')
import numpy as np import tensorflow as tf import pandas as pd import matplotlib.pyplot as plt from numpy import newaxis from collections import Counter from sklearn.model_selection import train_test_split, GridSearchCV from imblearn.over_sampling import ADASYN, SMOTE, BorderlineSMOTE, SVMSMOTE # , KMeansSMOTE from keras.models import Sequential, Model from keras.models import load_model from keras.layers import LSTM, Dense, Dropout, CuDNNLSTM, Flatten, Concatenate, Input, merge from keras.regularizers import l2 from keras.optimizers import Adam, SGD from sklearn.metrics import balanced_accuracy_score, classification_report, confusion_matrix, accuracy_score from keras.utils import to_categorical from keras.utils import np_utils import keras.backend as K from itertools import product from functools import partial # ===================================================================================================================== # Custom loss function with costs def w_categorical_crossentropy(y_true, y_pred, weights): nb_cl = len(weights) final_mask = K.zeros_like(y_pred[:, 0]) print ('final_mask:',final_mask.shape) y_pred_max = K.max(y_pred, axis=1) print('y_pred_max:', y_pred_max.shape) y_pred_max = K.expand_dims(y_pred_max, 1) print('y_pred_max with expand dims:', y_pred_max.shape) y_pred_max_mat = K.equal(y_pred, y_pred_max) print('y_pred_max_mat:', y_pred_max_mat.shape) for c_p, c_t in product(range(nb_cl), range(nb_cl)): final_mask += (K.cast(weights[c_t, c_p],K.floatx()) * K.cast(y_pred_max_mat[:, c_p] ,K.floatx())* K.cast(y_true[:, c_t],K.floatx())) return K.categorical_crossentropy(y_pred, y_true) * final_mask w_array = np.ones((3,3)) w_array[0, 1] = 1.5 #penalty for classifying a dry day as normal w_array[0, 2] = 1.2 #penalty for classifying a dry day as wet w_array[2, 1] = 1.5 #penalty for classifying a wet day as normal w_array[2, 0] = 1.2 #penalty for classifying a wet day as dry defined_loss_func = partial(w_categorical_crossentropy, weights=w_array) #==================================================== # returns the month index and days in that month def months(index): #Indexes that correspond to June, July, Aug, Sep if 0 <= index < 30: return 0, 30 if 30 <= index < 61: return 1, 31 if 61 <= index < 92: return 2, 31 if 92 <= index < 122: return 3, 30 def month_class(index): day = index % 122 if day == 0 & index != 0: return 3, 30 else: return months(day) def Grid2TimeArr(Grid): ''' Takes in a 4d grid in form (Levels, Time Steps, Heighth, Width) and returns an array in form (Levels, Time Steps, 1) where each step is the mean from the HxW grid ''' t_steps = Grid.shape[1] t_array = np.zeros((Grid.shape[0], t_steps)) for j in range(0,Grid.shape[0]): for i in range(0,t_steps): m_val = Grid[j,i].mean() t_array[j,i] = m_val return t_array # #================================================ #Creating rainfall features ''' Note, if you are doing this (history) for Enso/Nino, you must take history before upscaling to 8174 format! ''' def CreateHist(Dataset, hist): climate_data_new = np.zeros((Dataset.shape[1], 1)) Dataset = Dataset[:, np.newaxis] for j in range(0,Dataset.shape[0]): climate_data_new = Dataset[j,:].T for i in range(1, hist): climate_data_hist = np.roll(Dataset[j,:].T, i, axis = 0) climate_data_new = np.concatenate( (climate_data_new, climate_data_hist), axis = 1) if j == 0: climate_data_final = climate_data_new else: climate_data_final = np.concatenate((climate_data_final, climate_data_new), axis = 1) x = pd.DataFrame(climate_data_final) return x # ========================================================== # This function extracts the Nino dataset for our summer months and # upscales them to 8174 def CreateNinoData(Dataset, hist): # Extracting Nino Dataset Nino = np.asarray(Dataset) month_nino = [] i = 0 j = 0 # Month indexes (i.e. Jan = 0, Feb = 1, ...) to choose from mon_1 = 5 mon_2 = 9 mons = abs(mon_1 - mon_2) while i < Nino.shape[0]: month_nino[j:(j + mons)] = Nino[(mon_1 + i):(mon_2 + i)] i += 12 j += mons month_nino = np.asarray(month_nino) #Creating Nino Dataset in 8174x1 form day_nino = np.zeros((8174,1)) i = 0 j = 0 dataset = day_nino for k in range (1,hist): month_nino = np.roll(month_nino, k, axis = 0) while j < month_nino.shape[0]: month, days = month_class(i) day_nino[i : (i + days)] = month_nino[j] i += days j += 1 dataset = np.concatenate((dataset, day_nino), axis = 1) Nino = pd.DataFrame(dataset) return Nino #============================================================== # This function fixes the overlap when rolling lables: # It removes the last X (Lead) from each year def FixRollingOverlap(Dataset, Labels, Lead): Dataset = np.asarray(Dataset) Labels = np.asarray(Labels) Labels = np.roll(Labels, - Lead) Labels[:] = Labels[:] - 1 indices = [] i = 0 while i < Dataset.shape[0]: temp_ind = np.arange((i + 122),(i + 122 + Lead)) indices = np.concatenate((indices, temp_ind), axis = None) i += 122 x = np.delete(Dataset, indices, axis = 0) y = np.delete(Labels, indices, axis = 0) x = pd.DataFrame(x) y = pd.DataFrame(y) print('Fixed X:', x.shape, 'Fixed Y:', y.shape) return [x,y] #================================================================ # Creating Enso Categorical Dataset def CreateEnsoData(Data): Data.Type = Data.Type.fillna('N') Data.Type[1] = 'ML' yr_enso = np.asarray(Data.Type) day_enso = pd.DataFrame(np.zeros((8174, 1)).astype(str)) i = 0 j = 0 while j < 67: day_enso[i:(i+122)] = yr_enso[j] i += 122 j += 1 x = pd.get_dummies(day_enso) return x #================================================== # Standarizes the dataset with mean = 0 and std = 1 def StandarizeData(Dataset): # Dataset = pd.DataFrame(Dataset) #Standarizing for i in range(0,Dataset.shape[1]): if Dataset.all() == 0 or Dataset.all() == 1: continue Dataset[i] = (Dataset[i] - Dataset[i].mean()) / Dataset[i].std() return Dataset #===================================================== # Determines the Month for each Index and turns it into a categorical pandas dataframe def MonthClassDataset(length): Month_Class_data = np.zeros((length,1)) for i in range (0,length): month, days = month_class(i) Month_Class_data[i] = month Month_Class_data = pd.DataFrame(Month_Class_data) X = pd.get_dummies(Month_Class_data.astype(str)) return X # function: divide the set into training, validation, and test set #============================================================ def divideIntoSets(x, y, test_ratio): x_train1, x_test, y_train1, y_test = train_test_split( x, y, test_size=test_ratio, shuffle=True) x_train, x_valid, y_train, y_valid = train_test_split( x_train1, y_train1, test_size=test_ratio, shuffle=True) return [x_train, x_valid, x_test, y_train, y_valid, y_test] #==================================================================================================================== # function: count the instances of each class of the classification problem def countClasses(classes): c0 = 0 c1 = 0 c2 = 0 for elt in classes: if elt == 0: c0 = c0 + 1 elif elt == 1: c1 = c1 + 1 elif elt == 2: c2 = c2 + 1 return [c0,c1,c2] #================================================================ def FNN_model(X_train, y_train, x_valid, y_valid, bs, lr, ep): # Constants # Have batch size and learning rate in an array to test?? #===================================== # Model Structure inputs = Input(shape=(X_train.shape[1],1)) flat_lay = Flatten()(inputs) lay_1 = Dense(64, activation="tanh")(flat_lay) # kernel_regularizer = l2(0.01) drop_1 = Dropout(0.4)(lay_1) lay_2 = Dense(64, activation="tanh")(drop_1) drop_2 = Dropout(0.4)(lay_2) testing = Concatenate()([drop_2, lay_2]) predictions = Dense(3, activation="softmax")(testing) model = Model(inputs=inputs, outputs=predictions) #===================================== # Optimizing and fitting opt = SGD(lr=lr, decay=1e-6, momentum=0.9, nesterov=True) # opt = Adam(lr=lr) model.compile(loss=defined_loss_func, optimizer=opt, metrics=['accuracy']) model.summary() print("\n********Testing with a batch size of " + str(bs) + " and a learning rate of " + str(lr) + "********\n") result = model.fit(X_train, y_train, epochs=ep, batch_size=bs, validation_data=( x_valid, y_valid), verbose=2, shuffle=True) return [model,result] #=============================================================== # Plots the model def PlotModelStats(history, path, filename): plt.figure() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('Var') plt.xlabel('Epoch') plt.legend(['train_loss', 'validation_loss'], loc='upper right') plt.savefig(path + filename + '.png') plt.close() # function: providing different classification performance measures #=================================================================================================================== def modelPerformanceClassificationMetrics(y_test_nor, y_pred_nor, path, filename): file = open(path + filename + ".txt", 'w') file.write("\nClassification report:\n") file.write(classification_report(y_test_nor, y_pred_nor)) file.write("\n\nConfusion matrix:\n") file.write(np.array2string(confusion_matrix( y_test_nor, y_pred_nor), separator=', ')) file.write("\n\nBalanced accuracy score:") file.write(str(balanced_accuracy_score(y_test_nor, y_pred_nor))) file.write("\n\nAccuracy:") file.write(str(accuracy_score(y_test_nor, y_pred_nor))) #===================================================================================================================== # function: convert the softmax probability of class to class label def predictToNumeric(pred): pred_numeric = [] for i in range(pred.shape[0]): if pred[i, 0] >= pred[i, 1] and pred[i, 0] >= pred[i, 2]: pred_numeric.append(0) elif pred[i, 1] >= pred[i, 0] and pred[i, 1] >= pred[i, 2]: pred_numeric.append(1) elif pred[i, 2] >= pred[i, 0] and pred[i, 2] >= pred[i, 1]: pred_numeric.append(2) else: continue pred_numeric = np.asarray(pred_numeric) print(pred.shape, pred_numeric.shape) return pred_numeric def SelectVariable(num, rain_data_hist, Enso, Nino_hist, Month_classes, uwnd, vwnd): if num == 0: return rain_data_hist elif num == 1: return Enso elif num == 2: return Nino_hist elif num == 3: return Month_classes elif num == 4: return uwnd elif num == 5: return vwnd else: return -1 def ExtrCentReg(Data,levels): long_min = 4 long_max = 10 lat_north = 5 lat_south = 7 # Fixing Time Data_new = np.empty((levels + 1, 8174, Data.shape[2], Data.shape[3])) for i in range(0,levels+1): j = 0 while j < 8174: Data_new[i,j:(122 + j),:,:] = Data[i,(16 + j):(16 + 122 + j),:,:] j += 122 #Extracting Lat/Long x = Data_new[:, :, lat_north:lat_south, long_min:long_max] return x def ExtractPredictedSamples(y_pred, y_test): # This array contains the index of the maximum value (per row) and a boolean for if it was correct or not index_flag = np.zeros((y_pred.shape[0], y_pred.shape[1])) for i in range(0, y_pred.shape[0]): max_val = 0 max_ind = -1 for j in range(0, y_pred.shape[1]): if y_pred[i][j] > max_val: max_val = y_pred[i][j] max_ind = j index_flag[i][max_ind] = 1 # Comparing predicted to test to extract index for incorrect samples same_ind = [] diff_ind = [] for i in range(0, y_test.shape[0]): if (y_test[i] == index_flag[i]).all(): same_ind.append(i) else: diff_ind.append(i) # ================================================================= # Creating an array of the differences between the true column and the predicted column true_colns = [] pred_colns = [] for i in range(0, y_test.shape[0]): for j in range(0, y_test.shape[1]): if y_test[i][j] == 1: true_colns.append(j) if index_flag[i][j] == 1: pred_colns.append(j) true_colns = np.array(true_colns).reshape((len(true_colns), 1)) pred_colns = np.array(pred_colns).reshape((len(pred_colns), 1)) temp_colns = np.concatenate((pred_colns, true_colns), axis = 1) vals_and_colns = np.concatenate((y_pred, temp_colns), axis = 1) # same_arr = np.delete(y_pred, diff_ind, axis = 0) diff_arr = np.asarray(np.delete(vals_and_colns, same_ind, axis = 0)) return diff_arr def GraphingDifference(arr): diff_arr = [] for i in range(0, arr.shape[0]): # Obtains the predicted pred/true values true_ind = int(arr[i][4]) pred_ind = int(arr[i][3]) pred_true = arr[i][true_ind] pred_pred = arr[i][pred_ind] difference = abs(pred_pred - pred_true) diff_arr.append(difference) diff_arr = np.asarray(diff_arr) # Graphing now x = np.arange((diff_arr.shape[0])) y = diff_arr plt.scatter(x, y) plt.show() #================================================================ # Main Function def main(): print('Starting Main...\n') #Loading in Raw Data rain_class_og = np.loadtxt( "C:/Users/user/Documents/Personal/Research/MachineLearningClimate19/DataSets/dataset_rainfall/Rainfall_Class_SC.csv", delimiter=',') # "C:/Users/user/Desktop/original_datasets/test_enso.csv", sep=',') # Nino = pd.read_csv( # "C:/Users/user/Desktop/original_datasets/nino_3.4_monthly.csv") # uwnd = np.load("C:/Users/user/Desktop/original_datasets/uwnd_cent_single_norm.npy") # vwnd = np.load("C:/Users/user/Desktop/original_datasets/vwnd_cent_single_norm.npy") # Loading in Vwnd, Uwnd, and Hgt uwnd_25 = np.load("C:/Users/user/Desktop/original_datasets/PressureData/uwnd_mult_norm.npy") vwnd_25 = np.load("C:/Users/user/Desktop/original_datasets/PressureData/vwnd_mult_norm.npy") hgt_25 = np.load("C:/Users/user/Desktop/original_datasets/PressureData/hgt_mult_norm.npy") # A n_level of 0 corresponds to surface level n_levels = [0,2,2] history = [0,2,2] for i in range(2,len(history)): rain_data = np.loadtxt("C:/Users/user/Documents/Personal/Research/MachineLearningClimate19/DataSets/dataset_rainfall/rainfall_data_SC.csv", delimiter=',') rain_data = rain_data[:, np.newaxis] rain_data = np.swapaxes(rain_data, 0, 1) uwnd = ExtrCentReg(uwnd_25,n_levels[i]) vwnd = ExtrCentReg(vwnd_25,n_levels[i]) hgt = ExtrCentReg(hgt_25,n_levels[i]) uwnd = Grid2TimeArr(uwnd) vwnd = Grid2TimeArr(vwnd) hgt = Grid2TimeArr(hgt) # Putting it in row x coln form if history == 0: uwnd = np.swapaxes(uwnd, 0, 1) vwnd = np.swapaxes(vwnd, 0, 1) hgt = np.swapaxes(hgt, 0, 1) rain_data = np.swapaxes(rain_data, 0, 1) else: # Adding History uwnd = CreateHist(uwnd, history[i]) vwnd = CreateHist(vwnd, history[i]) hgt = CreateHist(hgt, history[i]) rain_data = CreateHist(rain_data, history[i]) if i == 2: X = pd.DataFrame(np.concatenate((uwnd, vwnd, hgt, rain_data), axis = 1)) else: X = pd.DataFrame(np.concatenate((uwnd, vwnd, hgt), axis = 1)) #Fixing shape to be like the others (8174x1 vs. 1x8174) # rain_class_og = rain_class_og[:, np.newaxis] #Creating Datasets from functions with history - Note Enso/months are constant so it is outside the loop # Enso = CreateEnsoData(Enso) # Month_classes = MonthClassDataset(8174) history = [3, 4, 5] batch_size = [15, 25, 100, 150] bs = 75 # learning_rate = [0.00001,0.000001] lr = 0.00001 epochs = 30 lead = 3 X, y = FixRollingOverlap(X, rain_class_og, lead) test_ratio = 0.15 X = np.asarray(X) y = np.asarray(y) #Loading and fixing data to work with the model [X_train, x_valid, x_test, y_train, y_valid, y_test] = divideIntoSets(X, y, test_ratio) c1,c2,c3 = countClasses(y_train) #Balancing Data X_train, y_train = SMOTE().fit_resample(X_train, y_train) x_valid, y_valid = SMOTE().fit_resample(x_valid, y_valid) x_test_over, y_test_over = SMOTE().fit_resample(x_test, y_test) #Fixing Axes to work with FNN X_train = X_train[:, :, np.newaxis] x_valid = x_valid[:, :, np.newaxis] x_test = x_test[:, :, np.newaxis] x_test_over = x_test_over[:, :, np.newaxis] #Standarize # X_train, y_train = StandarizeData(X_train), y_train # one hot encode y_train = to_categorical(y_train) y_test = to_categorical(y_test) y_test_over = to_categorical(y_test_over) y_valid = to_categorical(y_valid) filename = "reg_loss_baseline_" + str(i+1) + "_" + str(history[i]) + "_hist_" + str(n_levels[i]) + "levels_" + str(lr) + "_" + str(bs) path = "C:/Users/user/Desktop/original_datasets/FNN_results/" model, result = FNN_model(X_train, y_train, x_valid, y_valid, bs, lr, epochs) # PlotModelStats(result, path, filename) # model = load_model('C:/Users/user/Desktop/model_FNN_TEST.h5') model.save('C:/Users/user/Desktop/model_FNN_TEST.h5') y_pred = model.predict(x_test) y_pred_over = model.predict(x_test_over) diff = ExtractPredictedSamples(y_pred_over, y_test_over) GraphingDifference(diff) y_pred_nor = predictToNumeric(y_pred) y_test_nor = predictToNumeric(y_test) y_pred_nor_over = predictToNumeric(y_pred_over) y_test_nor_over = predictToNumeric(y_test_over) modelPerformanceClassificationMetrics(y_test_nor, y_pred_nor, path, filename) modelPerformanceClassificationMetrics(y_test_nor_over, y_pred_nor_over, path, 'oversample_' + filename) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-08-04 22:48 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('siwedeeapp', '0011_auto_20160731_1030'), ] operations = [ migrations.RenameField( model_name='catcarreras', old_name='IDCARREA', new_name='IDCARRERA', ), migrations.AlterField( model_name='catalumnos', name='IDALUMNO', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='siwedeeapp.CATPERSONAS'), ), ]
#!/usr/bin/python3 import asyncio async def count(): # async key word to make a funciton async print("One") await asyncio.sleep(1) # await keyword, suspend current job and run other jobs print("Two") async def main(): await asyncio.gather(count(), count(), count()) asyncio.run(main())
print("송진우") print("30") print("오늘부터 1일이네요")
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': ''' 用numpy的包读取数据为一个数组 属性:花萼长度,花萼宽度,花瓣长度,花瓣宽度 ''' data_array = np.loadtxt("iris.data.txt", delimiter=',') '''选择花瓣长度''' data = data_array[:, 2] plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 '''散点图,以第一列数据和第二列数据分别作为x,y轴,用蓝色和*标记''' # plt.plot(data_array[:, 0], data_array[:, 1], "b*") # plt.xlabel(u"花萼长度") # plt.ylabel(u"花萼宽度") '''直方图,以第一列数据及其分布分别作为x,y轴''' # plt.hist(data_array[:, 0], 50) # plt.xlabel(u'花萼长度') '''箱型图,一第一列数据绘制''' # plt.boxplot([data_array[:, 0]], labels=[u'长度']) # plt.title(u'花萼长度') # plt.show() '''茎叶图''' plt.stem(data_array[:, 0], data_array[:, 1]) plt.show() plt.show()
from .instapy import InstaPy
from django.urls import path from .views import * app_name = 'ReviewApp' urlpatterns = [ path('review/<int:rev_pk>/rebuttal/<int:reb_pk>/detail/', rebuttal_detail, name="get_rebuttal_detail"), path('review/<int:rev_pk>/rebuttal/<int:reb_pk>/delete/', RebuttalDelete.as_view(), name="delete_rebuttal"), path('review/<int:rev_pk>/rebuttal/<int:reb_pk>/update/', RebuttalUpdate.as_view(), name="update_rebuttal"), path('review/<int:pk>/rebuttal/add/', RebuttalCreate.as_view(), name="add_rebuttal"), path('review/<int:pk>/rebuttals/', rebuttals_list, name="get_rebuttals_list"), path('review/<int:pk>/detail/', review_detail, name="get_review_detail"), path('review/<int:pk>/delete/', ReviewDelete.as_view(), name="delete_review"), path('review/<int:pk>/update/', ReviewUpdate.as_view(), name="update_review"), path('review/add/', ReviewCreate.as_view(), name="add_review"), path('reviews/', reviews_list, name="get_reviews_list"), path('info-page/', redirect_to_info, name="get_info"), path('accounts/register/', RegisterUserView.as_view(), name='register'), path('accounts/profile/add_complaint/', ComSugCreate.as_view(), name='add_complaint'), path('accounts/profile/change-user-info', ChangeUserInfoView.as_view(), name="change_user_info"), path('accounts/profile/password/change/', UserPasswordChangeView.as_view(), name='password_change'), path('accounts/password/reset/done/', UserPasswordResetDoneView.as_view(), name='password_reset_done'), path('accounts/password/reset/', UserPasswordResetView.as_view(), name='password_reset'), path('accounts/password/confirm/complete/', UserPasswordResetCompleteView.as_view(), name='password_reset_complete'), path('accounts/password/confirm/<uidb64>/<token>/', UserPasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('accounts/profile/review/<int:rev_pk>/rebuttal<int:reb_pk>/delete', ProfRebuttalDelete.as_view(), name="prof_rebuttal_delete"), path('accounts/profile/review/<int:rev_pk>/rebuttal<int:reb_pk>/detail', prof_rebuttal_detail, name="prof_rebuttal_detail"), path('accounts/profile/review/<int:pk>/delete', ProfReviewDelete.as_view(), name="rev_prof_delete"), path('accounts/profile/review/<int:pk>/rebuttals', review_profile_rebuttals_on_me, name="rev_prof_rebuttals_on_me"), path('accounts/profile/review/<int:pk>/detail', prof_review_detail, name="prof_review_detail"), path('accounts/profile/rebuttals-on-me', profile_rebuttals_on_me, name="profile_rebuttals_on_me"), path('accounts/profile/rebuttals', profile_rebuttals, name="profile_rebuttals"), path('accounts/profile/reviews', profile_reviews, name="profile_reviews"), path('accounts/profile/', profile, name="profile"), path('accounts/logout/', logout_request, name="logout"), path('accounts/login/', LoginUser.as_view(), name="login"), path('', main, name="main"), ]
import gym import torch import DeepNEAT.NEAT_implementation.Population.population as population import DeepNEAT.configurations.poleBalancing.poleBalancing as config from DeepNEAT.NEAT_implementation.Phenotype.feedForwardNetwork import FeedForwardNetwork import time from DeepNEAT.visualization.Visualization import draw_net import torch.nn as nn import torch.nn.functional as F configuration = config.PoleBalanceConfig() if configuration.BUILD_TEST_DATA == True: configuration.build_test_data() neat = population.Population(configuration) solution, generation = neat.run() if solution is not None: # print('Found a Solution') draw_net(solution, view=True, filename='images/pole-balancing-solution', show_disabled=True) # OpenAI Gym env = gym.make('LongCartPole-v0') done = False observation = env.reset() fitness = 0 phenotype = FeedForwardNetwork(solution, config.PoleBalanceConfig) torch.save(solution, "./Results/" + neat.configuration.GAME + '/' + neat.configuration.GAME + '_final') while not done: env.render() input = torch.Tensor([observation]).to(config.PoleBalanceConfig.DEVICE) pred = torch.argmax(phenotype(input)[0]).numpy() observation, reward, done, info = env.step(pred) fitness += reward env.close() # class Net(nn.Module): # def __init__(self): # super(Net, self).__init__() # self.fc1 = nn.Linear(4, 4, False) # self.fc2 = nn.Linear(4, 2, False) # # # x represents our data # def forward(self, x): # x = F.relu(self.fc1(x)) # x = self.fc2(x) # # # Apply softmax to x # output = F.log_softmax(x, dim=1) # return output # # random_data = torch.rand(100, 4) # # print(random_data) # my_nn = Net() # print(my_nn) # result = my_nn(random_data) # print (result)
from django.conf import settings def insert_config(_): return { 'settings': { 'exponea_token': settings.EXPONEA_TOKEN, 'exponea_target': settings.EXPONEA_TARGET, 'registration_email': settings.REGISTRATION_PERSON_EMAIL, 'registration_name': settings.REGISTRATION_PERSON_NAME, 'registration_phone': settings.REGISTRATION_PERSON_PHONE, 'registration_year': settings.REGISTRATION_YEAR, }, }
""" Write a function: def solution(A, B, K) that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.: { i : A ≤ i ≤ B, i mod K = 0 } For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10. Assume that: A and B are integers within the range [0..2,000,000,000]; K is an integer within the range [1..2,000,000,000]; A ≤ B. Complexity: expected worst-case time complexity is O(1); expected worst-case space complexity is O(1). """ #Version 1 - Performance issue def solution(A, B, K): # write your code in Python 2.7 AB = range(A, B+1) solution = 0 for number in AB: if number % K == 0: solution += 1 return solution # Version 2 - 100% def solution(A, B, K): if B < A or K <= 0: raise Exception("Invalid Input") #Find 1st valid value bigger than A min_value = ((A + K -1) // K) * K if min_value > B: return 0 #If a min value within range is found #quantity of numbers that are divisible is # the quantity of divisible numbers within range + 1 to account for the min value return ((B - min_value) // K) + 1
""" 82. Remove Duplicates from Sorted List II Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: """ This will remove duplicates for any sorted/unsorted linked lists """ if not head: return None # find duplicates: duplicates = {} cur = head while cur: if cur.val in duplicates: duplicates[cur.val] += 1 else: duplicates[cur.val] = 1 cur = cur.next dummy_head = ListNode(-1) dummy_head.next = head prev = dummy_head cur = head while cur: if cur.val in duplicates and duplicates[cur.val] > 1: # duplicates - skip/remove cur node prev.next = cur.next else: prev = cur cur = cur.next return dummy_head.next def deleteDuplicates(self, head: ListNode) -> ListNode: """ This only works for sorted linked list """ if not head: return None dummy_head = ListNode(-1) dummy_head.next = head cur = dummy_head while cur.next and cur.next.next: # if encounter duplicates after current node if cur.next.val == cur.next.next.val: prev_val = cur.next.val while cur.next and cur.next.val == prev_val: # Keep skipping duplicates until find a new val cur.next = cur.next.next else: cur = cur.next return dummy_head.next
from alarm_handler import AlarmHandler alarmThread = AlarmHandler(src="alarm/alarm1.mp3") alarmThread.start()
from flask import Blueprint bp = Blueprint('notification', __name__)
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/31 21:45 # @Author : Yunhao Cao # @File : logger.py import logging __author__ = 'Yunhao Cao' __all__ = [ 'simple_config', 'config', 'debug', 'info', 'warning', 'error', ] def config(**kwargs): """ Configure logger. Detail reference -> logging - filename: output filename - level: output level for file. default:INFO - format: output format - datefmt: output time format - console_level: output level for console. Default=level :return: """ level = kwargs.get("level", logging.INFO) filename = kwargs.get("filename") fmt = kwargs.get("format") datefmt = kwargs.get("datefmt") # formatter = logging.Formatter(fmt, datefmt) logging.basicConfig(**{ "filename": filename, "level": level, "format": fmt, "datefmt": datefmt }) # sh = logging.StreamHandler(sys.stdout) # sh.setFormatter(formatter) # sh.setLevel(kwargs.get("console_level") or level) # logging.getLogger().addHandler(sh) # error solo file # if filename: # temp1 = filename.split('/') # temp2 = temp1[-1].split('.') # temp2[0] += "-err" # temp1[-1] = ".".join(temp2) # error_filename = "/".join(temp1) # # error FileHandler # error_fh = logging.FileHandler(error_filename) # error_fh.setFormatter(formatter) # error_fh.setLevel(logging.ERROR) # logging.getLogger().addHandler(error_fh) def simple_config(): config(**{ "filename": None, "level": logging.DEBUG, "format": "%(asctime)s [%(process)-4d] %(levelname)-8s : %(message)s", "datefmt": "[%Y-%m-%d %H:%M:%S]", }) simple_config() def debug(msg): logging.debug(msg) def info(msg): logging.info(msg) def warning(msg): logging.warning(msg) def error(msg): logging.error(msg) def _test(): simple_config() info('123') if __name__ == '__main__': _test()
import warnings from unittest.mock import sentinel import numpy as np import pandas as pd import pytest import osmo_camera.correction.flat_field as module def _replace_image_first_value(image, first_value): image_copy = np.copy(image) image_copy[0][0][0] = first_value return image_copy class TestFlatFieldDiagnostics: mock_before_image = np.array([[[1, 1, 0.1], [3, 4, 5]]]) @pytest.mark.parametrize( "expected_warnings_raised, after_image", [ ([], mock_before_image * 2), # All clear (["cv_increased"], _replace_image_first_value(mock_before_image, 1000)), (["nan_values_present"], np.ones(mock_before_image.shape) * np.nan), ], ) def test_warning_cases(self, expected_warnings_raised, after_image, mocker): mock_warn_if_any_true = mocker.patch.object(module, "warn_if_any_true") before = self.mock_before_image after = after_image # Numpy gets touchy when we throw around NaN values and such. # Quiet it down using this context manager: with np.errstate(invalid="ignore"): module.get_flat_field_diagnostics(before, after, mocker.sentinel.image_path) # Indexing: First arg in first call actual_warning_series = mock_warn_if_any_true.call_args[0][0] expected_warning_series = pd.Series( {"cv_increased": False, "nan_values_present": False} ) for warning_name in expected_warnings_raised: expected_warning_series[warning_name] = True pd.testing.assert_series_equal(expected_warning_series, actual_warning_series) def test_returns_reasonable_values(self): actual = module.get_flat_field_diagnostics( self.mock_before_image, self.mock_before_image * 2, sentinel.image_path ) actual_coefficient_of_variation = 0.7547445621912326 expected = pd.Series( { "cv_before": actual_coefficient_of_variation, "cv_after": actual_coefficient_of_variation, "flat_field_factor_max": 2, "flat_field_factor_min": 2, "nan_values_after": 0, "cv_increased": False, "nan_values_present": False, } ) pd.testing.assert_series_equal(actual, expected) class TestGuardFlatFieldShapeMatches: def test_raises_if_shape_does_not_match(self): with pytest.raises(ValueError): module._guard_flat_field_shape_matches( np.ones(shape=(1, 2, 3)), np.ones(shape=(4, 5, 6)) ) def test_does_not_raise_if_shape_matches(self): module._guard_flat_field_shape_matches( np.ones(shape=(1, 2, 3)), np.ones(shape=(1, 2, 3)) ) class TestFlatFieldCorrection: # Approximate an actual vignetting effect rgb_image = np.array( [ [[0.2, 0.2, 0.2], [0.3, 0.3, 0.3], [0.2, 0.2, 0]], [[0.4, 0.5, 0.6], [0.9, 1, 0.9], [0.6, 0.5, 0.4]], [[0.2, 0.2, 0.2], [0.7, 0.7, 0.7], [0.2, 0.2, 0]], ] ) # Approximate an actual flat field image flat_field_rgb = np.array( [ [[3, 3, 3], [0.9, 1, 2], [3, 3, 3]], [[1, 2, 0.9], [0.6, 0.6, 0.6], [0.9, 2, 1]], [[3, 3, 3], [2, 0.9, 1], [3, 3, 3]], ] ) expected_flat_field_corrected_rgb = np.array( [ [[0.6, 0.6, 0.6], [0.27, 0.3, 0.6], [0.6, 0.6, 0]], [[0.4, 1, 0.54], [0.54, 0.6, 0.54], [0.54, 1, 0.4]], [[0.6, 0.6, 0.6], [1.4, 0.63, 0.7], [0.6, 0.6, 0]], ] ) def test_apply_flat_field_correction_with_identity_returns_original_image(self): input_rgb = self.rgb_image actual = module.apply_flat_field_correction( input_rgb, flat_field_rgb=np.ones(shape=input_rgb.shape) ) np.testing.assert_array_equal(actual, input_rgb) def test_apply_flat_field_correction_multiplies(self): input_rgb = self.rgb_image actual = module.apply_flat_field_correction(input_rgb, self.flat_field_rgb) np.testing.assert_array_almost_equal( actual, self.expected_flat_field_corrected_rgb ) def test_load_flat_field_and_apply_correction(self, mocker): mocker.patch.object( module, "open_flat_field_image" ).return_value = self.flat_field_rgb actual = module.load_flat_field_and_apply_correction( self.rgb_image, sentinel.flat_field_filepath ) np.testing.assert_almost_equal(actual, self.expected_flat_field_corrected_rgb) def test_load_flat_field_and_apply_correction_raises_if_invalid_path(self): with pytest.raises(ValueError): module.load_flat_field_and_apply_correction( sentinel.rgb_image_series, flat_field_filepath_or_none="invalid.notnpy" ) def test_load_flat_field_and_apply_correction_no_ops_and_warns_if_missing_path( self, ): with warnings.catch_warnings(record=True) as _warnings: actual = module.load_flat_field_and_apply_correction( sentinel.rgb_image_series, flat_field_filepath_or_none=None ) # mypy thinks this could be None but it's not assert len(_warnings) == 1 # type: ignore assert actual == sentinel.rgb_image_series
from app.DAOs.MasterDAO import MasterDAO from psycopg2 import sql, errors class AuditDAO(MasterDAO): INSERTVALUE = 'Insert' UPDATEVALUE = 'Update' DELETEVALUE = 'Delete' TRANSACTIONTYPES = [INSERTVALUE, UPDATEVALUE, DELETEVALUE] USERTABLE = 'users' def getTableValueByIntID(self, table, pkeyname, pkeyval, cursor): """Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string representing the table name. :param pkeyname: string identifying the primary key's column name. :param pkeyval: representing the primary key's value. :param cursor: psycopg2 connection cursor. """ # If the table is Users, return all but the usub. # TODO: Verify this works after Diego's new table changes. if table == self.USERTABLE: query = sql.SQL("SELECT {fields} from {table} " "where {pkey} = %s;").format( fields=sql.SQL(',').join([ sql.Identifier('uid'), sql.Identifier('email'), sql.Identifier('display_name'), sql.Identifier('type'), sql.Identifier('roleid'), sql.Identifier('roleissuer') ]), table=sql.Identifier(str(table)), pkey=sql.Identifier(str(pkeyname))) else: query = sql.SQL("SELECT * from {table} " "where {pkey} = %s;").format( table=sql.Identifier(str(table)), pkey=sql.Identifier(str(pkeyname))) cursor.execute(query, (pkeyval,)) result = cursor.fetchone() return result def getTableValueByPkeyPair(self, table, pkeyname1, pkeyname2, pkeyval1, pkeyval2, cursor): """Get all values on a given table with a given primary key pair. TO BE USED INTERNALLY ONLY. :param table: string representing the table name. :param pkeyname1: string identifying the primary key's column name. :param pkeyname2: string identifying the primary key's column name. :param pkeyval1: primary key's value. :param pkeyval2: primary key's value. :param cursor: psycopg2 connection cursor. """ query = sql.SQL("SELECT * from {table} " "where {pkey1} = %s and {pkey2} = %s;").format( table=sql.Identifier(str(table)), pkey1=sql.Identifier(str(pkeyname1)), pkey2=sql.Identifier(str(pkeyname2))) cursor.execute(query, (pkeyval1, pkeyval2)) result = cursor.fetchone() return result def insertAuditEntry(self, changedTable, changeType, newValue, uid, cursor, oldValue=None,): """ Insert the received fields into the Audit table. :param changedTable: String designated the altered table. :param changeType: String designating the type of action. :param newValue: string representing the new value of the modified row. :param uid: User ID of user who made the action. :param cursor: psycopg2 connection cursor :param oldValue: Old value of row before alteration. """ # TODO: do better error raising. if changeType not in self.TRANSACTIONTYPES: raise ValueError("INSERT AUDIT ERROR: changeType not valid type: " + str(changeType)) if changeType != self.INSERTVALUE and not oldValue: raise ValueError("INSERT AUDIT ERROR: Not Insert and missing oldValue.") if not oldValue: oldValue="none" query = sql.SQL("Insert into audit({fields}) " "values(CURRENT_TIMESTAMP, %s, %s, %s, %s, %s);").format( fields=sql.SQL(',').join([ sql.Identifier('atime'), sql.Identifier('changedtable'), sql.Identifier('changetype'), sql.Identifier('oldvalue'), sql.Identifier('newvalue'), sql.Identifier('uid'), ])) cursor.execute(query, (str(changedTable).lower(), changeType, str(oldValue), str(newValue), int(uid))) return
from flask import jsonify from .template import * from .template.utils import get_value class Response: @classmethod def _jsonify(cls, **kwargs): return jsonify(dict(**kwargs)) @classmethod def raw(cls, code=0, **kwargs): assert isinstance(code, int), 'code should be a integer' return cls._jsonify(code=code, **kwargs) @classmethod def render(cls, template_, **kwargs): result = render(template_, **kwargs) if 'code' not in result: result['code'] = 0 return cls._jsonify(**result)
from datetime import datetime from django.test import TestCase, Client from django.urls import reverse, resolve from django.contrib.auth.models import User from ticketingsystem.views import * from ticketingsystem.models import * from ticketingsystem.forms import * # This class tests the URL routing gets resolved correctly class TestURLS(TestCase): def test_home_resolves(self): url = reverse('home') self.assertEquals(resolve(url).func, home) def test_dashboard_resolves(self): url = reverse('Dashboard') self.assertEquals(resolve(url).func, dashboard) def test_create_ticket_resolves(self): url = reverse('create-ticket') self.assertEquals(resolve(url).func, createTicket) def test_ticket_detail_resolves(self): url = reverse('Ticket_Detail', args=[1]) self.assertEquals(resolve(url).func, ticket_detail) def test_my_tickets_resolves(self): url = reverse('my-tickets') self.assertEquals(resolve(url).func, myTickets) def test_customer_list_resolves(self): url = reverse('Customer_List') self.assertEquals(resolve(url).func, customerList) def test_create_customer_resolves(self): url = reverse('create_customer') self.assertEquals(resolve(url).func, createCustomer) def test_stock_list_resolves(self): url = reverse('stock-list') self.assertEquals(resolve(url).func, stockList) def test_create_stock_resolves(self): url = reverse('create_stock') self.assertEquals(resolve(url).func, createStock) def test_stock_edit_resolves(self): url = reverse('stock_edit', args=[1]) self.assertEquals(resolve(url).func, editStock) # This class tests that the views are used correctly and the right template is rendered class testViews(TestCase): def setUp(self): self.client = Client() #creates a user for the testing user = User.objects.create_user(username = 'testUser', email = 'test@tester.com') user.set_password('hjok34ASDshuio*4') user.save() self.login = self.client.login(username = 'testUser', password = 'hjok34ASDshuio*4') #testCustomer created to create a test ticket testCustomer = Customer.objects.create(firstName = 'Tester', lastName = 'McTest', number = '07468524732', email = '', address = '') #test Ticket created to test ticket detail page testTicket = Ticket.objects.create(ticketName = 'HELP', deviceMake = 'HP', deviceModel = 'Tester', deviceType = 'Laptop', customer = testCustomer, assigned = user, ticketStatus = 'Open', ticketDescription = 'This is a test Ticket' ) #testStock created to test stock detail page testStock = inventoryItem.objects.create(itemName = 'Test Item', itemType = 'Tablet', quantityInStock = 1, price = 1.00, orderLink = '') self.homeURL = reverse('home') self.dashURL = reverse('Dashboard') self.ticketDetailURL = reverse('Ticket_Detail', args=[1]) self.createTicketURL = reverse('create-ticket') self.myticketsURL = reverse('my-tickets') self.customerListURL = reverse('Customer_List') self.createCustomerURL = reverse('create_customer') self.stockListURL = reverse('stock-list') self.createStockURL = reverse('create_stock') self.stockEditURL = reverse('stock_edit', args=[1]) def test_home_get(self): response = self.client.get(self.homeURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'home.html') def test_dashboard_GET(self): response = self.client.get(self.dashURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard.html') def test_ticketDetail_GET(self): response = self.client.get(self.ticketDetailURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ticket_detail.html') def test_create_ticket_GET(self): response = self.client.get(self.createTicketURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'create-ticket.html') def test_my_tickets_GET(self): response = self.client.get(self.myticketsURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'my_tickets.html') def test_customer_list_GET(self): response = self.client.get(self.customerListURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'customer_list.html') def test_create_customer_GET(self): response = self.client.get(self.createCustomerURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'create_customer.html') def test_stock_list_GET(self): response = self.client.get(self.stockListURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'stock_list.html') def test_create_stock_GET(self): response = self.client.get(self.createStockURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'create_stock.html') def test_stock_edit_GET(self): response = self.client.get(self.stockEditURL) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'stock_edit.html') # This class tests the model methods class testModels(TestCase): def setUp(self): self.client = Client() #creates a user for the testing user = User.objects.create_user(username = 'testUser', email = 'test@tester.com') user.set_password('hjok34ASDshuio*4') user.save() self.login = self.client.login(username = 'testUser', password = 'hjok34ASDshuio*4') #testCustomer created to create a test ticket testCustomer = Customer.objects.create(firstName = 'Tester', lastName = 'McTest', number = '07468524732', email = '', address = '') #test Ticket created to test ticket detail page testTicket = Ticket.objects.create(ticketName = 'HELP', deviceMake = 'HP', deviceModel = 'Tester', deviceType = 'Laptop', customer = testCustomer, assigned = user, ticketStatus = 'Open', ticketDescription = 'This is a test Ticket' ) #testStock created to test stock detail page testStock = inventoryItem.objects.create(itemName = 'Test Item', itemType = 'Tablet', quantityInStock = 1, price = 1.00, orderLink = '') def testCustomerModel(self): newtestCustomer = Customer.objects.create(firstName = 'Testy', lastName = 'McTest', number = '07468524732', email = '', address = '') #tests the __str__ method self.assertEqual(str(newtestCustomer),'Testy McTest') def testTicketModel(self): testCustomer = Customer.objects.create(firstName = 'Tester', lastName = 'McTest', number = '07468524732', email = '', address = '') user = User.objects.get(id=1) testTicket = Ticket.objects.create(ticketName = 'HELP ME', deviceMake = 'HP', deviceModel = 'Tester', deviceType = 'Laptop', customer = testCustomer, assigned = user, ticketStatus = 'Open', ticketDescription = 'This is a test Ticket' ) #tests the __str__ method self.assertEqual(str(testTicket),'HELP ME') #test the get assigned method self.assertEqual(testTicket.assigned, user) def testInventoryModel(self): testStock = inventoryItem.objects.create(itemName = 'Test Item', itemType = 'Tablet', quantityInStock = 1, price = 1.00, orderLink = '') #tests the __str__ method self.assertEqual(str(testStock),'Test Item(Tablet)') ''' FORM METHOD UNIT TESTS BELOW ''' #This class tests the customer form's validation class testCustomerModelForm(TestCase): def testValidData(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '07468524732', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertTrue(form.is_valid()) #Test No Data provided def testNoData(self): form = customerForm(data = { }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 3) def testFirstNameRequired(self): form = customerForm(data = { 'firstName': '', 'lastName': 'Test', 'number' : '07468524732', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testFirstNameLength(self): form = customerForm(data = { 'firstName': 'MyNameIsJohnBrownIHavemorethanahundredcharactersinmynamewhichshouldtriggerthelengthofthistesthopefully', 'lastName': 'Test', 'number' : '07468524732', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testLastNameRequired(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': '', 'number' : '07468524732', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testLastNameLength(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'MyNameIsJohnBrownIHavemorethanahundredcharactersinmynamewhichshouldtriggerthelengthofthistesthopefully', 'number' : '07468524732', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testNumberRequired(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testNumberLengthLong(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '15150151051510500150', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testNumberLengthShort(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '0154510', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) def testLettersInNumber(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '023926138H5', 'email' : 'test@tester.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) #Test Email def testNoEmail(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '07468524732', 'email' : '', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertTrue(form.is_valid()) def testEmailFormat(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '07468524732', 'email' : 'hello', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) def testEmailLength(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '07468524732', 'email' : 'thisissuperlongemailthatismorethan254characterstotessdasdasdasdasdasdasdasdasdtheemaillengththisissuperlongemailthatismorethan254characterstotestheemaillengththisissuperlongemailthatismorethan254characterstotestheemaillength@testercodedemailneedingtobemorethan254characters.com', 'address' : '123 fake street, Portsmouth, PO1 1NL' }) self.assertFalse(form.is_valid()) #Test blank address def testNoAddress(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '07468524732', 'email' : 'test@tester.com', 'address' : '' }) self.assertTrue(form.is_valid()) def testNoEmailORAddress(self): form = customerForm(data = { 'firstName': 'Test', 'lastName': 'Test', 'number' : '07468524732', 'email' : '', 'address' : '' }) self.assertTrue(form.is_valid()) #This class tests the Ticket form's validation class testTicketModelForm(TestCase): def setUp(self): self.client = Client() #creates a user to act as the technician assigned / ticket creator user = User.objects.create_user(username = 'testUser', email = 'test@tester.com') user.set_password('hjok34ASDshuio*4') user.save() self.login = self.client.login(username = 'testUser', password = 'hjok34ASDshuio*4') #testCustomer created to customer for the test ticket testCustomer = Customer.objects.create(firstName = 'Tester', lastName = 'McTest', number = '07468524732', email = '', address = '') def testValidData(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test Ticket', 'deviceMake': 'HP', 'deviceModel' : 'Test Mark 2', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertTrue(form.is_valid()) def testnoData(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { }) self.assertFalse(form.is_valid()) def testNameRequired(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': '', 'deviceMake': 'HP', 'deviceModel' : 'Test Mark 2', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testNameLength(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Help me my computer has caught fire and I dont think it works any more, also please help me please now please I really need this computer to work!!', 'deviceMake': 'HP', 'deviceModel' : 'Test Mark 2', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testDeviceMakeRequired(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': '', 'deviceModel' : 'Test Mark 2', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testDeviceMakeLength(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'Super Mega Awesome Company with super leet skills building computer hardware yo', 'deviceModel' : 'Test Mark 2', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testDeviceModelRequired(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : '', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testDeviceModelLength(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Super Cool Awesome Mega Fantastic Fast Computer that is totally real', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testDeviceTypeRequired(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Test', 'deviceType' : '', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testDeviceTypeNonOption(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Test', 'deviceType' : 'Awesome', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testNoCustomer(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Test', 'deviceType' : 'Tablet', 'customer' : '', 'assigned' : user, 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testNoTechnicianAssigned(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Omen', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : '', 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertTrue(form.is_valid()) # Whilst Null is allowed in the Technician Model, Null shouldn't be a valid option within the form. This test checks that. def testNULLTechnicianAssigned(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Omen', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : 'NULL', 'ticketStatus' : 'Open', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testNonStatusOption(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Omen', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Awesome', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testNoStatusProvided(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Omen', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : '', 'ticketDescription' : 'Help me' }) self.assertFalse(form.is_valid()) def testStatusLength(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Omen', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Waiting on Customer', 'ticketDescription' : 'Help me' }) self.assertTrue(form.is_valid()) def testDescriptionRequired(self): user = User.objects.get(id=1) customer = Customer.objects.get(id=1) form = ticketForm(data = { 'ticketName': 'Test', 'deviceMake': 'HP', 'deviceModel' : 'Omen', 'deviceType' : 'Tablet', 'customer' : customer, 'assigned' : user, 'ticketStatus' : 'Waiting on Customer', 'ticketDescription' : '' }) self.assertFalse(form.is_valid()) #This class tests the Inventory form's validation class testInventoryModelForm(TestCase): def testValidData(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertTrue(form.is_valid()) def testNoData(self): form = inventoryForm(data = { }) self.assertFalse(form.is_valid()) def testNameRequired(self): form = inventoryForm(data = { 'itemName': '', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testNameLength(self): form = inventoryForm(data = { 'itemName': 'super coool mega awesome item of awesomeness you would never believe how good this item is really it will blown your freaking mind how cool it is really it is so cool that people would would pay billions and billions of pounds for it', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testNoType(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': '', 'quantityInStock' : 1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testNonTypeSelected(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Cool Thing', 'quantityInStock' : 1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testlongestType(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Mobile Phone', 'quantityInStock' : 1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertTrue(form.is_valid()) def testNegativeQuantity(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : -1, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testZeroQuantity(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 0, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertTrue(form.is_valid()) def testLargeQuantity(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 100000000000000, 'price' : 1.99, 'orderLink' : 'http://www.google.com', }) self.assertTrue(form.is_valid()) def testNegativePrice(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : -1.99, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testPriceWithMoreDecimalPlaces(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.01516513150, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testBigPrice(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 999999999999999.00, 'orderLink' : 'http://www.google.com', }) self.assertFalse(form.is_valid()) def testOrderLinkNotRequired(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 999999999999999.00, 'orderLink' : '', }) self.assertFalse(form.is_valid()) def testLinkStructure(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 999999999999999.00, 'orderLink' : 'hello', }) self.assertFalse(form.is_valid()) def testhttpsLink(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.00, 'orderLink' : 'https://www.google.com', }) self.assertTrue(form.is_valid()) def testNewDomains(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.00, 'orderLink' : 'http://www.get.shop', }) self.assertTrue(form.is_valid()) def testNonURL(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.00, 'orderLink' : 'test', }) self.assertFalse(form.is_valid()) def testNoHTMLURL(self): form = inventoryForm(data = { 'itemName': 'Test Item', 'itemType': 'Tablet', 'quantityInStock' : 1, 'price' : 1.00, 'orderLink' : 'www.google.com', }) self.assertTrue(form.is_valid())
#! /usr/bin/env python3.3 try: filename = "../doc/cs296_report_06.tex" inFile = open(filename) except OSError: print("Report not found") else: def WriteHeading(heading, no, outFile): outFile.write("<h" + str(no) + " style=\"font-family: sans-serif, monospace; font-weight:Bold;\">") outFile.write(Heading) outFile.write("</h" + str(no) + ">\n") def addImage(no, outFile): if '1' in no or '2' in no or '3' in no or '4' in no or '5' in no: no = no.replace('k','m') outFile.write("<img src=\""+ str(no) + "\" alt=\"plot" + str(no) + "\" height=\"50%\" width=\"52%\">\n") subsection = "\subsection{" section = "\section{" incG = "\includegraphics" Heading = "" outFile = open("../doc/g06_report.html", "w") Start = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n\"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<title>" outFile.write(Start) while True: l = inFile.readline() lLow = l.lower() if '\\title' == l[0:6]: title = l[l.find("{") + 1:l.find("}")].replace('\\\\','<br>') outFile.write(title) break while True: l = inFile.readline() lLow = l.lower() if "pagebreak" in lLow: break outFile.write("</title>\n<style type=\"text/css\">\nbody {margin-left: 10%; margin-right: 10%; color: black; background: white; font-family: monospace;} \n </style>\n</head>\n<body>\n") WriteHeading(Heading, 1, outFile) outFile.write("<br><br>\n") flag = False while True: l = inFile.readline() lLow = l.lower() if "bibliographystyle" in lLow: break if subsection in lLow: if flag: outFile.write("</p>\n") sInd = lLow.find(subsection) + 12 eInd = lLow.find("}") Heading = l[sInd:eInd] WriteHeading(Heading, 2, outFile) outFile.write("<p>") flag = True elif section in lLow: if flag: outFile.write("</p>\n") sInd = lLow.find(section) + 9 eInd = lLow.find("}") Heading = l[sInd:eInd] WriteHeading(Heading, 2, outFile) outFile.write("<p>") flag = True elif incG in l: sInd = lLow.find("{") + 1 eInd = lLow.find("}") imgF = l[sInd:eInd] addImage(imgF, outFile) else: if "\\\\" in lLow: l = l.replace("\\\\","<br>").replace("\\cite{","").replace("}","") lLow = l.lower() outFile.write(l) outFile.write("</body>\n")
import sys import glob from flask import request, send_file from flask_restful import Resource, reqparse, fields, marshal from werkzeug.utils import secure_filename from common.auth import authenticate, get_user from models import db from models import File as F import os import uuid from pathlib import Path ALLOWED_EXTENSIONS = {'gif', 'png', 'jpg', 'jpeg', 'mp4', 'mp3', 'webm'} FILE_DIR = "files/" SAVE_DIR = os.path.join(os.path.dirname(__file__) + '/../' + FILE_DIR) def allowed_file(filename: str) -> bool: return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS file_fields = { 'id': fields.String, 'filename': fields.String, 'user': fields.String, 'extension': fields.String } class File(Resource): # Protected endpoint method_decorators = [authenticate] # Upload def post(self, user): if 'file' not in request.files: return {'error': 'Required field file'}, 400 file = request.files['file'] if file.filename == '': return {'error', 'file is empty'}, 400 if not allowed_file(file.filename): return {'error': 'file extension not allowed'}, 400 # Create subdirectory if not exist Path(SAVE_DIR + user.username).mkdir(parents=True, exist_ok=True) # Saving file into files/ folder filename = secure_filename(file.filename) file.save(SAVE_DIR + user.username + '/' + filename) # Create object File index = filename.rindex('.') extension = filename[index + 1:] new_file = F(id=uuid.uuid4().hex, user_id=user.id, filename=filename, user=user.username, extension=extension) # Commit object in database db.session.add(new_file) db.session.commit() return {} # Get def get(self, user): all_files = user.files for i in user.friends: all_files += i.files return marshal(all_files, file_fields) class FileManager(Resource): # Protected endpoint for delete method method_decorators = {'delete': [authenticate]} def get(self, filename): token = request.args.get('token') user = get_user(token) # Check if the user can access to the file all_files = user.files for i in user.friends: all_files += i.files all_id = [] for i in all_files: all_id.append(i.id) if filename not in all_id: return {'error': 'You don\'t have access to the required file'}, 400 # Get file object from filename f = None for i in all_files: if i.id == filename: f = i # Return file data filename = SAVE_DIR + f.user + '/' + f.filename return send_file(filename, mimetype=f.extension) def delete(self, user, filename): # Get File object f = None for i in user.files: if i.id == filename: f = i # Error handler if f is None: return {'error': 'file not found'}, 400 # Remove and commit changes db.session.delete(f) db.session.commit() return {}
import os import json import torch # VICTIMS_LINE_STYLES = {'DPN92', 'SENet18', 'ResNet50', 'ResNeXt29_2x64d', 'GoogLeNet', # 'MobileNetV2', 'ResNet18', 'DenseNet121'} VICTIMS_COLORS = {'DPN92': 'saddlebrown', 'SENet18': 'gray', 'ResNet50': 'seagreen', 'ResNeXt29_2x64d': 'violet', 'GoogLeNet': 'blue', 'MobileNetV2': 'gold', 'ResNet18': 'crimson', 'DenseNet121': 'cyan'} VICTIMS_LINESTYLES = {'DPN92': 'solid', 'SENet18': 'solid', 'ResNet50': 'solid', 'ResNeXt29_2x64d': 'solid', 'GoogLeNet': 'solid', 'MobileNetV2': 'solid', 'ResNet18': 'dashed', 'DenseNet121': 'dashed'} METHODS_LINESTYLES = {'mean': 'dashed', 'convex': 'solid', 'mean-3': 'dashdot', 'mean-5': 'dotted'} METHODS_NAMES = {'mean': 'BP', 'convex': 'CP', 'mean-3': 'BP-3x', 'mean-5': 'BP-5x'} METHODS_COLORS = {'mean': 'crimson', 'convex': 'gray', 'mean-3': 'darkcyan', 'mean-5': 'saddlebrown'} def read_all_in_dir(poisons_root_path, retrain_epochs, target_num): filename = 'eval-retrained-for-{}epochs.json'.format(retrain_epochs) all_res = {'targets': {}} for root, _, files in os.walk(poisons_root_path): for f in files: if f == filename: f = os.path.join(root, f) if 'target-num-{}/'.format(target_num) in f: # print("reading {}".format(f)) with open(f) as resf: res = json.load(resf) poison_label = res['poison_label'] target_label = res['target_label'] assert len(res['targets']) target_id = list(res['targets'].keys())[0] all_res['poison_label'] = poison_label all_res['target_label'] = target_label all_res['targets'][target_id] = res['targets'][target_id] return all_res def read_attack_stats(poisons_root_path, retrain_epochs, target_num): all_res = read_all_in_dir(poisons_root_path, retrain_epochs, target_num) if len(all_res['targets']) == 0: print("Nothing found in {} when target_num is set to {}".format(poisons_root_path, target_num)) assert "2000" in poisons_root_path print("path {} replaced by".format(poisons_root_path)) poisons_root_path = poisons_root_path.replace("2000", "1000") print(poisons_root_path) assert os.path.exists(poisons_root_path) all_res = read_all_in_dir(poisons_root_path, retrain_epochs, target_num) # assert len(all_res['targets']) == 14 return all_res def fetch_poison_bases(poison_label, num_poison, subset, path, transforms): """ Only going to fetch the first num_poison image as the base class from the poison_label class """ img_label_list = torch.load(path)[subset] base_tensor_list, base_idx_list = [], [] for idx, (img, label) in enumerate(img_label_list): if label == poison_label: base_tensor_list.append(transforms(img)) base_idx_list.append(idx) if len(base_tensor_list) == num_poison: break return base_tensor_list, base_idx_list
#!/usr/bin/python # -*- coding: utf-8 -*- import requests import json import re class Email_SMTP: def __init__(self, ip): self.request = {'params': {'overwrite': 'false', 'args': ' ', 'method': ' '}, 'type': 'alertmanager'} self.headers = {'Content-Type': 'application/json'} self.addr = 'https://' + ip + ':8446/ascws/jobmanager/job' def add_smtp_server(self, server, username, password): request = dict(self.request) value = ' '.join([server, username, password]) request['params']['args'] = value request['params']['method'] = 'asmtp' data = json.dumps(request) response = requests.post(self.addr, data=data, headers=self.headers, verify=False) return response.json() def add_interval(self, interval): request = dict(self.request) value = interval request['params']['args'] = value request['params']['method'] = 'interval' data = json.dumps(request) response = requests.post(self.addr, data=data, headers=self.headers, verify=False) return response.json() def add_sender(self, sender): request = dict(self.request) value = sender request['params']['args'] = value request['params']['method'] = 'asemail' data = json.dumps(request) response = requests.post(self.addr, data=data, headers=self.headers, verify=False) return response.json() def add_hadmin(self, admin): request = dict(self.request) value = admin request['params']['args'] = value request['params']['method'] = 'aemail' data = json.dumps(request) response = requests.post(self.addr, data=data, headers=self.headers, verify=False) return response.json() def delete_hadmin(self, admin): request = dict(self.request) value = admin request['params']['args'] = value request['params']['method'] = 'demail' data = json.dumps(request) response = requests.post(self.addr, data=data, headers=self.headers, verify=False) return response.json()
def ask(question, answers, default_answer, type_validator=str): """Ask question to user via console. :param question: [str] The question to ask. :param answers: [list of str, str] The possible answers to choose from. If '' (empty string), then no answer will be suggested. :param default_answer: [str or numeric] The default answer for when the user replies by pressing Enter. If '' (empty string), nothing will happen when user hits Enter. :param type_validator: Validate answer. Useful for when the user shall input an int, for instance, and replies with a float. Examples are str, float, int (no quotes, this is the class itself). :return user_answer: What the user has typed, validated according to type_validator. Note that this function does not raise Exceptions when user input cannot be validated or answer is not included among default ones. It keeps trying until user inputs a valid answer. """ # Get number of answers if not isinstance(answers, list): answers = [answers] if answers[0] == '': n_answers = 0 else: n_answers = len(answers) # Append answer hints to question if n_answers > 0 or str(default_answer) != '': question_to_show = question + ' (' if str(default_answer) != '': question_to_show += '[%s]' % str(default_answer) if n_answers > 0: question_to_show += '/' if n_answers > 0: question_to_show += '%s' % '/'.join([i for i in answers if str(i) != str(default_answer)]) question_to_show += ')' else: question_to_show = question # Ask user for an answer while True: user_answer = input(question_to_show) # Set default option when user presses Enter if user_answer == '': if str(default_answer) == '': print('Please try again') else: user_answer = default_answer # Validate user answer try: user_answer = type_validator(user_answer) except ValueError: print('Answer type not allowed. Reply something that can be converted to \'%s\'' % repr(type_validator)) continue # Stop if got an answer that is allowed, or if there are no good answers if user_answer in answers or n_answers == 0: break else: print('Please try again') return user_answer
import numpy as np from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import cross_val_score def load(filename): print('Loading 2008 Training data...', end='') f = open(filename, 'rb') data = np.loadtxt(f, dtype='float', delimiter=',', skiprows=1) f.close() X, y = data[:, 1:-1], data[:, -1] X = np.asarray(X) y = y.astype('int') print('DONE') return X, y X, y = load('./data/train_2008.csv') clf = GradientBoostingClassifier(n_estimators=100, subsample=0.9, max_depth=7, max_features=50, verbose=1) scores = cross_val_score(clf, X, y, cv=3) print(scores) print(np.average(scores))
for i in range (10): print(i) print('Hi')
import numpy as np import matplotlib.pyplot as plt import csv index_collumn = [] size_collumn = [] with open('dbsize.txt') as csvfile: csvfilereader = csv.reader(csvfile, delimiter=' ') for line in csvfilereader: index_collumn.append(int(line[0])) size_collumn.append(int(line[1])) print(size_collumn[:2]) figure_length = 300 plt.plot(index_collumn[:figure_length], size_collumn[:figure_length], label="observed size") # print(np.arange(int(min(index_collumn[:figure_length])), int(max(index_collumn[:figure_length]))+1, 20.0)) plt.xticks(np.arange(int(min(index_collumn[:figure_length])), int(max(index_collumn[:figure_length]))+1, 50.0)) plt.xlabel('Blocks Used') plt.ylabel('Database Size') plt.plot(index_collumn[:figure_length], (np.array(index_collumn[:figure_length])*323)+20480, label="(blocks*323)+20480") plt.title("Database Size Scaling") plt.legend() plt.show(block=True)
def test_wait_more_30_sec(desktop_app_auth): desktop_app_auth.navigate_to('Demo pages') desktop_app_auth.demo_pages.open_page_after_wait(32) assert desktop_app_auth.demo_pages.check_wait_page() def test_ajax(desktop_app_auth): desktop_app_auth.navigate_to('Demo pages') desktop_app_auth.demo_pages.open_page_and_wait_ajax(6) assert 6 == desktop_app_auth.demo_pages.get_ajax_responses_count()
import unittest import LowestCommonAncestor as lca class LowestCommonAncestorTest(unittest.TestCase): # tree functions # 0 # / \ # 1 2 # / \ / \ # 3 4 5 6 def testTree(self): tree = lca.LowestCommonAncestor.binaryTree() # empty tree assert tree.getKey(tree.head) == -1 # head tree.add(0, None, True) assert tree.getKey(tree.head) == 0 # children of the head tree.add(1, tree.head, True) tree.add(2, tree.head, False) assert tree.getKey(tree.head.lChild) == 1 assert tree.getKey(tree.head.rChild) == 2 # children of the children of the head tree.add(3, tree.head.lChild, True) tree.add(4, tree.head.lChild, False) tree.add(5, tree.head.rChild, True) tree.add(6, tree.head.rChild, False) assert tree.getKey(tree.head.lChild.lChild) == 3 assert tree.getKey(tree.head.lChild.rChild) == 4 assert tree.getKey(tree.head.rChild.lChild) == 5 assert tree.getKey(tree.head.rChild.rChild) == 6 # valid LCA # 0 # / \ # 1 2 # / \ / \ # 3 4 5 6 def testLCA(self): tree = lca.LowestCommonAncestor.binaryTree() tree.add(0, None, True) tree.add(1, tree.head, True) tree.add(2, tree.head, False) tree.add(3, tree.head.lChild, True) tree.add(4, tree.head.lChild, False) tree.add(5, tree.head.rChild, True) tree.add(6, tree.head.rChild, False) # LCA of 0 and 0 assert lca.LowestCommonAncestor.getLCA(tree, tree.head, tree.head) == 0 # LCA of 1 and 2 assert lca.LowestCommonAncestor.getLCA(tree, tree.head.lChild, tree.head.rChild) == 0 # LCA of 1 and 6 assert lca.LowestCommonAncestor.getLCA(tree, tree.head.lChild, tree.head.rChild.rChild) == 0 # LCA of 3 and 6 assert lca.LowestCommonAncestor.getLCA(tree, tree.head.lChild.lChild, tree.head.rChild.rChild) == 0 # LCA of 1 and 4 assert lca.LowestCommonAncestor.getLCA(tree, tree.head.lChild, tree.head.lChild.rChild) == 1 # LCA of 3 and 4 assert lca.LowestCommonAncestor.getLCA(tree, tree.head.lChild.lChild, tree.head.lChild.rChild) == 1 # invalid LCA # 0 # / \ # 1 2 # / \ / \ # 3 4 5 6 def testInvalid(self): tree = lca.LowestCommonAncestor.binaryTree() tree.add(0, None, True) tree.add(1, tree.head, True) tree.add(2, tree.head, False) tree.add(3, tree.head.lChild, True) tree.add(4, tree.head.lChild, False) tree.add(5, tree.head.rChild, True) tree.add(6, tree.head.rChild, False) # LCA of 0 and an empty node assert lca.LowestCommonAncestor.getLCA(tree, tree.head, None) == -1 # LCA of two empty nodes assert lca.LowestCommonAncestor.getLCA(tree, None, None) == -1 if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['CategoryTestCase::test_can_fetch_all_interests 1'] = { 'data': { 'interestsList': { 'edges': [ { 'node': { 'followerCategory': { 'id': 'Q2F0ZWdvcnlOb2RlOjE=', 'name': 'Gaming Meetup' }, 'id': 'SW50ZXJlc3ROb2RlOjQy' } }, { 'node': { 'followerCategory': { 'id': 'Q2F0ZWdvcnlOb2RlOjI=', 'name': 'Python Meetup' }, 'id': 'SW50ZXJlc3ROb2RlOjQx' } }, { 'node': { 'followerCategory': { 'id': 'Q2F0ZWdvcnlOb2RlOjE=', 'name': 'Gaming Meetup' }, 'id': 'SW50ZXJlc3ROb2RlOjQw' } } ] } } }
import cProfile import datetime import enum import json import logging import os import random import re import time class SetType(enum.Enum): """ Types of set, i.e. training set """ ALL = "all" QUERY = "query" TEST = "test" TRAIN = "train" def get_session(gpu_fraction=0.3): import tensorflow as tf # Shadow import for testing """ Helper function to ensure that Keras only uses some fraction of the memory Args: gpu_fraction: Fraction of the GPU memory to use Returns: A tensorflow session to be passed into tensorflow_backend.set_session """ num_threads = os.environ.get('OMP_NUM_THREADS') gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction) if num_threads: return tf.Session(config=tf.ConfigProto( gpu_options=gpu_options, intra_op_parallelism_threads=num_threads)) else: return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) def setup_custom_logger(name): """ Setup a custom logger that will output to the console """ logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create a console handler console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logger.addHandler(console_handler) # create a file handler file_handler = logging.FileHandler("./log_{}".format(name)) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger def get_index_of_tuple(list_of_tuple, index_of_tuple, value): """ Determine how far through the list to find the value. If the value does not exist in the list, then return the length of the list. Args: list_of_tuple: a list of tuples i.e. [(index1, index2, index3)] index_of_tuple_1: which index in the tuple you want to compare the value to value: the value to search Return: the number of items in the list it has compared """ for index_of_list, tupl in enumerate(list_of_tuple): if tupl[index_of_tuple] == value: return index_of_list + 1 # could not find value in list_of_tuple, so return length of tuple return len(list_of_tuple) def get_index_of_pairs(list_of_tuple, index_of_tuple_1, index_of_tuple_2, value): """ Determine how far through the list to find the value. If the value does not exist in the list, then return the length of the list. Args: list_of_tuple: a list of tuples i.e. [(index1, index2, index3)] index_of_tuple_1: which index in the tuple you want to compare the value to index_of_tuple_2: which index in the tuple you want to compare the value to value: the value to search Return: the number of items in the list it has compared """ for index_of_list, tupl in enumerate(list_of_tuple): if tupl[index_of_tuple_1] == value and tupl[index_of_tuple_2] == value: return index_of_list + 1 # could not find value in list_of_tuple, so return length of tuple return len(list_of_tuple) def get_basename(string): """ Extract the basename from the filepath. Args: filepath in the format of a string Args: filename in the format of a string """ return os.path.basename(os.path.normpath(string)) def get_numeric(string): """ Extract the numeric value in a string. Args: string Returns: a string with only the numeric value extracted """ return re.sub('[^0-9]', '', string) def get_timestamp(timestamp): """ Convert datetime object into a string in the format of Year-Month-Date Hour:Minute:Second Args: datetime Returns: string in the format of Year-Month-Date Hour:Minute:Second """ return timestamp.strftime("%Y-%m-%d %H:%M:%S") if isinstance(type(timestamp), datetime.datetime) else timestamp def should_drop(drop_percentage): """ Based on the given percentage, provide an answer whether or not to drop the image. Args: drop_percentage: the likelihood of a drop in the form of a float from [0,1] Returns: a boolean whether to drop or not drop the image """ return random.random() < drop_percentage def read_json(filepath): """ Assuming the json file contains a dictionary per line, read the json file and create a generator that yields each dictionary per line. Args: filepath: path to the json file Returns: a generator that yields dictionary line by line """ with open(filepath) as file: for line in file: yield json.loads(line) def remove_file(filename): """ Assuming the filename exists where the application is run, remove the file. Args: filename Returns: filename is removed """ try: os.remove(filename) except OSError: pass def timewrapper(func): """ This is a decorator to calculate how fast each operation takes. Args: func: function pointer args: arguments to the function kwargs: named arguments not defined in advance to be passed in to the function """ def timer(*args, **kwargs): start = time.time() result = func(*args, **kwargs) elapsed = time.time() - start print("{} took {} seconds".format(func.__name__, elapsed)) return result return timer def profilewrapper(func): """ This is a decorator to profile a function. Args: func: function pointer args: arguments to the function kwargs: named arguments not defined in advance to be passed in to the function """ def profiler(*args, **kwargs): profile = cProfile.Profile() try: profile.enable() result = func(*args, **kwargs) profile.disable() return result finally: profile.print_stats() return profiler def get_split(key, pivots): if not isinstance(pivots, list): pivots = list(pivots) pivots.sort() hash_val = hash(key)%100 for split, pivot in enumerate(pivots): if hash_val < pivot: return split return len(pivots) def train_test_key_filter(key, split="train"): hash_val = get_split(key, [90]) split = split.lower() if split == "train": desired_val = 0 elif split == "test": desired_val = 1 else: raise ValueError('Unknown Split Type: %s'%split) if hash_val == desired_val: return True else: return False
import networkx as nx import newt import csv,random def directedNetworkFromGDF(filename): f=open(filename,'rb') reader = csv.reader(f) print "Loading graph..." phase='nodes' header=reader.next() DG=nx.DiGraph() print "Loading nodes..." for row in reader: if row[0].startswith('edgedef>'): phase='edges' print "Moving on to edges" continue elif phase=='edges': fromNode=row[0].strip() toNode=row[1].strip() #print ':'.join(['Adding edge',fromNode,toNode]) DG.add_edge(fromNode,toNode) else: id=row[0].strip() val=row[1].strip() #print ':'.join(['Adding node',id,val]) if id!='' and val!='': DG.add_node(id,label=val) f.close() return DG def labelGraph(api,LG,idlist=None): if idlist==None: idlist=LG.nodes() idlabels=newt.twNamesFromIds(api,idlist) for id in idlabels: if str(id) in LG.node: LG.node[str(id)]['label']=idlabels[id] return LG def createTwitterFnet(api,user,typ='friends',samplesize='all'): DG=nx.DiGraph() userDet=api.get_user(user) userID=userDet.id if typ is 'friends': try: members=api.friends_ids(user) except: members=[] if samplesize !='all' and samplesize<len(members): members=random.sample(members, samplesize) fedges=[(str(userID),str(u)) for u in members] DG.add_edges_from(fedges) else: try: members=api.followers_ids(user) except: members=[] if samplesize !='all' and samplesize<len(members): members=random.sample(members, samplesize) fedges=[(str(u),str(userID)) for u in members] DG.add_edges_from(fedges) return DG def progressPrint(u,fetchlen,i): i=i+1 print 'getting data for',u,str(i),'of',fetchlen return i #-----CRIB http://www.drewconway.com/zia/?p=345 def snowball_search(network,api,cur_round=1): users=nodes_at_degree(network,cur_round) # Get all the users at the current round degree fetchlen=len(users) i=0 for u in users: i=progressPrint(u,fetchlen,i) search_results=createTwitterFnet(api,u) network=nx.compose(network,search_results) return network def nodes_at_degree(network,degree): # Get nodes to perform round k search on d=network.degree() d=d.items() return [(a) for (a,b) in d if b==degree] #---END CRIB def mergeNets(net1,net2): return nx.compose(net1,net2)
import math import random import matplotlib.pyplot as plt import numpy as np from scipy import special class Filter(object): def __init__(self, dpass=250, e=1, n=6): self._dpass = dpass self._e = e self._n = n def set_dpass(self, dpass): self._dpass = dpass def butterworth(self, distance): r = float(distance)/float(self._dpass) rp = math.pow(r, self._n) result = 1.0 / math.sqrt(1.0 + self._e * rp) return result def run(self, distance): return self.butterworth(distance) def get_factor(busses_per_hour, dpass): interval = 60.0 / float(busses_per_hour) filter = Filter(dpass = dpass) total = 0.0 if dpass == 1: runs = 1000000 else: runs = 100000 for i in xrange(runs): wait_time = random.randint(0, int(100.0 * interval)) / 100.0 factor = filter.butterworth(wait_time) total += factor # print wait_time, factor average = total/float(runs) return average def normalize(data): d = np.array(data) m_val = np.max(d) return d/m_val def wait_decay(per_hour, dpass): """ Compute the area under butterworth filter with x=1 and n=6 """ d = 60.0 / per_hour d2 = math.pow(d, 2) d4 = math.pow(d, 4) d6 = math.pow(d, 6) dpass2 = math.pow(dpass, 2) dpass4 = math.pow(dpass, 4) dpass6 = math.pow(dpass, 6) sqrt3 = math.sqrt(3.0) m = (sqrt3 + 2.0) / 4.0 cos_top = dpass2 - (sqrt3 - 1.0) * d2 cos_bottom = (1.0 + sqrt3) * d2 + dpass2 x = math.acos(cos_top/cos_bottom) elip = special.ellipkinc(x, m) top1 = d4 - dpass2 * d2 + dpass4 bottom1 = (1.0 + sqrt3) * d2 + dpass2 bottom1 = math.pow(bottom1, 2.0) part = math.sqrt(top1/bottom1) top = 5.0 * math.pow(3.0, 0.75) * d * (d2 + dpass2) * part * elip top2 = d2 * (d2 + dpass2) bottom2 = (1.0 + sqrt3) * d2 + dpass2 bottom2 = math.pow(bottom2, 2.0) part2 = 2.0 * math.sqrt(top2/bottom2) bottom = part2 * math.sqrt(d6 + dpass6) final_area = top / bottom result = final_area / d return result def plot_butterworth_wait(): wait_time = np.array(range(0, 600), dtype=np.float) wait_time /= 10.0 fig, ax = plt.subplots(figsize=(10, 6)) filter = Filter() mb = [1, 2, 5, 10, 15, 20, 30, 45, 60] for m in mb: result = [] filter.set_dpass(m) for t in wait_time: decay = filter.butterworth(t) result.append(decay) line2, = ax.plot(wait_time, result, label="mb: %d mins" % m) ax.legend(loc='upper right') plt.title("Decay vs. Wait Time (minutes)") plt.ylabel("Decay Value") plt.xlabel("Wait Time (minutes)") plt.subplots_adjust(left=0.1, right=.9, top=0.9, bottom=0.1) plt.show() def plot_butterworth(dpass): d = np.array(range(0, 500), dtype=np.float) filter = Filter(dpass=dpass) result = [] for dist in d: decay = filter.butterworth(dist) result.append(decay) fig, ax = plt.subplots(figsize=(10, 6)) line2, = ax.plot(d, result, label="dpass = 250 meters") ax.legend(loc='lower left') plt.title("Decay vs. Distance with Butterworth Filter") plt.ylabel("Decay Value") plt.xlabel("Distance (meters)") plt.show() def plot_wait(norm=False): per_hour = np.array(range(1, 6000), dtype=np.float) per_hour = per_hour / 1000.0 fig, ax = plt.subplots(figsize=(10, 6)) for dpass in [1, 2, 5, 10, 15, 20, 30, 45, 60]: decay_list = [] for f in per_hour: # decay = get_factor(f, dpass) decay = wait_decay(f, dpass) # print f, decay decay_list.append(decay) label = "m_b: %d (min)" % dpass if norm: line1, = ax.plot(per_hour, normalize(decay_list), label=label) else: line1, = ax.plot(per_hour, decay_list, label=label) # line1, = ax.plot(mi, decay_list, label=label) if norm: line2, = ax.plot(per_hour, normalize(per_hour), label="Departures / Hour") if norm: ax.legend(loc='lower right') plt.title("Normalized Service vs. Departures per Hour") plt.ylabel("Normalized Service") else: ax.legend(loc='upper left') plt.title("Service vs. Departures per Hour") plt.ylabel("Service") plt.xlabel("Departures / Hour") plt.subplots_adjust(left=0.1, right=.9, top=0.9, bottom=0.1) plt.show() if __name__ == "__main__": plot_wait(norm=True) # plot_butterworth_wait() # comp(30, 15) # raise ValueError("done") # decay = get_factor(2, 15) # print decay # raise ValueError("Done") """ fig, ax = plt.subplots() # line1, = ax.loglog(x, y, label="July") # line2, = ax.loglog(x2, y2, label="BRT 1") line1, = ax.semilogy(x, y, label="July") line2, = ax.semilogy(x2, y2, label="BRT 1") ax.legend(loc='lower left') plt.title("Score vs # of Grid Cells") plt.ylabel("Accessibility Score") plt.xlabel("Number of 100m X 100m grid Cells") plt.show() """
from datetime import date import numpy as np from scipy import signal import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator import pandas_datareader.data as webdata from dateutil.relativedelta import relativedelta today = date.today() start = today-relativedelta(years=1) symbol = "QQQ" quotes =webdata.get_data_yahoo(symbol, start, today) quotes = np.array(quotes) dates = quotes.T[0] qqq = quotes.T[1] y = signal.detrend(qqq) alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") fig = plt.figure() ax = fig.add_subplot(111) plt.plot(dates, qqq, 'o', dates, qqq - y,'-') ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(month_formatter) fig.autofmt_xdate() plt.show()
from app.api import users, customers, water_meter, detect_object routes = [ users, customers, water_meter, detect_object ] def init_app(app, base_url): for route in routes: app.register_blueprint(route.bp, url_prefix=base_url + route.path)
from name_function import get_formatted_name print("Enter 'q' at any time to quit.") while True: first=input("\nPlease give me a first name:\n") if first =='q': break second=input("Please give me a last name:\n") if second=='q': break formatted_name=get_formatted_name(first,second) print("\tNeatly formatted name: "+formatted_name+" .")
# -*- coding: utf-8 -*- class Solution: def search(self, nums, target): first, last = 0, len(nums) - 1 while first <= last: mid = (first + last) // 2 if nums[mid] == target: return True elif nums[first] == nums[mid]: first += 1 elif (nums[first] < nums[mid] and nums[first] <= target < nums[mid]) or ( nums[first] > nums[mid] and not (nums[mid] < target <= nums[last]) ): last = mid - 1 else: first = mid + 1 return False if __name__ == "__main__": solution = Solution() assert solution.search([2, 5, 6, 0, 0, 1, 2], 0) assert not solution.search([2, 5, 6, 0, 0, 1, 2], 3) assert solution.search([1, 3, 1, 1, 1], 3)
default_app_config = 'gim.front.activity.apps.FrontActivityConfig'
import random class Walker: def __init__(self,steps,dgrid2): self.steps = steps self.dgrid2 = dgrid2 self.right_bound = dgrid2.cols self.bot_bound = dgrid2.rows self.x,self.y = self.place_walker() def place_walker(self): ci = int(self.dgrid2.rows/2) cj = int(self.dgrid2.cols/2) self.dgrid2.set_cell(ci,cj,1) return (ci,cj) def color_landscape(self): # color the landscape after a walk has taken place so as to do the calculations once and not every frame in an animation for i in range(self.dgrid2.rows): for j in range(self.dgrid2.cols): self.color_cell(self.dgrid2.get_cell(i,j)) def color_cell(self,cell): # Set brackets to use in if statement, similar to walk() method land_bracket = self.dgrid2.biome.get_landscape_distrib() veg_bracket = self.dgrid2.biome.get_vegetation_distrib() + land_bracket mount_bracket = self.dgrid2.biome.get_mountain_distrib() + veg_bracket water_bracket = self.dgrid2.biome.get_water_distrib() + mount_bracket r = random.random() if r < land_bracket: cell.set_color(self.dgrid2.biome.get_landscape_color()) elif r < veg_bracket: cell.set_color(self.dgrid2.biome.get_vegetation_color()) elif r < mount_bracket: cell.set_color(self.dgrid2.biome.get_mountain_color()) else: cell.set_color(self.dgrid2.biome.get_water_color()) def is_valid_step(self,x,y): # x represents column number # y represents row number if x < 0 or x >= self.right_bound: return False if y < 0 or y >= self.bot_bound: return False return True def step_left(self): step_x = self.x - 1 # check move before making move if self.is_valid_step(step_x,self.y): self.x = step_x prev_step_count = self.dgrid2.get_cell(self.y,self.x).get_value() self.dgrid2.set_cell(self.y,self.x,prev_step_count + 1) return (prev_step_count + 1) else: return -1 def step_right(self): step_x = self.x + 1 if self.is_valid_step(step_x,self.y): self.x = step_x prev_step_count = self.dgrid2.get_cell(self.y,self.x).get_value() self.dgrid2.set_cell(self.y,self.x,prev_step_count + 1) return (prev_step_count + 1) else: return -1 def step_up(self): step_y = self.y - 1 if self.is_valid_step(self.x,step_y): self.y = step_y prev_step_count = self.dgrid2.get_cell(self.y,self.x).get_value() self.dgrid2.set_cell(self.y,self.x,prev_step_count + 1) return (prev_step_count + 1) else: return -1 def step_down(self): step_y = self.y + 1 if self.is_valid_step(self.x,step_y): self.y = step_y prev_step_count = self.dgrid2.get_cell(self.y,self.x).get_value() self.dgrid2.set_cell(self.y,self.x,prev_step_count + 1) return (prev_step_count + 1) else: return -1 def walk(self): steps = 0 for i in range(self.steps): r = random.random() if r < 0.25: steps = self.step_left() elif r < 0.5: steps = self.step_right() elif r < 0.75: steps = self.step_up() else: steps = self.step_down() if steps > self.dgrid2.max_step_count: self.dgrid2.max_step_count = steps
""" Created by Alex Wang On 2017-11-30 测试pandas pandas:list<dict>保存和读取 list<dict>转化成DataFrame:data_frame = pd.DataFrame(data_feature) DataFrame保存到csv文件:result_data.to_csv(os.path.join(data_base, 'labeled_dataset_result.csv'), sep='\t') 从csv文件加载DataFrame数据: DataFrame方法:head([n])--返回前n行;info()--信息总结;pop()--弹出列;drop()--丢弃列;shape--(行数,列数);get_value(i,label)--获取值 """ import pandas as pd def test_pandas(): print("test pandas") data_feature = [] data_feature.append({'name':'Alex Wang', 'year':1990}) data_feature.append({'name':'William', 'year':1991}) data_frame = pd.DataFrame(data_feature) data_frame.info() if __name__ == '__main__': test_pandas()
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.constants import epsilon_0 # np.set_printoptions(suppress=True) class FEM_1D(): ''' Modelo de elementos finitos 1D para solução do problema de um capacitor preenchido por dois dielétricos de permissividades e1 e e2. Considerando a placa inferior do capacitor (1) está aterrada. É assumido que L >> d para que o problema seja reduzido a 1 dimensão. ''' def __init__(self, L, d1, d2, er1, er2, N1, N2, V0, p01 = 0, p02 = 0): ''' Entradas: L => Comprimento da placa do capacitor d1 => Altura do dielétrico 1 d2 => Altura do dielétrico 2 er1 => Permissividade relativa do dielétrico 1 er2 => Permissividade relativa do dielétrico 2 N1 => Quantidade de segmentos no dielétrico 1 N2 => Quantidade de segmentos no dielétrico 2 V0 => Valor da diferença de potencial entre as placas do capacitor (Vsuperior - Vinferior) p01 => Densidade volumétrica de cargas livres no dielétrico 1 p02 => Densidade volumétrica de cargas livres no dielétrico 2 ''' self.L = L self.d1 = d1 self.d2 = d2 self.e1 = er1 * epsilon_0 self.e2 = er2 * epsilon_0 self.N1 = N1 self.N2 = N2 self.V0 = V0 self.p01 = p01 self.p02 = p02 self.N = N1 + N2 self.l1 = None self.l2 = None self.K = None self.K1 = None self.K2 = None self.f = None self.f1 = None self.f2 = None self.b = None self.sol = None def solve(self): ''' Método para realizar a solução do problema, faz a chamada de várias funções para o cálculo de um elemento específico para realizar a solução No final, retorna um vetor com os potenciais nos nós. ''' self.__calculateLengthElements() self.__calculateKi() self.__calculatefi() self.__calculateK() self.__calculatef() self.__applyBoundaryCondition() self.__calculateVs() return np.copy(self.sol) def __calculateLengthElements(self): ''' Calcula o comprimento dos elementos do dielétrico 1 (l1) e do dielétrico 2 (l2). ''' self.l1 = self.d1/self.N1 self.l2 = self.d2/self.N2 def __calculateKi(self): ''' Calcula a matriz Ki para os elementos do dielétrico 1 (K1) e para os elementos do dielétrico 2 (K2). ''' self.K1 = self.e1/self.l1 * np.array([[1, -1], [-1, 1]]) self.K2 = self.e2/self.l2 * np.array([[1, -1], [-1, 1]]) def __calculateK(self): ''' Calcula a matriz K ''' n = self.N + 1 K = np.zeros((n,n)) for i in range(self.N1): K[i][i] += self.K1[0][0] K[i][i+1] += self.K1[0][1] K[i+1][i] += self.K1[1][0] K[i+1][i+1] += self.K1[1][1] for i in range(self.N1, self.N): K[i][i] += self.K2[0][0] K[i][i+1] += self.K2[0][1] K[i+1][i] += self.K2[1][0] K[i+1][i+1] += self.K2[1][1] self.K = K print('-----------------------') print('K:') print(pd.DataFrame(self.K)) def __calculatefi(self): ''' Calcula a matriz fi para os elementos do dielétrico 1 (f1) e para os elementos do dielétrico 2 (f2) ''' self.f1 = -self.p01*self.l1/2 * np.array([1, 1]) self.f2 = -self.p02*self.l2/2 * np.array([1, 1]) def __calculatef(self): ''' Calcula a matriz coluna f ''' n = self.N + 1 f = np.zeros(n) for i in range(self.N1): f[i] += self.f1[0] f[i+1] += self.f1[1] for i in range(self.N1, self.N): f[i] += self.f2[0] f[i+1] += self.f2[1] self.f = f print('-----------------------') print('f:') print(pd.DataFrame(self.f)) def __applyBoundaryCondition(self): ''' Aplicando as condições de contorno para o problema: 1) V1(0) = 0 2) V2(d1+d2) = V0 Ao aplicar essas condições de limites ao problema o vetor d se reduzirar a um vetor com todos elementos nulos, logo não o consideraremos para o cálculo. ''' b = np.copy(self.f) # Aplicando condição de contorno 1) V1(0) = 0 # movendo a coluna para o outro lado do sistema c_v1 = self.K[:, 0] b += -c_v1 * 0 # Aplicando condição de contorno 2) V2(0) = 0 # movendo a coluna para o outro lado do sistema c_vN_plus_1 = self.K[:, self.N] b += -c_vN_plus_1 * self.V0 # removendo a primeira e última linha e a primeira e última coluna da matriz K e da matriz b self.K = self.K[1:self.N, 1:self.N] b = b[1: self.N] self.b = b print('-----------------------') print('K após condição de contorno:') print(pd.DataFrame(self.K)) print('-----------------------') print('b (f+d) após condição de contorno:') print(pd.DataFrame(self.b)) def __calculateVs(self): ''' Solução do sistema linear da forma KV = b sendo b = f+d ''' Vs = np.linalg.solve(self.K, self.b) # concatenando os potenciais de z = 0 e de z = d1+d2 Vs = np.concatenate((np.array([0]),Vs ,np.array([self.V0]))) self.sol = Vs def calculateCapacitance(self): ''' Calcula a capacitância do capacitor do problema ''' E = (self.sol[0] - self.sol[1])/self.l1 sigma = -E*self.e1 A = self.L*self.L Q = sigma * A C = Q/self.V0 return C def plotSol(d1, d2, N1, N2, V0, vs): ''' Função para plotar a solução dos potenciais obtidas em função de z. ''' x1 = np.linspace(0, d1, N1+1) x2 = np.linspace(d1, d1 + d2, N2+1) x = np.unique(np.concatenate((x1, x2))) y = np.copy(vs) plt.plot(x, y, 'o') plt.xlabel("z") plt.ylabel("V") plt.show() def showSol(sol, N, V0): ''' Função para printar no terminal os valores de V obtidos nos pontos. ''' vs = sol col_indx = [] print('-------------------------------') print('Valores de potencial entre as placas:') for i in range(N+1): print(f'v{i+1} = {vs[i]}') def showCap(Ns,Cs): ''' Função para plotar o grafico da capacitância em função de N ''' plt.plot(Ns, Cs) plt.xlabel("N") plt.ylabel("Capacitância") plt.show() def main(): L=0.02 d1=0.001 d2=0.001 er1=2 er2=4 N1=50 N2=50 V0=1 model = FEM_1D(L, d1, d2, er1, er2, N1, N2, V0) sol = model.solve() showSol(sol, N1+N2, V0) plotSol(d1, d2, N1, N2, V0, sol) # Seleciono alguns valores de (N1, N2) para realizar o cálculo da capacitância # desses valores e assim realizar o plot dos resultados obtidos. Ns = [(2, 2), (5, 5), (5, 10),(15,15), (50, 50)] Cs = [] for n in Ns: md = FEM_1D(L, d1, d2, er1, er2, n[0], n[1], V0) md.solve() Cs.append(md.calculateCapacitance()) Ns = list(map(lambda x : x[0] + x[1], Ns)) showCap(Ns, Cs) if __name__ == '__main__': main()
from django.core.management.base import BaseCommand, CommandError from catalog.models import Country, MovieRole, MovieFigure, Genre, AuthorReview, Review, Film, Tag from django.contrib.auth.models import User import factory from random import randint from datetime import timedelta class CountryFactory(factory.django.DjangoModelFactory): class Meta: model = Country name_county = factory.Faker('country') class MovieRoleFactory(factory.django.DjangoModelFactory): class Meta: model = MovieRole role = factory.Iterator(['режисер', 'продюсер', 'актер']) class MovieFigureFactory(factory.django.DjangoModelFactory): class Meta: model = MovieFigure fio = factory.Faker('name_nonbinary') @factory.post_generation def role(self, create, extracted, **kwargs): if extracted: for rol in extracted: self.role.add(rol) class AuthorReviewFactory(factory.django.DjangoModelFactory): class Meta: model = AuthorReview fio = factory.Faker('name_nonbinary') class ReviewFactory(factory.django.DjangoModelFactory): class Meta: model = Review film_review_title = factory.Faker('sentence', nb_words=3) film_review = factory.Faker('sentence', nb_words=20) rating = factory.Iterator([randint(1, 10) for x in range(100)]) film = factory.Iterator(Film.objects.all()) author_review = factory.Iterator(AuthorReview.objects.all()) class FilmFactory(factory.django.DjangoModelFactory): class Meta: model = Film movie_title = factory.Faker('sentence', nb_words=2) production_year = factory.Faker('date') country = factory.Iterator(Country.objects.all()) budget = factory.Iterator([float(randint(1000, 100000)) for x in range(100)]) worldwide_gross = factory.Iterator([float(randint(1000, 100000)) for x in range(100)]) duration = factory.Iterator([timedelta(minutes=randint(30, 180)) for x in range(100)]) @factory.post_generation def genre(self, create, extracted, **kwargs): if extracted: for ge in extracted: self.genre.add(ge) @factory.post_generation def director(self, create, extracted, **kwargs): if extracted: for dir in extracted: self.director.add(dir) @factory.post_generation def producer(self, create, extracted, **kwargs): if extracted: for prod in extracted: self.producer.add(prod) @factory.post_generation def actor(self, create, extracted, **kwargs): if extracted: for act in extracted: self.actor.add(act) @factory.post_generation def tag(self, create, extracted, **kwargs): if extracted: for tg in extracted: self.tag.add(tg) def delete_all(): Review.objects.all().delete() Film.objects.all().delete() Tag.objects.all().delete() Genre.objects.all().delete() Country.objects.all().delete() MovieFigure.objects.all().delete() MovieRole.objects.all().delete() AuthorReview.objects.all().delete() class Command(BaseCommand): help = "Upload data" def handle(self, *args, **kwargs): print('------ delete old data') delete_all() print("------ upload data: start") print("------ upload Country") countries = CountryFactory.create_batch(5) for county in countries: print(county.name_county) print("------ upload MovieRole") roles = MovieRoleFactory.create_batch(3) for rl in roles: print(rl.role) print("------ upload MovieFigure") # Создадим 5 режиссеров figures = MovieFigureFactory.create_batch(5, role=MovieRole.objects.filter(role='режисер')) for figure in figures: print(figure) # Создадим 5 актеров figures = MovieFigureFactory.create_batch(5, role=MovieRole.objects.filter(role='актер')) for figure in figures: print(figure) # Создадим 5 продюссеров figures = MovieFigureFactory.create_batch(5, role=MovieRole.objects.filter(role='продюсер')) for figure in figures: print(figure) print("------ upload Genre") genre_drama = Genre.objects.create(genre_name='драма') genre_comedy = Genre.objects.create(genre_name='комедия') genre_action = Genre.objects.create(genre_name='боевик') genre_romance = Genre.objects.create(genre_name='мелодрама') genre_thriller = Genre.objects.create(genre_name='триллер') print("------ upload Film") films = FilmFactory.create_batch( 10, genre=Genre.objects.all(), director=MovieFigure.objects.prefetch_related('role').filter(role__role='режисер').all(), producer=MovieFigure.objects.prefetch_related('role').filter(role__role='продюсер').all(), actor=MovieFigure.objects.prefetch_related('role').filter(role__role='актер').all(), # review=Review.objects.all() ) for film in films: print(film) print("------ upload AuthorReview") authors_review = AuthorReviewFactory.create_batch(5) for author in authors_review: print(author) print("------ upload Review") reviews = ReviewFactory.create_batch(5) for review in reviews: print(review) print("------ upload data: end")
first_name = "beata " # varaible first name last_name = "KOCHANEK" # variable last name greeting = "Hello, " # variable set to show hello print(greeting + "\n\n" + first_name.upper() + last_name.lower()) # show hello and add two new lines, show first name in uppercase and last name lowercase string_quote = "\"Start by doing what's necessary; then do what's possible; and suddenly you are doing the impossible\"- Francis of Assisi" # print quote with quotes on both sides of the text print(string_quote) numberOne= 12.2 numberTwo = 2.1 addition_result = numberOne + numberTwo # add numbers print(addition_result) # show the result of addition subtract_result = numberOne - numberTwo # subtract numbers print(subtract_result) # show the result of addition multiply_result = numberOne * numberTwo # multiply numbers print(multiply_result) # show the result of multiplication divide_result = numberOne / numberTwo #divide numbers print(divide_result) # show the result of division string_variable = "October " # store current month as variable number_variable = 29 # store day of the month output_variable = "\n\t\tToday is day " + str(number_variable) + " " + "of the month of " + string_variable # output the message on a new line with two tabs print(output_variable) # show the output variable
from __future__ import print_function import math, os, bz2, urlutil, tiles, time, pycurl, gzip, sys, tarfile from pyo5m import OsmData from io import BytesIO def GetTile(x, y, zoom, outFina): topLeft = tiles.num2deg(x, y, zoom) bottomRight = tiles.num2deg(x+1, y+1, zoom) #url = "http://fosm.org/api/0.6/map?bbox={0},{1},{2},{3}".format(topLeft[1],bottomRight[0],bottomRight[1],topLeft[0]) url = "http://sodium:8010/api/0.6/map?bbox={0},{1},{2},{3}".format(topLeft[1],bottomRight[0],bottomRight[1],topLeft[0]) print (url) timeout = 1 waiting = 1 while waiting: try: body, header = urlutil.Get(url) responseCode = urlutil.HeaderResponseCode(header) print (responseCode) if responseCode == "HTTP/1.1 200 OK": waiting = 0 else: time.sleep(timeout) timeout *= 2 except pycurl.error: time.sleep(timeout) timeout *= 2 extSp = os.path.splitext(outFina) extSp2 = os.path.splitext(extSp[0]) if extSp[1] == ".bz2" and extSp2[1] == ".osm": outFi = bz2.BZ2File(outFina,"w") outFi.write(body) if extSp[1] == ".gz" and extSp2[1] == ".o5m": osmData = OsmData.OsmData() osmData.LoadFromOsmXml(BytesIO(body)) osmData.SaveToO5m(gzip.open(outFina, "wb")) return 1 if __name__ == "__main__": tileBL = (0, 4095) #Planet tileTR = (4095, 0) #Planet #tileBL = tiles.deg2num(51.7882364, -3.4765251, 12) #Hampshire? #tileTR = tiles.deg2num(52.3707994, -2.2782056, 12) #Hampshire? #tileBL = tiles.deg2num(27.673799, 32.1679688, 12) #Sinai #tileTR = tiles.deg2num(31.297328, 35.0024414, 12) #Sinai #tileBL = tiles.deg2num(51.00434, -4.02825, 12) #Exmoor #tileTR = tiles.deg2num(51.26630, -3.26607, 12) #Exmoor #tileBL = tiles.deg2num(49.0018439, -0.6632996, 12) #Caen #tileTR = tiles.deg2num(49.3644891, 0.0054932, 12) #Caen #tileBL = tiles.deg2num(49.6676278, -14.765625, 12) #UK and Eire #tileTR = tiles.deg2num(61.1856247, 2.2851563, 12) #UK and Eire #tileBL = tiles.deg2num(-47.279229, 107.7539063, 12) #Aus #tileTR = tiles.deg2num(-9.2756222, 162.5976563, 12) #Aus #tileBL = tiles.deg2num(50.6599084, -1.3046265, 12) #Around portsmouth, uk #tileTR = tiles.deg2num(50.9618867, -0.8061218, 12) outFileTemplate1 = "{0}/{1}.osm.bz2" outFileTemplate = "12/{0}/{1}.osm.bz2" #outFileTemplate = "12/{0}/{1}.o5m.gz" tarCol = False print (tileBL, tileTR) count = 0 for x in range(tileBL[0], tileTR[0] + 1): #Check if column tar exists if tarCol: tarFina = "12/{0}.tar".format(x) if os.path.exists(tarFina): continue for y in range(tileTR[1], tileBL[1] + 1): print (count, (tileBL[0] - tileTR[0] + 1) * (tileTR[1] - tileBL[1] + 1), x, y) count += 1 if not os.path.isdir("12"): os.mkdir("12") if not os.path.isdir("12/{0}".format(x)): os.mkdir("12/{0}".format(x)) outFina = outFileTemplate.format(x, y) overwrite = False if not os.path.exists(outFina) or overwrite: GetTile(x, y, 12, outFina) #time.sleep(1) #Combine column into tar if tarCol: print ("Tarring column") t = tarfile.open(tarFina, mode='w') for y in range(tileTR[1], tileBL[1] + 1): tileFina = outFileTemplate.format(x, y) tileFi = open(tileFina, 'rb') tileFi.seek(0, 2) fileSize = tileFi.tell() tileFi.seek(0) tileStat = os.stat(tileFina) ti = tarfile.TarInfo() ti.name = outFileTemplate1.format(x, y) ti.size = fileSize ti.mtime = tileStat.st_mtime t.addfile(ti, tileFi) tileFi.close() t.close() for y in range(tileTR[1], tileBL[1] + 1): tileFina = outFileTemplate.format(x, y) os.unlink(tileFina) os.rmdir("12/{0}".format(x))
from django.conf.urls import url from . import views urlpatterns = [ # urls for handling contact us messages url(r'^autentificare/$', views.userLogin, name="login"), url(r'^logout/$', views.logOut, name="logout"), ]
from math import sqrt def is_prime(n): if n < 2: return False for i in range(2, n-1): if n % i == 0: return False return True def is_prime_optimized(n): if n < 2: return False limit = int(sqrt(n)) for i in range(2, limit+1): if n % i == 0: return False return True print(is_prime(2)) print(is_prime_optimized(2)) print(is_prime(3)) print(is_prime_optimized(3)) print(is_prime(5)) print(is_prime_optimized(5))
from django.apps import AppConfig class ReBlogConfig(AppConfig): name = 're_blog'
# coding:utf-8 from __future__ import absolute_import, unicode_literals from jspider.manager.deamon import Daemon import multiprocessing __author__ = "golden" __date__ = '2018/6/26' import time import asyncio async def task_async(): while True: print('task async running') await asyncio.sleep(1) class Main(Daemon): def __init__(self): super(Main, self).__init__(pid_file='/tmp/aa.pid', stdout='/tmp/aa.log') def run(self): def task(): while True: print('task running at %s' % time.time()) time.sleep(2) def task2(): loop = asyncio.new_event_loop() asyncio.run_coroutine_threadsafe(task_async(), loop) asyncio.set_event_loop(loop) loop.run_forever() p1 = multiprocessing.Process(target=task) p2 = multiprocessing.Process(target=task2) p1.start() p2.start() p1.join() p2.join() if __name__ == '__main__': m = Main() m.start()
# Generated by Django 2.2.6 on 2020-06-02 06:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('consumers', '0013_auto_20200204_0129'), ] operations = [ migrations.AlterField( model_name='consumer', name='census', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='consumer', name='consumer_id', field=models.CharField(blank=True, max_length=200, null=True, unique=True, verbose_name='x'), ), migrations.AlterField( model_name='consumer', name='name', field=models.CharField(blank=True, max_length=50, null=True), ), ]
import cv2 import time import numpy as np #计算程序执行时间的装饰器 def time_test(fn): def _wrapper(*args, **kwargs): start = time.clock() location, max_pos = fn(*args, **kwargs) print ("%s() cost %s second" % (fn.__name__, time.clock() - start)) return location, max_pos return _wrapper @time_test def img_choose(deep_img, threshold = 150, border = [25, 50]): region = deep_img > threshold #region = np.zeros(deep_img.shape, dtype = 'bool') #region[threshold[0] < deep_img & deep_img < threshold[1]] = True shape = deep_img.shape height = np.arange(0, shape[0], 1) width = np.arange(0, shape[1], 1) location = [int(shape[0]/2), int(shape[1]/2), int(shape[0]/2), int(shape[1]/2)] #top-left, bottom_right max_value = threshold max_pos = [0, 0] for h in height[border[0]: shape[0] - border[0]]: #排除部分边缘 for w in width[border[1]: shape[1] - border[1]]: if(region[h, w]): if(deep_img[h, w] > max_value): if((deep_img[h - 4 : h + 4, w - 4 : w + 5] > 180).all()): max_value = deep_img[h, w] max_pos = [h, w] if(h < location[0] and region[h + 1 : h + 5, w].all()): location[0] = h if(w < location[1] and region[h, w + 1 : w + 5].all()): location[1] = w if(h > location[2] and region[h - 5 : h, w].all()): location[2] = h if(w > location[3] and region[h, w - 5 : w].all()): location[3] = w return location, max_pos #return top-left', bottom_right' coordinate if __name__ == '__main__': name_part = ['a', 'b', 'c', 'd', 'e'] with open('Bounding Box.txt', mode = 'w') as output: for i in range(0, 5): for j in range(1, 6): deep_img_name = 'x' + 'd' + name_part[i] + str(j) + '.jpg' color_img_name = 'x' + 'c' + name_part[i] + str(j) + '.jpg' deep_img = cv2.imread(deep_img_name, 0) color_img = cv2.imread(color_img_name) location, max_pos = img_choose(deep_img, threshold = 150) h_mapping = lambda x: int((x - 47.10)/0.7708) w_mapping = lambda x: int((x - 22.35)/0.7022) #max_pos = deep_img.argmax() #根据最近点,标定工件上的区域位置 #h_max_pos = int(max_pos/640 - 1) #w_max_pos = int(max_pos - 640*(h_max_pos + 1) - 1) h_max_pos = max_pos[0] w_max_pos = max_pos[1] deep_img[:, w_max_pos] = 255 deep_img[h_max_pos, :] = 255 h_max_pos = h_mapping(h_max_pos) w_max_pos = w_mapping(w_max_pos) color_img[:, w_max_pos] = np.array([255, 255, 255]) color_img[h_max_pos, :] = np.array([255, 255, 255]) #print('Depth : ', location) cv2.imwrite('new_' + deep_img_name, deep_img[location[0]:location[2], location[1]:location[3]]) location[0] = h_mapping(location[0]) #映射深度图像坐标至彩色图像 location[2] = h_mapping(location[2]) location[1] = w_mapping(location[1]) location[3] = w_mapping(location[3]) output.write('(' + str(location[0]) + ',' + str(location[2]) + ')' + ' ' + '(' + str(location[1]) + ',' + str(location[3]) + ')' + '\n') #print('Color : ', location, '\n') cv2.imwrite('new_' + color_img_name, color_img[location[0]:location[2], location[1]:location[3]])
# ############################### # Michael Vassernis - 319582888 # ################################# import numpy as np import struct import pickle def softmax_batch(x): e_x = np.exp(x - (np.max(x) + 1)) return e_x / e_x.sum(axis=1)[:,None] def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum() def read_idx(filename): with open(filename, 'rb') as f: zero, data_type, dims = struct.unpack('>HBB', f.read(4)) shape = tuple(struct.unpack('>I', f.read(4))[0] for _ in range(dims)) return np.fromstring(f.read(), dtype=np.uint8).reshape(shape) def load_mnist(folder_path): print 'loading dataset...' train_y = read_idx(folder_path + '/train-labels-idx1-ubyte/data') train_x = read_idx(folder_path + '/train-images-idx3-ubyte/data') train_x = (train_x.reshape((len(train_y), 28*28)) / 255.0) C = np.sum(train_x, axis=0) count_zeros = 0 zero_indexes = [] for i in range(len(C)): if C[i] < 0.5: count_zeros += 1 zero_indexes.append(i) size_no_zeros = (len(train_x) * len(train_x[0]) - count_zeros * len(train_x)) mean = np.sum(train_x) / size_no_zeros std_temp = (train_x - mean) ** 2 for index in zero_indexes: std_temp[:,index] = 0.0 std = np.sqrt(np.sum(std_temp) / size_no_zeros) print 'dataset mean:', mean print 'dataset std:', std train_x = (train_x - mean) / std for index in zero_indexes: train_x[:,index] = 0.0 print 'dataset normalized.' train_set = np.c_[train_x.reshape(len(train_x), -1), train_y.reshape(len(train_y), -1)] dev_set = train_set[50000:] train_set = train_set[:50000] np.random.shuffle(train_set) return train_set, dev_set def accuracy_on_dataset(data_set, model): correct = wrong = 0.0 for example in data_set: if model.predict(example[:-1]) == example[-1]: correct += 1 else: wrong += 1 return correct / (correct + wrong) def save_model(model, filename): file_pickle = open(filename, 'wb') pickle.dump(model, file_pickle) def load_model(filename): file_pickle = open(filename, 'rb') model = pickle.load(file_pickle) return model
# Define a function that gets a string and a filepath as parameters and returns the number of occurences of that string in the file. def foo(character, filepath="bear.txt"): file = open(filepath) content = file.read() return content.count(character) bear_count = foo("bear","files/bear.txt") print(bear_count)
import pyaudio import numpy as np from scipy import signal from microphone import Microphone from melmat import * from dsp import DSP from config import * import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() ax.set_xlim([0,VISUALIZER_LENGTH]) ax.set_ylim([0,VISUALIZER_HEIGHT]) x_axis = np.arange(VISUALIZER_LENGTH) y_axis = np.zeros(VISUALIZER_LENGTH) line, = ax.plot(x_axis, y_axis) mic = Microphone(FORMAT=FORMAT, CHANNELS=CHANNELS, RATE=RATE, FRAMES_PER_BUFFER=FRAMES_PER_BUFFER, DEVICE_ID=DEVICE_ID) sig_processor = DSP(ALPHA_SMOOTHING=ALPHA_SMOOTHING) def init(): # only required for blitting to give a clean slate. x_data = np.arange(VISUALIZER_LENGTH) y_data = np.zeros(len(x_data)) line.set_data(x_data, y_data) return line, def animate(i): x_data = np.arange(VISUALIZER_LENGTH) y_data = np.zeros(len(x_data)) raw_data = mic.sampleInput() if sum(raw_data) > 0: processed_data = sig_processor.process_sample(raw_data) y_data = np.concatenate((processed_data[::-1], processed_data)) y_data = y_data / y_data.mean() x_data = np.arange(len(y_data)) line.set_data(x_data, y_data) return line, ani = animation.FuncAnimation( fig, animate, blit=True, init_func=init, frames = 10, interval=10 ) plt.show() mic.destroy()
X=int(input()) H=int(input()) M=int(input()) hr=(H+(X//60)) #8 mn=(M+(X%60)) #110 if mn > 60: hr = hr+(mn//60) mn = mn - 60 print(hr) print(mn) else: if mn < 60: print(hr) print(mn)
from __future__ import division from pynsim import Engine class SupplyRouting(Engine): """ This engine routs water through the UBB system. Currently routing is done for reservoirs and junction nodes (i.e. non-demand nodes. Return flows are not accounted for in this version (but should be in future versions, when we have a better idea of demand node (agri, urban) return flows. This routing engine may be replaced by an optimization based engine. The routing is done for each timestep (i.e. a month)'. The following steps take place in this version of the engine: i) Each node is ranked according to how many nodes are upstream of it. The most upstream nodes have rank of 1, and so on ii) Starting from the highest ranked (rank = 1) nodes, the water is routed ('pushed') through the system. The water release decision depends on the type of node, and its associated decision rule. If it's a reservoir, a mass balance is performed to obtain releases from the reservoir. The reservoirs make their water release decisions based on a defined release schedule. We currently do not have information for this, so I have made up some synthetic data on target releases. The reservoirs try to satisfy these targets while being constrained by minimum and maximum storage. For both junctions and reservoirs, the flow can be directed downstream in two ways. The default is to split the flow equally among all downstream links. Another way is to provide specific allocations (either in form of a percentage or absolute volume of flows for each of the downstream links). """ name = "Supply based flow routing." def run(self): alldepths = [] for n in self.target.nodes: alldepths.append(n.get_depth()) deepest = max(alldepths) for rank in range(1,deepest+1): appnodes = [] for n in self.target.nodes: if n.get_depth() == rank and n.node_type in ['jnc', 'res']: appnodes.append(n) for node in appnodes: if node.node_type == 'jnc': node.allocate() if node.node_type == 'res': #node.res_mass_balance() node.all_inflow = sum([l.flow for l in node.in_links]) + node.surf_inflow #Set initial storage for this simulation time step if len(node._history['S']) == 0: init_stor = node.init_stor else: init_stor = node._history['S'][-1] node.actual_release = node.release_schedule[self.target.network.current_timestep_idx] node.S = init_stor + node.all_inflow - node.actual_release maxFlag = (node.S - node.max_stor) > 0.1 minFlag = (node.min_stor - node.S) > 0.1 #while any(maxFlag) or any(minFlag): #FOR NOW WE ARE REMOVING THIS FLAG BECAUSE WE'RE NOT SURE IF THE SYNTHETIC VALUES MAKE SENSE if maxFlag: excess_stor = node.S - node.max_stor node.actual_release += excess_stor elif minFlag: deficit_stor = node.S - node.min_stor node.actual_release += deficit_stor # Update storages node.S = init_stor + node.all_inflow - node.actual_release ############################################################################################# #node.res_allocate() allocation_avail = node.actual_release if node.allocation is not None: if type(node.allocation_priority) == tuple: for i, link in enumerate(node.allocation_priority): allocation = node.allocation[i] alloc_vol = node.set_outflow(link, allocation) allocation_avail = allocation_avail - alloc_vol else: link = node.allocation_priority allocation = node.allocation alloc_vol = node.set_outflow(link, allocation) allocation_avail = allocation_avail - alloc_vol if allocation_avail < 0: raise Exception("Node %s cannot satisfy allocation." % (node.name)) if len(node.out_links) > 0: # Split the remaining water equally between remaining links link_alloc = 1/len(node.out_links) for seq in node.out_links: supply = node.actual_release * link_alloc if seq.end_node.node_type == 'farm': seq.flow = min(seq.end_node.demand, supply) else: seq.flow = supply
import os import msal from office365.graph_client import GraphClient from settings import settings def acquire_token(): """ Acquire token (MSAL) """ authority_url = 'https://login.microsoftonline.com/{0}'.format(settings.get('tenant')) app = msal.ConfidentialClientApplication( authority=authority_url, client_id=settings.get('client_credentials').get('client_id'), client_credential=settings.get('client_credentials').get('client_secret') ) result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"]) return result client = GraphClient(acquire_token) user_name = settings.get('first_account_name') target_drive = client.users[user_name].drive local_path = "../../tests/data/SharePoint User Guide.docx" with open(local_path, 'rb') as f: file_content = f.read() file_name = os.path.basename(local_path) target_file = target_drive.root.upload(file_name, file_content).execute_query() print(f"File {target_file.web_url} has been uploaded")
# Javascript 들여쓰기 예제 # var sumResult = plusCalculator(5, 10); # console.log(sumResult); # function plusCalculator(x, y) { #     return x + y; # } # var sumResult = plusCalculator(5, 10); # console.log(sumResult); # function plusCalculator(x, y) { # return x + y; # } def plusCalculator(x, y): result = x + y print(result) plusCalculator(5, 10)
from linear import linear_sort from bubble import bubble_sort from utility import generate_data from time import time from copy import deepcopy data_lengths = [10, 100, 1000, 10000] times = [] for length in data_lengths: data_set = generate_data(length) round_time = [] linear_set = deepcopy(data_set) bubble_set = deepcopy(data_set) linear_start = time() linear_sort(linear_set) linear_end = time() round_time.append(linear_end - linear_start) bubble_start = time() bubble_sort(bubble_set) bubble_end = time() round_time.append(bubble_end - bubble_start) times.append(round_time) print('Times:') print(times)
import sys n = int(input()) ; a = [int(e) for e in sys.stdin.readline().strip().split()] def MCS(a): p = a[0] ; s = a[0] for i in range(1,len(a)): p = max(p+a[i],a[i]) s = max(p,s) return s print(MCS(a))
#!/usr/bin/python3 # classes.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC class inclusive_range: def __init__(self,*args): numargs = len(args) if numargs < 1: raise TypeError('At least one error is needed') elif numargs == 1: self.stop = args[0] self.start = 0 self.step = 1 elif numargs == 2: (self.start,self.stop) = args if self.start > self.stop: print('Expected START to be smaller than STOP') return None self.step = 1 elif numargs == 3: (self.start,self.stop,self.step) = args if self.start > self.stop: print('Expected START to be smaller than STOP') return None else:raise TypeError('Expected at most 3 arguments, got {}'.format(numargs)) #Makes the object an generator object or iterable object def __iter__(self): i = self.start while i <= self.stop: yield i i += self.step def main(): o = inclusive_range(20) for i in inclusive_range(20): print(i, end = ' ') if __name__ == "__main__": main()