text
stringlengths
8
6.05M
from django.urls import path, include from acc import views ############################api############################# #from rest_framework.urlpatterns import format_suffix_patterns ############################################################# from rest_framework import routers ############################################################ router = routers.DefaultRouter() router.register('', views.userView) ############################################################ urlpatterns = [ path('', views.main, name="main"), path('reg/', views.reg, name='reg'), path('login/', views.log, name='login'), path('multi/', views.reglog, name='reglog'), ############################################################ #path('data/', views.userlist.as_view()), path('apilogin/', views.userLoginView.as_view()), path('msg/', views.Msg.as_view()), path('data/', include(router.urls)), ############################################################ ] ############################api############################# #urlpatterns = format_suffix_patterns(urlpatterns) ############################################################
# Generated by Django 3.0.3 on 2020-08-06 12:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Agents', fields=[ ('cf', models.IntegerField(primary_key=True, serialize=False, unique=True)), ('name', models.CharField(max_length=50)), ('surnames', models.CharField(max_length=100)), ('category', models.CharField(max_length=20)), ('residence', models.CharField(max_length=20)), ], ), migrations.CreateModel( name='Shifts', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=10, unique=True)), ('start', models.TimeField()), ('end', models.TimeField()), ('category', models.CharField(max_length=20)), ], ), migrations.CreateModel( name='AgentShifts', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('shift_date', models.DateField()), ('agent', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='weekly.Agents')), ('shift', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='weekly.Shifts')), ], ), ]
import requests as rq import time from random import shuffle with open('auth_token', 'r') as f: auth_token = f.read().strip() API_ENDPOINT = 'https://api.spotify.com/v1/' HEADERS = { 'Accept': 'application/json', 'Authorization': 'Bearer ' + auth_token } POPULARITY_THRESHOLD = 50 def get_playlists(q): q = q.replace(' ', '+') url = API_ENDPOINT + 'search?q=' + q + '&type=playlist' rep = rq.get(url, headers=HEADERS) data = rep.json().get('playlists', {}).get('items') if not data: return res = list() for d in data: res.append({ 'playlist_id': d.get('id'), 'user_id': d.get('owner', {}).get('id') }) return res def get_tracks(user_id, playlist_id): url = API_ENDPOINT + 'users/' + str(user_id) + '/playlists/' + str(playlist_id) + '/tracks' rep = rq.get(url=url, headers=HEADERS) data = rep.json().get('items') if not data: return low_popular_tracks = low_popularity_filter(data) ressources = get_ressources(low_popular_tracks) return ressources def low_popularity_filter(data): return filter(lambda d: d.get('track', {}).get('popularity') < POPULARITY_THRESHOLD, data) def get_ressources(tracks): res = list() for t in tracks: track = t.get('track', {}) res.append({ 'name': track.get('name'), 'artists': get_artists(track), 'previewUrl': track.get('preview_url') }) return res def get_artists(track): artists = track.get('artists') return ', '.join([a.get('name', '') for a in artists]) def process(query): playlists = get_playlists(query) res = list() for p in playlists: res += get_tracks(p.get('user_id'), p.get('playlist_id')) time.sleep(1) shuffle(res) return res
class Control: angle_min = 0 angle_max = 180 def __setStep(self): return self.__min + (self.__max - self.__min) * 0.7 def __init__(self, pw_min=1500, pw_max=1500): """ New control element Args: pw_min: pulse width in microseconds, corresponding to the minimum control value pw_max: pulse width in microseconds, corresponding to the maximum control value """ self.__min = pw_min self.__max = pw_max self.__threshold = self.__setStep() def setup(self, val): """ sets the value for the min and max pulse duration """ if val < self.__min: self.__min = val self.__threshold = self.__setStep() return True elif val > self.__max: self.__max = val self.__threshold = self.__setStep() return True def degree(self, val: int) -> int: """ translate pulse duration to angle in degrees Returns: Int """ if val > self.__max: return Control.angle_max elif val < self.__min: return Control.angle_min else: own = Control.angle_max - Control.angle_min ext = self.__max - self.__min return (val - self.__min) * own // ext + Control.angle_min def switch(self, val: int) -> bool: """ translate pulse duration to switch position Returns: True, if val more than 70% of (pw_max - pw_mix) None otherwise """ if val >= self.__threshold: return True def variator(self, val: int, min_val: float, max_val: float) -> float: """ translate pulse duration to variator position (custom value) Args: val: input value min_val: min value of data max_val: max value of data Returns: Float """ if val > self.__max: return max_val elif val < self.__min: return min_val else: own = max_val - min_val ext = self.__max - self.__min return (val - self.__min) * own / ext + min_val @property def max(self): return self.__max @property def min(self): return self.__min @max.setter def max(self, val): self.__max = val @min.setter def min(self, val): self.__min = val
from __future__ import annotations from typing import List, Optional from .package import Package class Label(object): """ Representation of a package and/or target, following bazel's Labels [1]. Not a full or even accurate re-implementation of bazel's Labels. Examples:: // //apps/pkg:target //apps/pkg //apps # May not be valid bazel pkg:target :target target [1]: https://docs.bazel.build/versions/2.0.0/build-ref.html#labels """ def __init__(self, package_path: Optional[str], target_name: Optional[str]): # TODO Enforce package_path and target_name validity? self.package_path = package_path self.target_name = target_name @classmethod def parse(cls, value: str) -> Label: if value is None: return cls(None, None) components = value.split(":") if len(components) == 1: item = components[0] if cls.is_absolute(item): package_path, target_name = item, None else: # Lacking a path specifier, assume the single component # refers to the target_name package_path, target_name = None, item # type: ignore else: # TODO Consider handling error of > 2 parts package_path, target_name = components[0:2] # Turn empty strings from .split() into None package_path = package_path or None # type: ignore target_name = target_name or None return cls(package_path, target_name) @staticmethod def is_absolute(package_path: Optional[str]) -> bool: return package_path is not None and package_path.startswith("//") def __eq__(self, other: object) -> bool: return ( isinstance(other, Label) and self.package_path == other.package_path and self.target_name == other.target_name ) def __str__(self) -> str: package_path = self.package_path or "" target_name = self.target_name or "" return f"{package_path}:{target_name}" def __repr__(self) -> str: return f"<{self.__class__.__name__}: {self}>" class ResolvedLabel(object): def __init__(self, packages: List[Package], target: Optional[Target]): self.packages = packages self.target = target def __eq__(self, other: object) -> bool: return ( isinstance(other, ResolvedLabel) and self.packages == other.packages and self.target == other.target ) def __str__(self) -> str: return f"{self.packages}:{self.target}" def __repr__(self) -> str: return f"<{self.__class__.__name__}: {self}>" class Target(object): def __init__(self, name: str): # TODO Validate target names self.name = name def __eq__(self, other: object) -> bool: return isinstance(other, Target) and self.name == other.name def __str__(self) -> str: return f"{self.name}" def __repr__(self) -> str: return f"<{self.__class__.__name__}: {self}>"
import FWCore.ParameterSet.Config as cms source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_100_1_u9l.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_101_1_91u.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_102_1_IqW.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_103_1_o8I.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_104_1_eqh.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_105_1_vBJ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_106_1_2X2.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_107_1_g0H.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_108_1_WKZ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_109_1_lFp.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_10_1_ecQ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_110_1_PUP.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_111_1_Stp.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_112_1_1E6.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_113_1_8vY.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_114_1_STO.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_115_1_E4V.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_116_1_Wra.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_117_1_lP4.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_118_1_yeD.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_119_1_pkc.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_11_1_aXK.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_120_1_G1P.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_121_1_I99.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_122_1_X9s.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_123_1_fwT.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_124_1_zY8.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_125_1_ic6.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_126_1_K5t.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_127_1_ghd.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_128_1_cC1.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_129_1_POW.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_12_1_CwP.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_130_1_BUt.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_131_1_nar.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_132_1_5iB.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_133_1_ofH.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_134_1_sEv.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_135_1_1ls.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_136_1_vbW.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_137_1_yhT.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_138_1_pup.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_139_1_DwE.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_13_1_qMS.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_140_1_Q5t.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_141_1_j7H.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_142_1_KWt.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_143_1_9pb.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_144_1_OsK.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_145_1_5MO.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_146_1_CT7.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_147_1_AFE.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_148_1_xGX.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_149_1_bm3.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_14_1_m6r.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_150_1_uye.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_151_1_sgW.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_152_1_uSF.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_153_1_We3.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_154_1_sjN.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_155_1_2JG.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_156_1_pUB.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_157_1_yrA.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_158_1_1LE.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_159_1_wVj.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_15_1_Qx6.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_160_1_Co2.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_161_1_Ujf.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_162_1_0FD.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_163_1_v6L.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_164_1_1WN.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_165_1_Xx3.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_166_1_0Hf.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_167_1_ejx.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_168_1_w19.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_169_1_QPT.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_16_1_XSL.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_170_1_Zkv.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_171_1_yRM.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_172_1_fuO.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_173_1_diQ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_174_1_cGX.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_175_1_cpY.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_176_1_Hh5.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_177_1_zzk.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_178_1_f7T.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_179_1_Gh3.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_17_1_Jmk.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_180_1_WR3.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_181_1_1kC.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_182_1_Hc5.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_183_1_s5f.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_184_1_b5M.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_185_1_1yQ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_186_1_QSz.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_187_1_rs8.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_188_1_NFw.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_189_1_FkX.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_18_1_U9h.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_190_1_vaR.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_191_1_DxS.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_192_1_TC8.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_193_1_Qfj.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_194_1_4v3.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_195_1_6ac.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_196_1_IqI.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_197_1_4SL.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_198_1_nGl.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_199_1_0wD.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_19_1_1uj.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_1_1_sZX.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_200_1_SSI.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_20_1_ppy.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_21_1_KR9.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_22_1_RZL.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_23_1_iQV.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_24_1_Ean.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_25_1_txt.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_26_1_kxw.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_27_1_u38.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_28_1_Ue9.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_29_1_9fD.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_2_1_5eH.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_30_1_pm9.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_31_1_69v.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_32_1_YNL.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_33_1_aRD.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_34_1_7VY.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_35_1_Kl7.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_36_1_Z42.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_37_1_gXK.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_38_1_Y9W.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_39_1_FA1.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_3_1_XU0.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_40_1_Aun.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_41_1_Vpj.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_42_1_AIM.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_43_1_iAr.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_44_1_6k4.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_45_1_QOk.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_46_1_Xeh.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_47_1_yA5.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_48_1_S8W.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_49_1_MvZ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_4_1_MZN.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_50_1_Dc7.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_51_1_JKb.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_52_1_jm6.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_53_1_Lii.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_54_1_un1.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_55_1_oeV.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_56_1_l0p.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_57_1_xhE.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_58_1_0Gv.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_59_1_gG7.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_5_1_GGk.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_60_1_1EI.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_61_1_fwg.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_62_1_j3Y.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_63_1_w0P.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_64_1_K8N.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_65_1_gk4.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_66_1_qVA.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_67_1_fpo.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_68_1_Ybg.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_69_1_baC.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_6_1_4Fc.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_70_1_KzV.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_71_1_Vgy.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_72_1_qhF.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_73_1_6OY.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_74_1_O7n.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_75_1_1AH.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_76_1_bLy.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_77_1_Sg8.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_78_1_wdk.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_79_1_ZhE.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_7_1_jHd.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_80_1_NQL.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_81_1_9je.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_82_1_5pU.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_83_1_lAO.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_84_1_axs.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_85_1_LmU.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_86_1_iJR.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_87_1_yAp.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_88_1_9qp.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_89_1_q2S.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_8_1_nq6.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_90_1_Z2B.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_91_1_0cb.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_92_1_JpJ.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_93_1_ysR.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_94_1_1Zm.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_95_1_cJx.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_96_1_XQ9.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_97_1_w5J.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_98_1_2xu.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_99_1_Ctl.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_9_1_enT.root', ) )
# -*- coding: utf-8 -*- """Tests for the similarity measure. MIT License Copyright (c) 2021-2022, Daniel Nagel All rights reserved. """ import os.path import numpy as np import pytest from beartype.roar import BeartypeException import mosaic # Current directory HERE = os.path.dirname(__file__) TEST_FILE_DIR = os.path.join(HERE, 'test_files') def X1_file(): """Define coordinate file.""" return os.path.join(TEST_FILE_DIR, 'X1.dat') def X1(): """Correlated coordinates.""" x = np.linspace(0, np.pi, 1000) return np.array([ np.cos(x), np.cos(x + np.pi / 6), ]).T def X1_result(mode): """Correlated coordinates results.""" return { 'correlation': 0.9697832, 'GY': 0.94966701, 'GY_knn': 0.99995091, 'JSD': 0.67786610, 'NMI_joint': 0.54114068, 'NMI_max': 0.68108618, 'NMI_arithmetic': 0.70225994, 'NMI_geometric': 0.702599541, 'NMI_min': 0.72479244, }[mode] @pytest.mark.parametrize('X, error', [ (np.random.uniform(size=(100, 20)), None), (np.random.uniform(size=(10, 5)), None), (np.random.uniform(size=10), BeartypeException), (np.random.uniform(size=(10, 5, 5)), BeartypeException), ]) def test__standard_scaler(X, error): if not error: Xscaled = mosaic.similarity._standard_scaler(X) np.testing.assert_array_almost_equal( np.mean(Xscaled), np.zeros_like(Xscaled), ) np.testing.assert_array_almost_equal( np.std(Xscaled), np.ones_like(Xscaled), ) else: with pytest.raises(error): mosaic.similarity._standard_scaler(X) @pytest.mark.parametrize('metric, kwargs, X, result, error', [ ('correlation', {}, X1(), X1_result('correlation'), None), ( 'correlation', {'low_memory': True}, X1_file(), X1_result('correlation'), None, ), ('GY', {}, X1(), X1_result('GY'), None), ('GY', {'use_knn_estimator': True}, X1(), X1_result('GY_knn'), None), ('JSD', {}, X1(), X1_result('JSD'), None), ('NMI', {}, X1(), X1_result('NMI_geometric'), None), ('NMI', {'normalize_method': 'joint'}, X1(), X1_result('NMI_joint'), None), ('NMI', {'normalize_method': 'max'}, X1(), X1_result('NMI_max'), None), ( 'NMI', {'normalize_method': 'arithmetic'}, X1(), X1_result('NMI_arithmetic'), None, ), ( 'NMI', {'normalize_method': 'geometric'}, X1(), X1_result('NMI_geometric'), None, ), ('NMI', {'normalize_method': 'min'}, X1(), X1_result('NMI_min'), None), ( 'correlation', {'normalize_method': 'joint'}, X1(), None, NotImplementedError, ), ( 'correlation', {'use_knn_estimator': True}, X1(), None, NotImplementedError, ), ('correlation', {'low_memory': True}, X1(), None, TypeError), ('correlation', {}, X1()[:, 0], None, ValueError), ('correlation', {}, X1_file(), None, TypeError), ('NMI', {'low_memory': True}, X1_file(), None, NotImplementedError), ]) def test_Similarity(metric, kwargs, X, result, error): if not error: sim = mosaic.Similarity(metric=metric, **kwargs) sim.fit(X) np.testing.assert_almost_equal( sim.matrix_[-1, 0], result, ) np.testing.assert_almost_equal( sim.fit_transform(X)[-1, 0], result, ) np.testing.assert_almost_equal( sim.transform(X)[-1, 0], result, ) else: with pytest.raises(error): sim = mosaic.Similarity(metric=metric, **kwargs) sim.fit(X) @pytest.mark.parametrize('metric, X, kwargs', [ ('correlation', X1(), {}), ('correlation', X1_file(), {'low_memory': True}), ]) def test__reset(metric, X, kwargs): sim = mosaic.Similarity(metric=metric, **kwargs) sim.fit(X) assert hasattr(sim, 'matrix_') sim._reset() assert not hasattr(sim, 'matrix_')
""" Lazy evaluation常被译为“延迟计算”或“惰性计算”,指的是仅仅在真正需要执行的时候才计算表达式的值。 充分利用Lazy evaluation的特性带来的好处主要体现在以下两个方面: 1)避免不必要的计算,带来性能上的提升。对于Python中的条件表达式if x and y, 在x为false的情况下y表达式的值将不再计算。而对于if x or y, 当x的值为true的时候将直接返回,不再计算y的值。因此编程中应该充分利用该特性。 """ """ 2)节省空间,使得无限循环的数据结构成为可能。Python中最典型的使用延迟计算的例子就是生成器表达式了,它仅在每次需要计算的时候才通过yield产生所需要的元素。 斐波那契数列在Python中实现起来就显得相当简单,而while True也不会导致其他语言中所遇到的无限循环的问题。 """ def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b from itertools import islice print(list(islice(fib(), 5)))
#Komputer ma za zadanie zgadnąć liczbę import random #Welcome and intruct print("HELLO!!! \nPlease think about some number in range from 1 to 100. Computer will try to guess the number") print("Give a clues to computer if guess number is higher or lower than your\n\n") # Function which takes tries counter def guessing(tries = 1): min = 1 max = 100 guess = random.randint(min, max) print(guess) result = None while result != "OK": result = input("\n\nYour number is higher than given by computer, lower or OK? ") if result == "higher": min = guess guess = random.randint(min, max) print(guess) elif result == "lower": max = guess guess = random.randint(min, max) print(guess) elif result == "OK": print("\nComputer guessed your number in",tries,"attempts") tries += 1 guessing() input("\n\nPlease press enter key if you want exit\n\n")
import itertools import datetime import calendar def find_december_monday(currentYear): month = 12 dates = [] for year in range(currentYear, 2008, -1): day = 1 if calendar.weekday(year, month, day) == calendar.MONDAY: day += 7 dates.append(str(year) + '/' + str(month) + '/' + str(day)) elif calendar.weekday(year, month, day + 1) == calendar.MONDAY: day += 8 dates.append(str(year) + '/' + str(month) + '/' + str(day)) else: for day in range(3, 8): if calendar.weekday(year, month, day) == calendar.MONDAY: dates.append(str(year) + '/' + str(month) + '/' + str(day)) return dates
""" Unlike ReqMgr1 defining Request and RequestSchema classes, define just 1 class. Derived from Python dict and implementing necessary conversion and validation extra methods possibly needed. TODO/NOTE: 'inputMode' should be removed by now (2013-07) since arguments validation #4705, arguments which are later validated during spec instantiation and which are not present in the request injection request, can't be defined here because their None value is not allowed in the spec. This is the case for e.g. DbsUrl, AcquisitionEra This module should probably define only absolutely necessary request parameters and not any optional ones. """ from __future__ import print_function, division import time import cherrypy from WMCore.ReqMgr.DataStructs.RequestStatus import REQUEST_START_STATE from WMCore.ReqMgr.DataStructs.RequestError import InvalidSpecParameterValue from WMCore.Lexicon import identifier ARGS_TO_REMOVE_FROM_ORIGINAL_REQUEST = \ ["_id", "_rev", "Requestor", "ReqMgr2Only", "RequestTransition", "RequestStatus", "RequestorDN", "MaxRSS", "MaxVSize", "IgnoredOutputModules", "TrustSitelists", "TrustPUSitelists", "HardTimeout", "GracePeriod", "SoftTimeout", "MaxWaitTime", "Team", "Teams", "SiteWhitelist", "SiteBlacklist", "EnableNewStageout", "DeleteFromSource", "OutputDatasets", "Dashboard", "SoftwareVersions", "VoRole", "DN", "TotalEstimatedJobs", "TotalInputEvents", "TotalInputLumis", "TotalInputFiles"] def initialize_request_args(request, config, clone=False): """ Request data class request is a dictionary representing a being injected / created request. This method initializes various request fields. This should be the ONLY method to manipulate request arguments upon injection so that various levels or arguments manipulation does not occur across several modules and across about 7 various methods like in ReqMgr1. request is changed here. """ # user information for cert. (which is converted to cherry py log in) request["Requestor"] = cherrypy.request.user["login"] request["RequestorDN"] = cherrypy.request.user.get("dn", "unknown") # service certificates carry @hostname, remove it if it exists request["Requestor"] = request["Requestor"].split('@')[0] # assign first starting status, should be 'new' request["RequestStatus"] = REQUEST_START_STATE request["RequestTransition"] = [{"Status": request["RequestStatus"], "UpdateTime": int(time.time()), "DN": request["RequestorDN"]}] request["RequestDate"] = list(time.gmtime()[:6]) if clone: # if it is clone parameter should contain requestName request["OriginalRequestName"] = request["RequestName"] # TODO: generate this automatically from the spec # generate request name using request generateRequestName(request) if not clone: # update the information from config request["CouchURL"] = config.couch_host request["CouchWorkloadDBName"] = config.couch_reqmgr_db request["CouchDBName"] = config.couch_config_cache_db request.setdefault("SoftwareVersions", []) if "CMSSWVersion" in request and request["CMSSWVersion"] not in request["SoftwareVersions"]: request["SoftwareVersions"].append(request["CMSSWVersion"]) # TODO # do we need InputDataset and InputDatasets? when one is just a list # containing the other? ; could be related to #3743 problem if "InputDataset" in request: request["InputDatasets"] = [request["InputDataset"]] def initialize_resubmission(request_args, config, reqmgr_db_service): request_args["OriginalRequestCouchURL"] = '%s/%s' % (config.couch_host, config.couch_reqmgr_db) requests = reqmgr_db_service.getRequestByNames(request_args["OriginalRequestName"]) resubmission_args = requests.values()[0] for arg in resubmission_args: if (arg not in request_args) and (arg not in ARGS_TO_REMOVE_FROM_ORIGINAL_REQUEST): request_args[arg] = resubmission_args[arg] return request_args def generateRequestName(request): currentTime = time.strftime('%y%m%d_%H%M%S', time.localtime(time.time())) seconds = int(10000 * (time.time() % 1.0)) if "RequestString" not in request: raise InvalidSpecParameterValue("RequestString need to be specified") request["RequestName"] = "%s_%s" % (request["Requestor"], request["RequestString"]) # add time info request["RequestName"] += "_%s_%s" % (currentTime, seconds) # then validate the final request name identifier(request["RequestName"])
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='pyrunjs', version='1.0.3', description='Python PyV8 JS wrapper', author='Sergey V. Sokolov', author_email='sergey.sokolov@air-bit.eu', url='https://github.com/sokolovs/pyrunjs', packages=find_packages(exclude=['examples']), package_data={'runjs': ['data/*.*']}, install_requires=['pyduk @ git+https://git.air-bit.eu/airbit/pyduk@0.2.1', 'pyv8 @ git+https://git.air-bit.eu/airbit/pyv8@prebuilt-ubuntu-x64-0.2.1'], dependency_links=['git+https://git.air-bit.eu/airbit/pyduk@0.2.1#egg=pyduk', 'git+https://git.air-bit.eu/airbit/pyv8@prebuilt-ubuntu-x64-0.2.1#egg=pyv8'], )
# -*- encoding: utf-8 -*- import netsvc import pooler, tools import math from tools.translate import _ from osv import fields, osv import wizard import decimal_precision as dp import time class conai_cod(osv.osv): _name = "conai.cod" _description = "Codici CONAI" _columns = { 'name':fields.char('Codice Conai', size=15, required=True), 'descrizione':fields.char('Descrizione Imballo', size=100, required=True), 'valore':fields.float('Valore Unitario ', digits=(2, 7), required=True), } conai_cod() class conai_esenzioni(osv.osv): _name = "conai.esenzioni" _description = "Esenzioni Conai" _columns = { 'name':fields.char('Codice Esenzione', size=10, required=True), 'descrizione':fields.char('Descrizione Esenzione', size=50, require=True), 'perc':fields.float('Percentuale di Esenzione', required=False) , } conai_esenzioni()
import matplotlib.pyplot as plt import numpy as np import math import scipy from scipy import stats filename = 'airbnb_msoa' def my_hist(data, n): plt.hist(data, n) plt.show() def my_plot(data): plt.plot(data) plt.show() msoa_cd_nm_map = {} with open('all_msoas', 'r') as infile: for line in infile: if len(line) > 10: line.replace('\n','') msoa_nm = line.split(':')[0] msoa_cd = line.split(':')[1] msoa_cd_nm_map[msoa_cd[:-1]] = msoa_nm years = ['11','12','13','14','15','16'] all_years = {} for i in range(len(years)): all_years[years[i]] = {} for code in msoa_cd_nm_map: all_years[years[i]][code] = 0 with open(filename) as infile: for line in infile: data = line[:-1].split(',') if data[5] in all_years[data[3]]: all_years[data[3]][data[5]] += 1 with open("year_msoacd_airbnb.csv", 'w') as output_file: for year in all_years: if int(year) > 13: my_data = [] my_order = [] for msoa_cd in all_years[year]: value = int(all_years[year][msoa_cd]) my_data.append(float(value)*10 + 1) my_order.append(msoa_cd) my_data = [math.log(x + .1, 500000) for x in my_data] my_data = [np.log(x) for x in my_data] my_data = [np.log(x + 10) for x in my_data] my_data, _ = scipy.stats.boxcox([x + .5 for x in my_data]) my_data = scipy.stats.zscore(my_data) my_hist(my_data, 6) for i in range(len(my_order)): buffer_str = '20' + year buffer_str += ',' + str(my_order[i]) buffer_str += ',' + str(my_data[i]) buffer_str += '\n' output_file.write(buffer_str)
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtGui import * import shutil import os class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(437, 387) MainWindow.setFixedSize(MainWindow.size()) MainWindow.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0.130864, y1:0.131, x2:0.92, y2:0.903409, stop:0 rgba(59, 227, 209, 255), stop:1 rgba(255, 255, 255, 255));") MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded) MainWindow.setWindowIcon(QtGui.QIcon('icon.png')) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(20, 60, 171, 51)) self.pushButton.setStyleSheet("font: 75 12pt \"Calibri\";\n" "color: rgb(0, 0, 127);\n" "background-color: rgb(255, 255, 255);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(220, 60, 201, 51)) self.pushButton_2.setStyleSheet("font: 75 12pt \"Calibri\";\n" "color: rgb(170, 0, 127);\n" "background-color: rgb(255, 255, 255);") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(40, 142, 141, 81)) self.pushButton_3.setStyleSheet("font: 75 italic 24pt \"Calibri\";\n" "background-color: rgb(85, 255, 127);\n" "color: rgb(170, 0, 127);") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(220, 142, 141, 81)) self.pushButton_4.setStyleSheet("font: 75 italic 24pt \"Calibri\";\n" "background-color: rgb(85, 255, 127);\n" "color: rgb(170, 0, 127);") self.pushButton_4.setObjectName("pushButton_4") self.progressBar = QtWidgets.QProgressBar(self.centralwidget) self.progressBar.setGeometry(QtCore.QRect(57, 282, 331, 41)) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.pushButton.clicked.connect(self.srcdir) self.pushButton_2.clicked.connect(self.destdir) self.pushButton_3.clicked.connect(self.move) self.pushButton_4.clicked.connect(self.copy) def srcdir(self): dialog = QtWidgets.QFileDialog() self.src = dialog.getExistingDirectory(None, "Select Folder") if self.src=="": QMessageBox.about(self, "Error", "Please specify source directory") def destdir(self): dialog = QtWidgets.QFileDialog() self.dest = dialog.getExistingDirectory(None, "Select Folder") if self.dest=="": QMessageBox.about(self, "Error", "Please specify source directory") def move(self): if os.path.exits(self.src): files = os.listdir(self.src) else: QMessageBox.about(self, "Error", "Please specify source directory") xt = "/Moved_files" if not os.path.exits(os.path.join(self.dest,xt)): os.makedirs(os.path.join(self.dest,xt)) cnt,tot = 1, len(files) self.completed=0 for f in files: self.completed = (cnt*100/tot) shutil.move(self.src + "/" + f, self.dest+"/Moved_files/") self.progressBar.setValue(self.completed) cnt += 1 def copy(self): files1 = os.listdir(self.src) os.makedirs(self.dest+"/Copied_files") cnt1,tot1 = 1, len(files1) self.completed=0 for f in files1: self.completed = (cnt1*100/tot1) shutil.copy(self.src + "/" + f, self.dest+"/Copied_files/") self.progressBar.setValue(self.completed) cnt1 += 1 def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "Select Source directory")) self.pushButton_2.setText(_translate("MainWindow", "Select Destination directory")) self.pushButton_3.setText(_translate("MainWindow", "Move")) self.pushButton_4.setText(_translate("MainWindow","Copy")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
def leap(year): if ((year % 100) %4 == 0): return 1 if((year % 1000) - ((year % 100) % 4 == 0) and (year % 100)==0): return 1 return 0 #print(leap(2019)) def MDYToNumDay(date): #-> int month= date[0] day = date[1] year = date[2] monthDays = [31,28+leap(year),31,30,31,30,31,31,30,31,30,31] numDays = day for i in range(month-1): numDays += monthDays[i] return numDays #print("mMDYToNumDay 1,2,2019: "+MDYToNumDay([1,2,2019])) def numDayToMDY(dayNum,year):# -> month, Day, Year monthDays = [31,28+leap(year),31,30,31,30,31,31,30,31,30,31] for month in range(12): if (dayNum > monthDays[month]): dayNum -= monthDays[month] else: return [month+1,dayNum,year] #print("NumDayToMDY 111,2019: "+numDayToMDY(111,2019)) def relativeDate(numberOfDays, date):#-> date print(date) year = date[2] monthDays = [31,28+leap(date[2]),31,30,31,30,31,31,30,31,30,31] dateDayNumber = MDYToNumDay(date) dateDayNumber += numberOfDays dateNew = numDayToMDY(dateDayNumber,year) if (dateNew[1]<0): dateNew[2] -=1 dateNew[0] = 13 - dateNew[0] i = date[1] i += 31 dateNew[1] += monthDays[dateNew[0]-1] return dateNew #print(relativeDate(-46, [4,21,2019])) #def weekDay(date):# - >int # month= date[0] # day = date[1] # year = date[2] # if (month<3): # month+=10 # d = (year%100)-1 # # else: # month-=2 # d = (year%100) # # c = parseInt((year-d)/100) # f =(day + parseInt(((13*month)-1)/5) + d + parseInt(d/4) + parseInt(c/4) - (2*c))%7 # return f def weekDay(date): # - >int month= date[0] day = date[1] year = date[2] if month<3: month+=10 d = (year%100)-1 else: month-=2 d = (year%100) c = (year-d)//100 f = (day + ((13*month)-1)//5 + d + (d//4) + (c//4) - (2*c))%7 return f #print("weekDay: "+weekDay([1,1,2019])) def calcEaster( year):#->[int] a = (year % 19) b = (year // 100) c = (year % 100) d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30 e = (32 + 2 * (b % 4) + 2 * (c // 4) - d - (c % 4)) % 7 f = d + e - 7 * ((a + 11 * d + 22 * e) // 451) + 114 month = f // 31 day = f % 31 + 1 return month,day,year #print("calcEaster: "+calcEaster(2019)) def allSundays(year):# - >[ [int,int,int,string,string] ] calender = [] for i in range(1-weekDay([1,1,year]),(366+leap(year)),7): # for( i = 1-weekDay([1,1,year])i<(366+leap(year))i+=7): if (i>0): calender.append(numDayToMDY(i,year)) return calender #print("allSundays "+allSundays(2019)) def allDays(year): easter = calcEaster(year) print(7-(weekDay([1,6,year]))) epiphanyA = [1,6,year] if (weekDay([1,6,year])>0): epiphanyA = relativeDate(7-(weekDay([1,6,year])),[1,6,year]) epiphanyB = relativeDate(7,epiphanyA) ashWed = relativeDate(-46,easter) epiphanyC = relativeDate(-3, ashWed) lent = relativeDate(4,ashWed) palm = relativeDate(-7,easter) hThursday = relativeDate(-3,easter) gFriday = relativeDate(-2,easter) #easter pentA = relativeDate(49,easter) trinity = relativeDate(7,pentA) pentB = relativeDate(7,trinity) ref = relativeDate(0-weekDay([10,31,year]),[10,31,year]) saints = relativeDate(7,ref) pentD = relativeDate(7,saints) thanks = relativeDate(0-weekDay([11,3,year]),[11,28,year]) advent = relativeDate(3,thanks) xmas = [12,25,year] sundays = allSundays(year) yearFixedDates = [[epiphanyA,"white","Epiphany First Block"],[epiphanyB,"green","Epiphany Second Block"],[epiphanyC,"white","Epiphany Final Block"],[ashWed,"black","Ash Wednesday"],[lent,"purple","Lent"],[palm,"red","Palm Sunday"],[hThursday,"white","Holy Thursday"],[gFriday,"black","Good Friday"],[easter,"white","Easter"],[pentA,"red","Pentecost First Block"],[trinity,"white","Trinity"],[pentB,"green","Pentecost Second Block"],[ref,"red","Reformation"],[saints,"white","All Saints Day"],[pentD,"green","Pentecost Final Block"],[thanks,"white","Thanks Giving"],[advent,"blue","Advent"],[xmas,"white","Cristmas"]] monthDays = [31,28+leap(year),31,30,31,30,31,31,30,31,30,31] calendar = [[[0,0,0],"white"]] for month in range(12): for day in range(monthDays[month]+1): # for ( day =1day<monthDays[month]+1day++): if (len(yearFixedDates)>0): if (str(yearFixedDates[0][0])+"" == str(sundays[0])+"" ): sundays.pop(0) if (str(yearFixedDates[0][0])+"" == str([month+1,day,year])+"" ): calendar.append(yearFixedDates[0]) yearFixedDates.pop(0) if (str(sundays[0])+"" == str([month+1,day,year])+""): calendar.append([[month+1,day,year],calendar[len(calendar)-1][1]]) sundays.pop(0) calendar.pop(0) return calendar #print(allDays(2019)) yearStart =2013 yearStop = 2019 data = ':"Calendars"::\n' for year in range(yearStart,yearStop): #for (year =yearStartyear<yearStart+10year++): cal = allDays(year) data +='\n"'+year+'"::\n' for x in range(len(cal)): #for ( x =0x<cal.lengthx++): data+= '"'+cal[x][0][0]+'-'+cal[x][0][1]+'" : "'+cal[x][1]+'"\n' if ( not x == cal.length-1): data+="," else: data+="" if (not year == yearStop-1): data+=",\n" data+='' # Data which will write in a file. # Write data in 'Output.txt' . with open('Output.json',"wb") as file: file.write(data) # #def tableGen() : # year = parseInt(document.getElementById("year").value) # myArray =allDays(year) # table = "<p>"+year+"</p><table border=1>" # for(r=0 r<myArray.length r++) : # table += "<tr style='background-color:"+myArray[r][1]+"'>" # for(c=0 c<myArray[r].length c++): # table += "<td>"+myArray[r][c]+"</td>" # # table += "</tr>" # # table += "</table>" # document.getElementById("c").innerHTML = table # #document.addEventListener("DOMContentLoaded", def() : # tableGen() #)
#!/usr/bin/env python # -*- coding: utf-8 -*- # ˅ from tkinter import * from behavioral_patterns.mediator.colleague import Colleague # ˄ class ColleagueTextField(Colleague): # ˅ # ˄ def __init__(self, text_field): self.__text_field = text_field # ˅ super().__init__() self.__text_field.bind('<KeyRelease>', self.__on_key_released) # ˄ # Set enable/disable from the Mediator def set_activation(self, is_enable): # ˅ if is_enable: self.__text_field.configure(state=NORMAL) else: self.__text_field.configure(state=DISABLED) # ˄ def is_empty(self): # ˅ return len(self.__text_field.get()) == 0 # ˄ def __on_key_released(self, event): # ˅ self.mediator.colleague_changed() # ˄ # ˅ # ˄ # ˅ # ˄
#!/usr/bin/env python import os import json import argparse import sys import termtables from .property_reader import PropertyReader from .generator import Generator from .renderer import Renderer def list_projects(config): print("Available generators:") rows = [] for gen, props in config.items(): rows.append([gen, props.get('root_dir', ''), props.get('description', '')]) string = termtables.to_string( rows, header=['Project', 'Root folder', 'Description'], style=termtables.styles.ascii_thin_double, padding=(0, 1), alignment="lcc") print(string) sys.exit(0) def get_parser(): parser = argparse.ArgumentParser( description='Generates boiler plate projects') parser.add_argument('generator', type=str, nargs="?", default='no_gen', help='The name of the template to be\ used for generating the new project') parser.add_argument('direcotry', type=str, default="~/code/", nargs="?", help='The direcotry where the\ new project will be created') parser.add_argument('--list-gen', action='store_true', help='List all the available generators') parser.add_argument('--config', dest='config_dir', action='store', default=None, help='A custom configuraion directory') return parser def main(): parser = get_parser() args = parser.parse_args() data_dir = None config_file = None if args.config_dir is not None: if not os.path.isdir(args.config_dir): print('{} is not a directory!'.format(args.config_dir)) sys.exit(1) if not os.path.isfile(os.path.join(args.config_dir, 'config.json')): print('There is no \'config.json\' in {}!'.format(args.config_dir)) sys.exit(1) data_dir = os.path.abspath(args.config_dir) config_file = os.path.join(args.config_dir, 'config.json') else: config = None data_dir = os.path.expanduser('~/.config/projector') config_file = os.path.join(data_dir, "config.json") if not os.path.isdir(data_dir): print("Configuraion direcotry is missing.\ {} is not a file!".format(data_dir)) sys.exit(1) if not os.path.isfile(config_file): print("Configuraion file is missing.\ {} is not a file!".format(config_file)) sys.exit(1) with open(config_file, 'r') as config_file_fd: config = json.load(config_file_fd) if args.list_gen: list_projects(config) generator = args.generator if generator not in config.keys(): print("There is no defined generator with this name") sys.exit(1) print("Generator in use: " + generator) reader = PropertyReader() renderer = Renderer() gen = Generator(config[generator], reader, renderer, data_dir=data_dir) gen.generate(args.direcotry) if __name__ == '__main__': main()
import numba import numpy as np # import must stay here even if it's not used directly! import pycuda.autoinit import pycuda.driver as cuda from pycuda.compiler import SourceModule import pycuda.gpuarray as gpuarray import nufft_cims import nufft_ref import time import pyfftw import multiprocessing import skcuda import skcuda.linalg import skcuda.fft as cu_fft # import pytest_benchmark BLOCK_SIZE = 1024 start = cuda.Event() end = cuda.Event() num_threads = multiprocessing.cpu_count() # GLOBAL CONSTS b = 0.5993 m = 2 # the GPU kernel mod = SourceModule(""" #include <pycuda-complex.hpp> #include <stdio.h> __global__ void fast_nufft1(float *alpha_re, float *alpha_im, float *omega, int M, float* tau_re, float* tau_im) { int k; k = (threadIdx.x + blockDim.x * blockIdx.x); int j; j = (threadIdx.y + blockDim.y * blockIdx.y); if (k >= M){ return ; } // always single precision float b = 0.5993; int m=2; int q=10; j -= q/2; // consts const float pi = 3.141592653589793; const float denominator = 2 * powf (b * pi, 0.5); float numerator = 0; float add_Re = 0; float add_Im = 0; //int j = 0; int idx = 0; // m is always even - so this is the right formula int offset = (M * m - 1)/2 + 1; //for (j = -q/2; j < q/2 + 1;j++){ idx = lround(omega[k] * 2) + j; numerator = exp(-1*(((m * omega[k] - idx) * (m * omega[k] - idx) / (4*b)))) / denominator; idx = (int) fmod((float)(idx + offset + (m * M)), (float) (M * m)); add_Re = numerator * alpha_re[k]; add_Im = numerator * alpha_im[k]; //tau_im[idx] += add_Im; //tau_re[idx] += add_Re; atomicAdd(&tau_im[idx], add_Im); atomicAdd(&tau_re[idx], add_Re); //} } """) gpu_fft1 = mod.get_function("fast_nufft1") mod2 = SourceModule(""" #include <pycuda-complex.hpp> #include <stdio.h> __global__ void nufft2(int M, int offset, pycuda::complex<float> *alpha, float *omega_x, float *omega_y, int* mu_x, int* mu_y, float* tau_re, float* tau_im) { int k = (threadIdx.x + blockDim.x * blockIdx.x); if (k >= M){ return ; } float b = 0.5993; int m=2; int q=10; int j1 = -q / 2; int j2 = -q / 2; int idx1 = 0; int idx2 = 0; // consts const float pi = 3.141592653589793; const pycuda::complex<float> comp_m(m, 0); const pycuda::complex<float> denominator(4 * b * pi, 0); // inner loop variables pycuda::complex<float> tmp1(0, 0); pycuda::complex<float> tmp2(0, 0); pycuda::complex<float> add; pycuda::complex<float> numerator; for (j1 = -q/2; j1 < q/2 + 1; j1++){ for (j2 = -q/2; j2 < q/2 + 1; j2++ ){ idx1 = mu_x[k] + j1; idx2 = mu_y[k] + j2; idx1 = (idx1 + offset + (m * M)) % (M * m); idx2 = (idx2 + offset + (m * M)) % (M * m); tmp1.real(j1 + mu_x[k]); tmp2.real(j2 + mu_y[k]); numerator = ((comp_m * omega_x[k] - tmp1) * (comp_m * omega_x[k] - tmp1) + (comp_m * omega_y[k] - tmp2) * (comp_m * omega_y[k] - tmp2)) / (4*b); add = (exp(-numerator) / denominator) * alpha[k]; //tau_im[idx1 * (M * m) + idx2] = tau_im[idx1 * (M * m) + idx2] + imag(add); //tau_re[idx1 * (M * m) + idx2] = tau_re[idx1 * (M * m) + idx2] + real(add); atomicAdd(&tau_im[idx1 * (M * m) + idx2], imag(add)); atomicAdd(&tau_re[idx1 * (M * m) + idx2], real(add)); } } } """) gpu_fft2 = mod2.get_function("nufft2") mod2 = SourceModule(""" #include <pycuda-complex.hpp> #include <stdio.h> __global__ void fast_nufft2(int M, float *alpha_re, float *alpha_im, float *omega_x, float *omega_y,float *tau_re, float *tau_im) { int k; k = (threadIdx.x + blockDim.x * blockIdx.x); int j1; j1 = (threadIdx.y + blockDim.y * blockIdx.y); int j2; j2 = (threadIdx.z + blockDim.z * blockIdx.z); float b = 0.5993; int m=2; int q=10; if (k >= M){ // printf("Index is out of bound\\n"); return ; } j1 = j1 - q/2; j2 = j2 - q/2; int idx1 = 0; int idx2 = 0; // consts const float pi = 3.141592653589793; const float denominator = 4 * b * pi; float add_Re = 0; float add_Im = 0; pycuda::complex<float> add; int offset = (M*m - 1)/2 + 1; float numerator = 0; float omega_x_k = omega_x[k]; float omega_y_k = omega_y[k]; idx1 = lround(omega_x_k * m) + j1; idx2 = lround(omega_y_k * m) + j2; numerator = exp(-1*(((m * omega_x_k - idx1) * (m * omega_x_k - idx1) + (m * omega_y_k - idx2) * (m * omega_y_k - idx2)) / (4*b))) / denominator; idx1 = (int)fmod((float)(idx1 + offset + (m * M)), (float)(M*m)); idx2 = (int)fmod((float)(idx2 + offset + (m * M)), (float)(M*m)); add_Re = numerator * alpha_re[k]; add_Im = numerator * alpha_im[k]; atomicAdd(&tau_im[idx1 * (M * m) + idx2], add_Im); atomicAdd(&tau_re[idx1 * (M * m) + idx2], add_Re); } """) fast_gpu_fft2 = mod2.get_function("fast_nufft2") mod4 = SourceModule(""" #include <stdio.h> #include <pycuda-complex.hpp> __global__ void fftshift(pycuda::complex<float>* Source, pycuda::complex<float>* Destination, int size) { int i = (blockIdx.x * blockDim.x + threadIdx.x) % size; int j = (blockIdx.x * blockDim.x + threadIdx.x) / size; // new indices int xc = i + size/2; int yc = j + size/2; // index is bounded by size if (xc >= size){ xc -= size; } if (yc >= size){ yc -= size; } Destination[xc + yc*size].real(real(Source[i + j*size])); Destination[xc + yc*size].imag(imag(Source[i + j*size])); } """) my_fftshift = mod4.get_function("fftshift") class nufft_gpu(): @staticmethod def forward1d(alpha, omega, eps=None): ''' running 1dfft on GPU: calculating the sum: n f(j) = sum alpha(k)*exp(2*pi*i*j*omega(k)/M) k=1 :param alpha: Coefficients in the sums above. Real or complex numbers. :param omega: Sampling frequnecies. Real numbers in the range [-n/2,n/2] :param eps: :return: the sum defined above ''' # kernel parameters (single precision)# omega = omega.astype(np.float32) n = len(alpha) M = n offset = np.ceil((m * M - 1) / 2.) tau_im = pycuda.gpuarray.empty(M * m, dtype=np.float32) tau_re = pycuda.gpuarray.empty(M * m, dtype=np.float32) bdim = (BLOCK_SIZE / 10, 10, 1) gridm = ((n / BLOCK_SIZE + (n % (BLOCK_SIZE) > 0)), 1, 1) alpha_real = np.ascontiguousarray(alpha.real) alpha_imag = np.ascontiguousarray(alpha.imag) gpu_fft1(cuda.In(alpha_real), cuda.In(alpha_imag), cuda.In(omega), np.int32(M), tau_re, tau_im, block=bdim, grid=gridm) tau = tau_re.get() + 1j * tau_im.get() T = np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(tau))) T = T * len(T) low_idx_M = int(-np.ceil((M - 1) / 2.)) high_idx_M = int(np.floor((M - 1) / 2.)) + 1 idx = np.arange(low_idx_M, high_idx_M) E = np.exp(b * (2 * np.pi * idx / (m * M)) ** 2) E = E.flatten(order='F') offset2 = offset + low_idx_M f = T[int(offset2):int(offset2 + M)] * E return f, 0 @staticmethod def forward2d(alpha, omega, eps=None): t0 = time.time() # prepare parameters for running omega2 = omega.astype(np.float32) alpha_real2 = np.ascontiguousarray(alpha.real) alpha_imag2 = np.ascontiguousarray(alpha.imag) M = len(alpha) global size size = M * m # allocating memory for tau if it's the first time this code runs if "tau_im_gpu" not in globals() and "tau_re_gpu" not in globals(): global tau_im_gpu global tau_re_gpu tau_im_gpu = gpuarray.to_gpu(np.zeros([size * size], dtype=np.float32)) tau_re_gpu = gpuarray.to_gpu(np.zeros([size * size], dtype=np.float32)) print "some memory was allocated on GPU" else: tau_im_gpu.fill(0) tau_re_gpu.fill(0) # allocating memory for results if it's the first time this code runs if "T_res_gpu " not in globals() and "T_res_gpu2" not in globals(): global T_res_gpu global T_res_gpu2 T_res_gpu = gpuarray.to_gpu(np.ascontiguousarray(np.zeros([size, size], dtype=np.complex64))) T_res_gpu2 = gpuarray.to_gpu(np.ascontiguousarray(np.zeros([size ,size], dtype=np.complex64))) print "some memory was allocated on GPU" else: # fill arrays in 0's for reuse T_res_gpu.fill(0) T_res_gpu2.fill(0) # the GPU kernel bdim = (BLOCK_SIZE/121, 11, 11) gridm = ((M / bdim[0] + (M % bdim[0] > 0)), 1, 1) fast_gpu_fft2(np.int32(M), cuda.In(alpha_real2), cuda.In(alpha_imag2), cuda.In(omega2[:, 0]), cuda.In(omega2[:, 1]), tau_re_gpu, tau_im_gpu, block=bdim, grid=gridm) tau_gpu = tau_re_gpu + 1j*tau_im_gpu bdim = (min(1024, size*size), 1, 1) gridm = ((len(tau_re_gpu) / bdim[0] + (len(tau_re_gpu) % bdim[0] > 0)), 1, 1) my_fftshift(tau_gpu, T_res_gpu2, np.int32(size), block=bdim, grid=gridm) if "plan" not in globals(): print "Planning" global plan plan = cu_fft.Plan((size, size), np.complex64, np.complex64) if plan.shape != (size, size): print "Planning" global plan plan = cu_fft.Plan((size, size), np.complex64, np.complex64) cu_fft.ifft(T_res_gpu2, T_res_gpu, plan, True) my_fftshift(T_res_gpu, T_res_gpu2, np.int32(size), block=bdim, grid=gridm) T_res_gpu2 *= (size * size) bound = (M - 1) / 2. low_idx_M = -np.ceil(bound) high_idx_M = int(bound) + 1 idx = np.arange(low_idx_M, high_idx_M) E = np.exp(b * (2. * np.pi * idx / (size)) ** 2) E = np.outer(E, E) offset = int(np.ceil((size - 1) / 2.) + low_idx_M) offset2 = offset + M T = T_res_gpu2.get() f = T[offset:offset2, offset: offset2] * E return f, 0 @staticmethod def forward3d(fourier_pts, sig, eps=None): return 0, 0 @staticmethod def adjoint1d(fourier_pts, sig, eps=None): return 0, 0 @staticmethod def adjoint2d(fourier_pts, sig, eps=None): return 0, 0 @staticmethod def adjoint3d(fourier_pts, sig, eps=None): return 0, 0 # def test_my_stuff(benchmark, alpha, omega, inner_block_size=16): # result = benchmark(nufft_gpu.fast_forward1d,arg=(alpha, omega, inner_block_size), iterations=10, rounds=100) if __name__ == "__main__": # delete global variables for x in globals(): del x for i in range(6): n = 33 #alpha = np.arange(-n / 2, n / 2) / float(n) alpha = np.random.uniform(-np.pi, np.pi, n) alpha = alpha.astype(np.complex64) #omega_x = np.arange(-n / 2, n / 2) omega_x = np.random.uniform(-n/2, n/2, n) #omega_y = np.arange(-n / 2, n / 2) omega_y = np.random.uniform(-n / 2, n / 2, n) omega = np.array([omega_x, omega_y]).transpose() # test_my_stuff(benchmark, alpha, omega, 32) ret = nufft_gpu.forward2d(alpha, omega) ret2 = nufft_ref.kernel_nufft_2d(alpha, omega, n) print np.abs(np.sum(np.square(ret[0] - ret2[0]))) / ( len(ret[0]) * len(ret[0])) # ret = nufft_gpu.forward1d(alpha, omega) # ret2 = nufft_ref.slow_forward1d(alpha, omega) # print np.abs(np.sum(np.square(ret[0] - ret2[0]))) / (len(ret[0]))
from typing import Optional, List from orun.db import models from orun.utils.translation import gettext_lazy as _ class MailServer(models.Model): name = models.CharField(128, null=False, unique=True) active = models.BooleanField(default=True, label=_('Active')) sequence = models.IntegerField() smtp_host = models.CharField(null=False) smtp_port = models.IntegerField(null=False, default=25) smtp_user = models.CharField(64) smtp_pwd = models.CharField(64) smtp_encryption = models.ChoiceField( ( ('none', _('None')), ('tls', _('TLS')), ('ssl', _('SSL/TLS')), ), default='none', ) smtp_debug = models.BooleanField(default=False) class Meta: name = 'mail.server' class Channel(models.Model): name = models.CharField(null=False, unique=True) channel_type = models.SelectionField( ( ('chat', 'Chat'), ('channel', 'Channel'), ), default='channel', label=_('Channel Type'), ) description = models.TextField() access = models.SelectionField( ( ('public', 'Everyone'), ('private', 'Invited people only'), ('groups', 'Selected groups of users') ), default='groups', ) partners = models.ManyToManyField('res.partner') groups = models.ManyToManyField('auth.group', label=_('Groups')) moderate = models.BooleanField() class Meta: name = 'mail.channel' def send_to_partner(self, partner, message: str, subject: Optional[str]=None, attachments: Optional[List]=None): pass
# # Some plotting routes to show off the learning agent for the "driverless car" using Tensorflow # # @scottpenberthy # November 1, 2016 # import tensorflow as tf import numpy as np from learning import * import matplotlib import matplotlib.mlab as mlab import matplotlib.cm as cm import matplotlib.pyplot as plt import matplotlib.animation as animation from scipy.signal import convolve2d class Plotter: # We put some plotting routines here that # we used to document performance of our # final model. # # These fight with PyGame for control of the # matplot environment. As a result, you should # load these separately, as follows: # # from plotting import * # # p.contour_plot() # p.angle_v_sensor_plot() # p.theta_anim() # p.sensor_anim() def __init__(self, name='q_value', track=False): # Tf graph input self.ai = Learner(True) self.saver = tf.train.Saver() self.saver.restore(self.ai.s,"models/narrow-deep-pipe.ckpt") self.theta = 0 self.im = None self.fig = None self.sensor = 0 self.smoothing = True matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' def moving_average_2d(self, data, window): """Moving average on two-dimensional data. """ # Makes sure that the window function is normalized. window /= window.sum() # Makes sure data array is a numpy array or masked array. if type(data).__name__ not in ['ndarray', 'MaskedArray']: data = numpy.asarray(data) # The output array has the same dimensions as the input data # (mode='same') and symmetrical boundary conditions are assumed # (boundary='symm'). return convolve2d(data, window, mode='same', boundary='symm') def location_contours(self, sensors=[0.2,0.2,0.2,0.0]): # # Create a mesh grid for 100x100 points within the simulated game. # Store the maximum Q value at each (x,y) location using the # fixed sensor values and car angle (theta) passed into this function. # x = np.arange(0,1,0.01) y = np.arange(0,1,0.01) qt = self.ai.q_train a,b = np.meshgrid(x,y) s1,s2,s3,theta = sensors # this hairball creates an entry in our matrix, storing the # sensor readings, x,y, and theta in the proper order # for evaluating through our network. X = np.concatenate([[[s1, s2, s3, a[:,i][j], b[:,i][j], theta] for i in range(len(a[0]))] for j in range(len(a))]) feed = {qt.x: X, qt.q_max: qt.q_max_val} # use the maximum q value here.. q = self.ai.s.run(tf.reduce_max(qt.q_value, reduction_indices=[1]), feed_dict=feed) # or uncomment and use the chosen action here #q = self.ai.s.run(tf.argmax(qt.q_value, dimension=1), feed_dict=feed) cols = len(a[0]) rows = len(a) c = np.array([[q[i*cols+j] for j in range(cols)] for i in range(rows)]) if self.smoothing: c = self.moving_average_2d(c, np.ones((6,40))) return a,b,c def angle_v_sensor_contours(self, x0=0.5, y0=0.5): # # Create a mesh grid of 100x100 varying from 0-1 on both axes. # Treat the x axis as the angle of the car # Treat the y axis as the sensor level for all 3 sensors # Compute the maximum Q value at a fixed position x0,y0 as supplied, # varying angle and sensor level across the grid. # # x axis varies theta from 0 to 2*pi # y axis varies sensors all from 0 to 1.0 in unison # x = np.arange(0,1,0.01) y = np.arange(0,1,0.01) qt = self.ai.q_train a,b = np.meshgrid(x,y) # this is the ugly hairbal that does the bulk of the work # populating our state values for pushing through the neural network. X = np.concatenate([[[b[:,i][j], b[:,i][j], b[:,i][j], x0, y0, 2*np.pi*a[:,i][j]] for i in range(len(a[0]))] for j in range(len(a))]) feed = {qt.x: X, qt.q_max: qt.q_max_val} q = self.ai.s.run(tf.reduce_max(qt.q_value, reduction_indices=[1]), feed_dict=feed) #q = self.ai.s.run(tf.argmax(qt.q_value, dimension=1), feed_dict=feed) cols = len(a[0]) rows = len(a) c = np.array([[q[i*cols+j] for j in range(cols)] for i in range(rows)]) if self.smoothing: c = self.moving_average_2d(c, np.ones((6,40))) return a,b,c def contour_plot(self, sensors=[0.2,0.2,0.2,0.0], title="Contour Plot of Q(s,a)"): # # Show a contour plot of how Q varies over the geometry of our # play area, while fixing sensor readings and car rotation. # x,y,z = self.location_contours(sensors) plt.figure(facecolor='white') plt.hot() im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8) plt.title(title+": theta="+str(int(sensors[3]*180.0/np.pi))) plt.xlabel('x%') plt.ylabel('y%') plt.show() def angle_v_sensor_plot(self, x0=0.5, y0=0.5, title="Contour Plot of Q(s,a)"): # # Show a contour plot of how Q varies as we change car rotation # and sensor strength at a fixed position (x0,y0) in the game area. # x,y,z = self.angle_v_sensor_contours(x0, y0) plt.figure(facecolor='white') plt.hot() plt.xlabel('Orientation') plt.ylabel('Signal strength') im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8) plt.title(title) plt.show() def update_theta(self, *args): # # Companion to theta_anim, which increments the angle # self.theta += np.pi/20.0 x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta]) self.theta %= (np.pi*2.0) self.im.set_data(z) self.fig.suptitle("Countour Q plot - Heading "+str(int(self.theta*180.0/np.pi))) return self.im def theta_anim(self): # # Animate the contour plot from above by varying theta from 0 to 2*pi # self.theta = 0 x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta]) self.fig = plt.figure() self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8) plt.title('Contour Plot - Q') ani = animation.FuncAnimation(self.fig, self.update_theta, interval=50, blit=False) plt.show() def theta_gif(self): # # Create an animated gif of the contour plot from above by varying theta from 0 to pi # self.theta = 0 x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta]) self.fig = plt.figure() self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8) plt.xlabel('X %') plt.ylabel('Y %') ani = animation.FuncAnimation(self.fig, self.update_theta, frames=np.arange(0,20), interval=200, blit=False) ani.save('figures/theta.gif', dpi=80, writer='imagemagick') def update_sensor(self, *args): # # Companion to sensor_anim, which increments the angle # self.sensor += 0.02 if self.sensor > 1: self.sensor = 0.0 s = self.sensor x,y,z = self.location_contours([s, s, s, self.theta]) self.im.set_data(z) self.fig.suptitle("Countour Q plot - Sensor "+str(self.sensor)) return self.im def sensor_anim(self, theta=0): # # Animate the contour plot by changing sensor values and holding # the angle fixed at theta. # self.theta = theta self.sensor = 0.0 x,y,z = self.location_contours([0,0,0, self.theta]) self.fig = plt.figure() self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8) ani = animation.FuncAnimation(self.fig, self.update_sensor, interval=50, blit=False) plt.show() p = Plotter()
from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime # For datetime objects import os.path # To manage paths import sys # To find out the script name (in argv[0]) # Import the backtrader platform import backtrader as bt from custom_indicators import * from custom_functions import * # Strategy: class TestStrategy(bt.Strategy): def log(self, txt, dt=None): """ Logging Function for This Strategy""" dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) print(self.cross[0]) def __init__(self): self.cheating = self.cerebro.p.cheat_on_open # Keep a reference to "close" line in the data[0] dataseries self.dataclose = self.datas[0].close # Keep track of pending orders self.order = None # Add some idicators it = iTrend(self.datas[0],period=29) self.atr = bt.indicators.ATR() self.cross = bt.ind.CrossOver(it.trigger,it.itrend) def size_position(self, stop_amount, risk, method=0, exchange_rate=None, JPY_pair=False): price = self.data[0] stop = price - stop_amount risk = float(risk)/100.0 if JPY_pair == True: # check if a YEN cross and change the multiplier multiplier = 0.01 else: multiplier = 0.0001 # Calc how much to risk acc_value = self.broker.getvalue() cash_risk = acc_value * risk stop_pips_int = abs((price - stop) / multiplier) pip_value = cash_risk / stop_pips_int if method == 1: # pip_value = pip_value * price units = pip_value / multiplier return units elif method == 2: pip_value = pip_value * exchange_rate units = pip_value / multiplier return units else: # is method 0 units = pip_value / multiplier return units def notify_order(self, order): date = self.data.datetime.datetime().date() if order.status == order.Accepted: print('-' * 32, ' NOTIFY ORDER ', '-' * 32) print('Order Accepted') print('{}, Status {}: Ref: {}, Size: {}, Price: {}'.format( date, order.status, order.ref, order.size, 'NA' if not order.price else round(order.price, 5) )) if order.status == order.Completed: print('-' * 32, ' NOTIFY ORDER ', '-' * 32) print('Order Completed') print('{}, Status {}: Ref: {}, Size: {}, Price: {}'.format( date, order.status, order.ref, order.size, 'NA' if not order.price else round(order.price, 5) )) print('Created: {} Price: {} Size: {}'.format(bt.num2date(order.created.dt), order.created.price, order.created.size)) print('-' * 80) if order.status == order.Canceled: print('-' * 32, ' NOTIFY ORDER ', '-' * 32) print('Order Canceled') print('{}, Status {}: Ref: {}, Size: {}, Price: {}'.format( date, order.status, order.ref, order.size, 'NA' if not order.price else round(order.price, 5) )) if order.status == order.Rejected: print('-' * 32, ' NOTIFY ORDER ', '-' * 32) print('WARNING! Order Rejected') print('{}, Status {}: Ref: {}, Size: {}, Price: {}'.format( date, order.status, order.ref, order.size, 'NA' if not order.price else round(order.price, 5) )) print('-' * 80) def notify_trade(self, trade): date = self.data.datetime.datetime() if trade.isclosed: print('-' * 32, ' NOTIFY TRADE ', '-' * 32) print('{}, Close Price: {}, Profit, Gross {}, Net {}'.format( date, trade.price, round(trade.pnl, 2), round(trade.pnlcomm, 2))) print('-' * 80) def operate(self, fromopen): if self.cross[0] > 0: if self.position: self.close() print('{} Send Buy, fromopen {}, close {}'.format( self.data.datetime.date(), fromopen, self.data.close[0]) ) self.order = self.buy(size=self.size_position( 2.0, 1.0 )) #self.sell(exectype=bt.Order.StopTrail, trailamount=2 * self.atr.atr[0]) elif self.cross[0] < 0: if self.position: self.close() print('{} Send Sell, fromopen {}, close {}'.format( self.data.datetime.date(), fromopen, self.data.close[0]) ) self.order = self.sell(size=self.size_position( 2.0, 1.0 )) #self.buy(exectype=bt.Order.StopTrail, trailamount=2 * self.atr.atr[0]) def next(self): date = self.data.datetime.date() close = self.data.close[0] print('{}: Close: ${}, Position Size: {}'.format(date, close, self.position.size)) # Check to see if an order is pending. If so, we cannot create another if self.order: return if self.cheating: return self.operate(fromopen=True) def next_open(self): if not self.cheating: return self.operate(fromopen=True) if __name__ == '__main__': # Create a cerebro entity cerebro = bt.Cerebro(cheat_on_open=True) # Add our strategy cerebro.addstrategy(TestStrategy) # Datas are in a subfolder of the samples. Need to find where the script is # because it could have been called from anywhere datapath = 'Data/NZDUSD_daily.csv' # Create a Data Feed data = bt.feeds.GenericCSVData( dataname=datapath, openinterest=-1, dtformat='%d.%m.%Y %H:%M:%S.000' ) # Add the Data Feed to Cerebro cerebro.adddata(data) # Set our desired cash start cerebro.broker.setcash(1000.0) # Set Commission: comminfo = forexSpreadCommisionScheme(spread=2, acc_counter_currency=False) cerebro.broker.addcommissioninfo(comminfo) # Print out the starting conditions print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Run over everything cerebro.run() # Print out the final result print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.plot()
from agents import ExpectiMaxAgent from game import * import numpy as np GAME_SIZE = 4 SCORE_TO_WIN = 2048 eposide = 4000 game_train = Game(size=GAME_SIZE, score_to_win=SCORE_TO_WIN) agent = ExpectiMaxAgent(game_train) txt_dir = "./dataset2/data0.txt" index = 0 file = open(txt_dir, mode='w') for ep in range(eposide): _ = game_train.reset() if ep % 10 == 0 and ep != 0: index += 1 txt_dir = "./dataset2/data" + str(index) + ".txt" file.close() file = open(txt_dir, mode='w') while game_train.end == 0: state = game_train.board max_score = np.max(state) state_print = np.reshape(state, [1, 16]).squeeze() action = agent.step() game_train.move(action) for _ in range(4): print(state_print, " ", action, file=file) state = np.rot90(state) action = (action + 1) % 4 state_print = np.reshape(state, [1, 16]).squeeze() """ if max_score >= 16: max_score = 1024 / max_score else: max_score = 64 while max_score != 0: print(state, " ", action, file=file) max_score -= 1 """
l1 = [1, 2, 2, 2, 3, 3, 4, 56, 61, 78] l2 = [] for i in l1: if i not in l2: l2.append(i) print(l2)
import torch from torchvision.datasets import Omniglot import albumentations as albu from albumentations.core.transforms_interface import DualTransform from albumentations.augmentations import functional as F from albumentations.pytorch.transforms import ToTensorV2 import cv2 import numpy as np class RandomResize(DualTransform): def __init__(self, h_resize_limit=1., w_resize_limit=1., interpolation=cv2.INTER_LINEAR, always_apply=False, p=1): super(RandomResize, self).__init__(always_apply, p) if isinstance(h_resize_limit, float): assert 0. <= h_resize_limit <= 1. self.h_resize_limit = 1 - abs(h_resize_limit), 1 + abs(h_resize_limit) elif isinstance(h_resize_limit, tuple) or isinstance(h_resize_limit, list): assert all(list(map(lambda x: isinstance(x, float), h_resize_limit))) assert all(list(map(lambda x: 0. <= x, h_resize_limit))) assert h_resize_limit[0] < h_resize_limit[1] self.h_resize_limit = h_resize_limit else: raise ValueError if isinstance(w_resize_limit, float): assert 0. <= w_resize_limit <= 1. self.w_resize_limit = 1 - abs(w_resize_limit), 1 + abs(w_resize_limit) elif isinstance(w_resize_limit, tuple) or isinstance(w_resize_limit, list): assert all(list(map(lambda x: isinstance(x, float), w_resize_limit))) assert all(list(map(lambda x: 0. <= x, w_resize_limit))) assert w_resize_limit[0] < w_resize_limit[1] self.w_resize_limit = w_resize_limit else: raise ValueError self.interpolation = interpolation def get_params(self): return { 'h_scale': np.random.uniform(self.h_resize_limit[0], self.h_resize_limit[1]), 'w_scale': np.random.uniform(self.w_resize_limit[0], self.w_resize_limit[1]) } def apply(self, img, interpolation=cv2.INTER_LINEAR, **params): h, w = int(params['h_scale'] * img.shape[0]), int(params['w_scale'] * img.shape[1]) return F.resize(img, height=h, width=w, interpolation=interpolation) def apply_to_bbox(self, bbox, **params): return bbox def get_transform_init_args_names(self): return ("h_resize_limit", "w_resize_limit", "interpolation") class Patch: def __init__(self, root): self.dataset = Omniglot( root=root, background=True, transform=lambda x: 255 - np.array(x) ) self.W, self.H = 420, 420 self.transform = albu.Compose([ albu.Rotate(limit=20, border_mode=cv2.BORDER_CONSTANT, value=0, always_apply=True), RandomResize(h_resize_limit=[0.7, 1.5], w_resize_limit=[0.7, 1.5], p=1.) ], bbox_params=albu.BboxParams(format='coco', label_fields=['bbox_cats'])) self.cats_dict = [{'id': i, 'name': label} for i, label in enumerate(self.dataset._characters)] data = list(map(list, zip(*[elem for elem in self.dataset]))) x = np.array(data[0]) y = np.array(data[1]) x = x.astype(np.float32) / 255. self.x = x self.y = y self.all_idxs = np.arange(len(y)) def get_sample(self, img): def coco_target(bboxes, bbox_cats): target = [] for bbox, bbox_cat in zip(bboxes, bbox_cats): target.append( { 'bbox': bbox, 'category_id': bbox_cat[0] } ) return target image = np.zeros((self.H, self.W, 3), dtype=np.uint8) patches, bboxes, bbox_cats = self._locate_pathces(idxs=self.idxs) for patch, bbox in zip(patches, bboxes): if self.dataset.is_colourful: colour = np.random.randint(1, 256, size=(3,)) else: colour = 255 image[self._get_slice(*bbox)] = \ colour * np.stack((patch,) * self.n_channels, axis=2) target = coco_target(bboxes, bbox_cats) return image, target def _locate_patches(self, img, idxs): def valid(bbox): x, y, w, h = bbox if x < 0 or x + w > self.W: return False if y < 0 or y + h > self.H: return False return True def overlap(bboxes, bbox): # bboxes in coco format [x_l, y_t, w, h] if len(bboxes) == 0: return False coords = np.asarray(bboxes)[:, :2] coord = np.asarray(bbox)[np.newaxis, :2] distances = (coords - coord) sizes = np.asarray(bboxes)[:, 2:] size = np.asarray(bbox)[np.newaxis, 2:] limits = np.where(distances < 0, sizes, size) axis_overlap = abs(distances) < limits return np.logical_and(axis_overlap[:, 0], axis_overlap[:, 1]).any() patches = [] bboxes = [] bbox_cats = [] for idx in idxs: patch = self.x[idx] bbox = [0, 0, 105, 105] bbox_cat = [int(self.dataset.y[idx])] transformed = self.dataset.transform(image=patch, bboxes=[bbox], bbox_cats=[bbox_cat]) patch, bbox = transformed['image'], transformed['bboxes'][0] i = 1 while i < 5000: i += 1 x_l, y_t = np.round(np.random.rand(2) * [self.dataset.W - bbox[1], self.dataset.H - bbox[2]]) bbox = tuple(map(int, (x_l, y_t, bbox[2], bbox[3]))) if valid(bbox) and not overlap(bboxes, bbox): break patches.append(patch) bboxes.append(bbox) bbox_cats.append(bbox_cat) if i == 5000: patches.pop(), bboxes.pop(), bbox_cats.pop() return patches, bboxes, bbox_cats def __call__(self, s_img): n_patches = np.random.randint(low=1, high=4) result = [] idxs = np.random.choice(self.all_idxs, size=n_patches) def preprocess_input(image_list): """ :param image_list: List[PIL.Image]. image_list[0] - query, image_list[1:] - supports :return: result (dict): input sample to model sampe['q_img'] (torch.Tensor): query image (1xCxHxW) sampe['s_imgs'] (torch.Tensor): support set images (1xKxCxHxW) sampe['s_bboxes'] (List[List[List[float, ..]]]): bbox coordinates for support set images (conditionally 1xKxVx4, K - length of support set V - number of instances per image) """ q_img = image_list[0] s_imgs = image_list[1:] s_bboxes = [[[0, 0, 105, 105, 1]] for _ in range(3)] q_transform = albu.Compose([ albu.Resize(320, 320), albu.Normalize(), ToTensorV2() ]) s_transform = albu.Compose([ albu.PadIfNeeded(420, 420, border_mode=cv2.BORDER_CONSTANT, value=0), albu.Resize(320, 320), albu.Normalize(), ToTensorV2(), ], bbox_params=albu.BboxParams(format='coco')) q_img = q_transform(image=q_img)['image'] s_transformed = [s_transform(image=s_img, bboxes=s_bbox) for s_img, s_bbox in zip(s_imgs, s_bboxes)] s_imgs = [transformed['image'] for transformed in s_transformed] s_bboxes = [transformed['bboxes'] for transformed in s_transformed] s_bboxes = [[s_bbox[0][:-1]] for s_bbox in s_bboxes] q_img = torch.unsqueeze(q_img, dim=0) s_imgs = torch.stack(s_imgs) s_imgs = torch.unsqueeze(s_imgs, dim=0) s_bboxes = [[[s_bbox for s_bbox in b_s_bbox] for b_s_bbox in s_bboxes]] result = { 'q_img': q_img, 's_imgs': s_imgs, 's_bboxes': s_bboxes } return result
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import os import logging import lmdb import msgpack from ..util import time_uuid from ..runtime import environ from .errors import DataNotFoundError, DataError from .service import IStore, ICursor _DATA_FILE_DIR = b'data' logger = logging.getLogger(__name__) class Store(IStore): def __init__(self, name, _db, _engine): self.name = name self._db = _db self._engine = _engine def __len__(self): with self._engine.database.begin() as txn: stat = txn.stat(self._db) return stat['entries'] def __getitem__(self, key): with self._engine.cursor(self.name) as cur: return cur.get(key) def __setitem__(self, key, value): with self._engine.cursor(self.name, readonly=False) as cur: cur.put(key, value) def __delitem__(self, key): with self._engine.cursor(self.name, readonly=False) as cur: cur.remove(key) def __iter__(self): return self._engine.cursor(self.name).iternext() def __contains__(self, key): with self._engine.cursor(self.name, readonly=True) as cur: return cur.seek(key) def put(self, key, value): with self._engine.cursor(self.name, readonly=False) as cur: return cur.put(key, value) def get(self, key): with self._engine.cursor(self.name, readonly=True) as cur: return cur.get(key) def remove(self, key): with self._engine.cursor(self.name, readonly=False) as cur: return cur.remove(key) def cursor(self, readonly=True): _write = not readonly assert self._db is not None _txn = self._engine.database.begin(db=self._db, write=_write, buffers=False) return Cursor(_txn, self._db, _readonly=readonly) class Cursor(ICursor): def __init__(self, _txn, _db, _readonly=True): self._txn = _txn self._db = _db self._readonly = _readonly self._cursor = lmdb.Cursor(_db, _txn) def __enter__(self, *args, **kwargs): self._txn.__enter__(*args, **kwargs) self._cursor.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): self._cursor.__exit__(exc_type, exc_val, exc_tb) self._txn.__exit__(exc_type, exc_val, exc_tb) def first(self): return self._cursor.first() def next(self): return self._cursor.next() def prev(self): return self._cursor.prev() def last(self): return self._cursor.last() def iternext(self, keys=True, values=False): return self._cursor.iternext(keys=keys, values=values) def iterprev(self, keys=True, values=False): return self._cursor.iterprev(keys=keys, values=values) def close(self): self._cursor.close() def value(self): """ Gets raw value of the record. :return: record's value. """ return msgpack.unpackb(self._cursor.value(), use_list=False) def key(self): return self._cursor.key() def get(self, key): if isinstance(key, unicode): key = key.encode('utf-8') if not self._cursor.set_key(key): return None return msgpack.unpackb(self._cursor.value(), use_list=False) def load(self, key): """ Same as get method, except raising exception if entry not found. :param _key: item key. :return: the value. """ ret = self.get(key) if ret is None: raise DataNotFoundError() return ret def delete(self): """ Actually deletes document and its revisions if required. :return: """ return self._cursor.delete(True) def remove(self, key): """ Delete the current element and move to the next, returning True on success or False if the store was empty :return: """ if isinstance(key, unicode): key = key.encode('utf-8') if not self._cursor.set_key(key): return False return self._cursor.delete(True) def seek(self, key): """ Finds the document with the provided ID and moves position to its first revision. :param key: :return: True if found; False, otherwise. """ if isinstance(key, unicode): key = key.encode('utf-8') return self._cursor.set_key(key) def seek_range(self, key): """ Finds the document whose ID is greater than or equal to the provided ID and moves position to its first revision. :param key: :return: """ if isinstance(key, unicode): key = key.encode('utf-8') return self._cursor.set_range(key) def post(self, value): key = time_uuid.utcnow().hex if self._cursor.put(key, msgpack.packb(value)): return key return None def pop(self): """ Fetch the first document then delete it. Returns None if no value existed. :return: """ if self._cursor.first(): value = self._cursor.pop(self._cursor.key()) if value is None: return None return msgpack.unpackb(value, use_list=False) def put(self, key, value): if isinstance(key, unicode): key = key.encode('utf-8') return self._cursor.put(key, msgpack.packb(value)) def exists(self, key): if isinstance(key, unicode): key = key.encode('utf-8') if self._cursor.set_key(key): return True return False class DataEngine(object): def __init__(self, datapath=None): logger.debug("Initializing data engine...") self.datapath = datapath self.database = None self.stores = {} def start(self, ctx=None): logger.debug("Starting data engine...") # register with the context if ctx: ctx.bind('dataengine', self) if not self.datapath: self.datapath = os.path.join(environ.data_dir(), 'stores') if not os.path.exists(self.datapath): os.makedirs(self.datapath) logger.debug("Data path: %s", self.datapath) try: self.database = lmdb.Environment(self.datapath, map_size=2000000000, max_dbs=1024) with self.database.begin(write=False) as txn: cur = txn.cursor() for k, v in iter(cur): logger.debug("Found existing store: %s", k) _db = self.database.open_db(k, create=False) self.stores[k] = Store(k, _db, self) except lmdb.Error: logger.exception("Failed to open database.", exc_info=True) raise logger.debug("Data engine started.") def stop(self, ctx=None): logger.debug("Stopping data engine...") if self.database: self.database.close() self.database = None logger.debug("Data engine stopped.") def store_names(self): return self.stores.keys() def create_store(self, name): if isinstance(name, unicode): name = name.encode('utf-8') try: _db = self.database.open_db(name, dupsort=False, create=True) store = Store(name, _db, self) self.stores[name] = store return store except lmdb.Error as ex: logger.exception(ex) raise DataError(ex.message) def get_store(self, name, create=True): result = self.stores.get(name) if result is None and create: return self.create_store(name) return result def remove_store(self, name): try: store = self.stores.get(name) if store is not None: with self.database.begin(write=True) as txn: txn.drop(store._db) del self.stores[name] except lmdb.Error as ex: logger.exception("Failed to remove store.", ex) raise DataError(ex.message) def remove_all_stores(self): for name in self.stores.keys(): self.remove_store(name) def store_exists(self, name): return name in self.stores def cursor(self, store_name, readonly=True): if isinstance(store_name, unicode): store_name = store_name.encode('utf-8') store = self.get_store(store_name, create=False) return store.cursor(readonly=readonly) def stat(self): ret = self.database.stat() return ret def __iter__(self): return self.stores.iterkeys() def __getitem__(self, store_name): return self.get_store(store_name) def __delitem__(self, store_name): return self.remove_store(store_name)
# -*- coding: utf-8 -*- """ Created on Wed Jun 28 14:38:04 2017 @author: Martin """ from textblob import TextBlob wiki = TextBlob("I like to eat pizza") wiki.tags
import ipfsapi import asyncio import aiohttp import logging from nulsexplorer.modules.register import register_tx_type, register_tx_processor LOGGER = logging.getLogger('ipfs_module') async def add_file(fileobject, filename): async with aiohttp.ClientSession() as session: from nulsexplorer.web import app url = "http://%s:%d/api/v0/add" % (app['config'].ipfs.host.value, app['config'].ipfs.port.value) data = aiohttp.FormData() data.add_field('path', fileobject, filename=filename) resp = await session.post(url, data=data) return await resp.json() async def get_ipfs_api(): from nulsexplorer.web import app host = app['config'].ipfs.host.value port = app['config'].ipfs.port.value return ipfsapi.connect(host, port) async def get_json(hash): loop = asyncio.get_event_loop() api = await get_ipfs_api() result = await loop.run_in_executor( None, api.get_json, hash) return result async def add_json(value): loop = asyncio.get_event_loop() api = await get_ipfs_api() result = await loop.run_in_executor( None, api.add_json, value) return result async def process_transfer_ipfs_remark(tx): # This function takes a tx dict and modifies it in place. # we assume we have access to a config since we are in a processor from nulsexplorer.web import app if tx.remark.startswith(b'IPFS;'): parts = tx.remark.split(b';') info = { 'type': 'ipfs', 'success': False } if app['config'].ipfs.enabled.value: try: if parts[1] == b"A": # Ok, we have an aggregate. # Maybe check object size to avoid ddos attack ? info['aggregate'] = await get_json(parts[2]) elif parts[1] == b"P": info['post'] = await get_json(parts[2]) else: info['extended'] = await get_json(parts[1]) info['success'] = True except Exception as e: LOGGER.warning("Can't retrieve the ipfs hash %s" % parts[1]) LOGGER.exception(e) tx.module_data.update(info) register_tx_processor(process_transfer_ipfs_remark, step="pre")
import sys for linea in sys.stdin: n = int(linea) if n == 0: print('error') else: ini = 4 res = 2 for j in range(n-1): print(ini, end=' ') ini = (ini*3) - res res = res+2 print(ini, end='') print()
# Python imports # Tornado imports import tornado.auth import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options from tornado.web import url # Sqlalchemy imports from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker # App imports import models # Options define("port", default=8000, help="run on the given port", type=int) define("debug", default=False, type=bool) define("db_path", default='sqlite:////tmp/test.db', type=str) class Application(tornado.web.Application): def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), ] settings = dict( debug=options.debug, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine( options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine)) class BaseHandler(tornado.web.RequestHandler): @property def db(self): return self.application.db class IndexHandler(BaseHandler): def get(self): try: testModel = models.TestModel(name='hello world') self.db.add(testModel) self.db.commit() except Exception as e: self.db.rollback() finally: self.write({'init': testModel.id}) self.db.close() def post(self): self.write({'init': 'hello world'}) # Write your handlers here def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': main()
from django.urls import path from .views import allblogs, detailed_blog urlpatterns = [ path('', allblogs, name='allblogs'), path('<int:blog_id>/', detailed_blog, name='detailed_blog'), ]
sum = 0 for i in range(0,100): sum+=(i+1); print(sum) # print(sum(range(1,101)))
import telepot import datetime as datetime from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time def EnviaTextoTelegram(msg, chatid, token): bot = telepot.Bot(token) bot.sendMessage(chatid, msg) return msg def EnviaCallEntradaTelegram(mensagem, chatid, token): bot = telepot.Bot(token) bot.sendPhoto(chatid, open(mensagem[0],'rb')) ganho = "{:.2f}".format(mensagem[7]-mensagem[1]) perda = "{:.2f}".format(mensagem[1] - mensagem[2]) msg = mensagem[8] + ' em '+ datetime.date.today().strftime('%d/%m/%Y')+ ' atingiu a retração de Fibonacci de '+str(mensagem[4])+'% e está com IFR(5) em '+ "{:.2f}".format(mensagem[3])+'\n' msg += '- Compra (Entrada): Se subir acima de R$'+ "{:.2f}".format( mensagem[1]) + '\n' msg += '- Venda no sucesso (Alvo): R$'+ "{:.2f}".format( mensagem[7]) + ' (Ganho de R$ '+ganho+' p/ ação)\n' msg += '- Venda na falha (Stop): Se cair abaixo de R$'+ "{:.2f}".format( mensagem[2]) + ' (Perda de R$ '+perda+' p/ ação)\n' bot.sendMessage(chatid, msg) def EnviaCallSaidaTelegram(mensagem, chatid, token): bot = telepot.Bot(token) bot.sendPhoto(chatid, open(mensagem[0],'rb')) ganho = "{:.2f}".format(mensagem[7]-mensagem[1]) perda = "{:.2f}".format(mensagem[1] - mensagem[2]) msg = mensagem[8] + ' em '+ datetime.date.today().strftime('%d/%m/%Y')+ ' atingiu a retração de Fibonacci de '+str(mensagem[4])+'% e está com IFR(5) em '+ "{:.2f}".format(mensagem[3])+'\n' msg += '- Compra (Entrada): Se subir acima de R$'+ "{:.2f}".format( mensagem[1]) + '\n' msg += '- Venda no sucesso (Alvo): R$'+ "{:.2f}".format( mensagem[7]) + ' (Ganho de R$ '+ganho+' p/ ação)\n' msg += '- Venda na falha (Stop): Se cair abaixo de R$'+ "{:.2f}".format( mensagem[2]) + ' (Perda de R$ '+perda+' p/ ação)\n' bot.sendMessage(chatid, msg)
import praw from pprint import pprint import config from sqlconfig import cursor,cnx,add_submission,retrieve_submissions,update_submission,delete_submissions,purge_table import string import hashlib import time punctuation = string.punctuation.replace(">","").replace("=","").replace("!","").replace("/","") #A list of all standard punctuation minus a few tokens that the bot searches for punctmap = str.maketrans("","",punctuation) #used later to filter punctuation from text get_time_seconds = lambda: int(round(time.time())) #gets the current time in seconds def parseComment(comment): """ Parses comment to determine what type of query to run. Does not validate the query just yet -comment: The body of reddit comment object Returns: object containing the keywords for the query """ commentTokens = comment.lower().translate(punctmap).split() #Individual tokens/terms in comment. Remove most punctuation besides (>!=/) startIndex = 0 #start of query. try: startIndex = commentTokens.index("!updateme") #The index where !UpdateMe is found except ValueError: #if !UpdateMe is found but not as a standalone token (ie "!UpdateMe" or !!UpdateMe versu !UpdateMe) return None #then we return none, as this is an invalid query sliceRange = slice(startIndex,startIndex+5) #Max query should be 5 terms, ie: !UpdateMe on user in subreddit queryWindow = commentTokens[sliceRange] #At most, 5 tokens that comprise the query and possibly some extra text #pad array with None if len > 5 lenDiff = 5 - len(queryWindow) queryWindow += [None]*lenDiff for i in range(1,len(queryWindow)): if(queryWindow[i] != None): queryWindow[i] = queryWindow[i].replace("!","") """ The summons should have the following format !UpdateMe [mode] [target] (in [target2])/([clause]) Examples: !UpdateMe on user in subreddit | !UpdateMe when votes > 1000 """ modes = ["on","when","help",] #what kind of query this is targets = ["op","post","all","comment"] #target can also be a username such as u/UpdatesAssistant mode = None target = None hasIn = False target2 = None clause = None if(queryWindow[1] in modes): #Checks mode mode = queryWindow[1] if(mode == "on"): if(queryWindow[2] in targets or isUser(queryWindow[2])): #checks target target = queryWindow[2] if(queryWindow[3] == "in" and queryWindow[4] == "subreddit"): #checks for in-statement hasIn = True target2 = queryWindow[4] elif(mode == "when"): mode = queryWindow[1] operators = [">",">=","="] # = should be after >= to prevent any mixups if(queryWindow[2] != None and queryWindow[3] != None and queryWindow[4] != None): #if clause is delimited by whitespace if(queryWindow[3] in operators): clause = (queryWindow[2],queryWindow[3],queryWindow[4]) elif(queryWindow[2] != None and queryWindow[3] == None): #if clause is not delimited by white space for operator in operators: if(operator in queryWindow[2]): splitToken = queryWindow[2].split(operator) clause = (splitToken[0],operator,splitToken[1]) #TODO: Ensure that the first part of the clause is valid break elif(mode == "help"): mode = queryWindow[1] return {"mode":mode,"target":target,"hasIn":hasIn,"target2":target2,"clause":clause} def validateComment(comment): """ Ensures that the query is valid. -comment: the object containing the parameters from the parsed comment returns: True if the comment is deemed valid and false otherwise """ mode = comment["mode"] target = comment["target"] target2 = comment["target2"] hasIn = comment["hasIn"] clause = comment["clause"] if(mode != None): if(mode == "on" and target == None): return False elif((mode == "when" and hasIn == True and target2 == None) or (mode == "when" and clause == None)): return False return True else: return False def checkIfSummons(comment): """ Determines if the comment is summoning the bot. Not rigorous and functions just as an initial filter. -comment: Reddit comment object return: True if the comment might be a summons. False if not """ #Summons must start with !UpdateMe if(comment.author.fullname == bot_account.fullname): #Return false if the comment was posted by this bot return False if("!updateme" in comment.body.lower()): return True else: return False #TODO: Make this a little more rigorous using reddit's api to determine if the user even exists def isUser(token): """ Determines if the token passed is a username. Simply checks if the token starts with "u/" -token: The potential username return: True if the token starts with "u/" and false otherwise. """ if(token == None): return False return token.startswith("u/") def processRequest(parsedComment,comment): """ Sends request to the proper function to the proper handler. -parsedComment: the object containing the keywords from the comment -comment: Reddit comment object """ mode = parsedComment["mode"] if(mode == "on"): onHandler(parsedComment,comment) if(mode == "help"): helpHandler(comment) def helpHandler(comment): """ Replies to comment with a help message. """ helpMessage = "" replyToComment(comment,helpMessage) def whenHandler(request,comment): clause = request["clause"] submission = "" if(clause[0] == "post"): submission = "post" elif(clause[0] == "comment"): submission = "comment" value = convertToNumber(clause[2]) #get the int value from the clause if(clause[1] == ">"): def convertToNumber(stringValue): """ """ def onHandler(request,comment): """ Handler for when the user uses the "on" mode. Packs comment/post information into a tuple to dump into the sql table. A verification is then sent to the user. -request: The keywords for the !UpdateMe request -coment: The reddit comment object that summoned the bot """ print("Handling \"on\" request") print(request) clause = None #"on" commands do no have a clause if(request["target"] == "post"): parent = comment.submission #In this case, the parent is the originating thread comment_id = comment.id #the id of the requesting comment parent_id = parent.id #the id of the parent post submission_type = 0 #post comment_permalink = comment.permalink parent_permalink = parent.permalink body_hash = hashlib.md5(parent.selftext.encode('utf-8')).hexdigest() #hexdigest converts into string poster = parent.author.name requester = comment.author.name num_upvotes = parent.ups num_comments = parent.num_comments subreddit_name = parent.subreddit.display_name expiration_date = get_time_seconds() + 60#259200 #3 days from now params = ( comment_id,parent_id,submission_type,comment_permalink, parent_permalink,body_hash,poster,requester,subreddit_name, expiration_date,num_upvotes,num_comments,clause ) reply_body = (f"Hi u/{requester}! I'll make sure to remind you about u/{poster}\'s [post](http://reddit.com{parent_permalink})!") addSubmissionToDatabase(params) #sends data to sql server replyToComment(comment,reply_body) elif(request["target"] == "comment"): parent = comment.parent() #In this case, the parent is the parent comment comment_id = comment.id parent_id = parent.id submission_type = 1 #comment comment_permalink = comment.permalink parent_permalink = parent.permalink body_hash = hashlib.md5(parent.body.encode('utf-8')).hexdigest() #Gets the md5 hash of the string. Hexdigest converts into string poster = parent.author.name requester = comment.author.name num_upvotes = parent.ups num_comments = len(parent.replies) subreddit_name = parent.subreddit.display_name expiration_date = get_time_seconds() + 60#259200 #3 days from now params = ( comment_id,parent_id,submission_type,comment_permalink, parent_permalink,body_hash,poster,requester,subreddit_name, expiration_date,num_upvotes,num_comments,clause ) reply_body = (f"Hi u/{requester}! I'll make sure to remind you about u/{poster}\'s [comment](https://reddit.com{parent_permalink})!") addSubmissionToDatabase(params) #sends data to sql server replyToComment(comment,reply_body) #elif(isUser(request["target"])): def addSubmissionToDatabase(queryParams): """ Takes information and inserts them into the MySQL Database. Database config found in sqlconfig.py -queryParams: The information to be inserted into the database columns """ cursor.execute(add_submission,queryParams) cnx.commit() def retrieveSubmissionsFromDatabase(): cursor.execute(retrieve_submissions) submissions = [] for submission in cursor: #print(user) submissions.append(submission) return submissions def replyToComment(comment,body): """ Replies to the comment that summoned the bot. Attaches a footer to each reply from the bot -comment: The reddit comment object that we are replying to -body: The body of the reply """ if(body == None or body.strip() == ""): raise ValueError("Message body cannot be empty!") footer = "" #Footer message for bot. Attached to every reply if(comment != None): print("Replied to comment",comment.id) comment.reply(body) else: raise ValueError("Comment required!") def sendMessage(submission,body): """ Sends a message to inform the recipient that the post/comment they were following has been updated. -submission: The SQL entry of the request as a tuple. -body: The message body. """ recipient = submission[8] subredditName = submission[9] postAuthor = submission[7] postType = getPostType(submission[3]) footer = "" #footer for message subject = f"u/{postAuthor}'s {postType} in r/{subredditName} has been updated!" reddit.redditor(recipient).message(subject,body+footer) def updateSubmission(submission): """ Updates the table entry with the new information. -submission: A tuple ocntaining all of the updated information on a query """ newSubmission = submission[:2] + submission[3:] + (submission[2],) #slice out the uid at index 2 and place it at the end (to satisfy the WHERE clause) cursor.execute(update_submission,newSubmission) cnx.commit() def deleteSubmissions(uids): """ Deletes a table entry -uids: The list of uids of the rows to be deleted """ if(len(uids) == 0): return paramInflater = ','.join(['%s'] * len(uids)) #adjusts number of inputs for query to match number of inputs passed in cursor.execute(delete_submissions % paramInflater,tuple(uids)) cnx.commit() print("Deleted",uids) def getPostType(typeNum): """ Converts the type number into a string for the post type Post: 0 Comment: 1 -typeNum: The type number for the post type returns: The post type as a string """ if(typeNum == 0): return "post" elif(typeNum == 1): return "comment" # #Initialize PRAW # reddit = praw.Reddit(client_id = config.client_id, # client_secret = config.client_secret, # user_agent = 'testscript by /u/cyclo_methane', # username = config.dev_username, # password = config.dev_password) # subreddit = reddit.subreddit('UpdateBotTest') # for submission in subreddit.hot(): #get all of the posts in the subreddit # pprint(vars(submission)) # quit() # commentFile = open("testComments.txt") # for line in commentFile: # splitLine = line.split(",") # comment = splitLine[0] # groundTruth = splitLine[1].strip() # parsedComment = parseComment(comment) # valid = str(False) # if(parsedComment != None): # valid = str(validateComment(parsedComment)) # if(valid != groundTruth): # print("Error:",parsedComment) # print(line) # print("Expected:",groundTruth) # print("Got:",valid) # print("-"*10) # quit() #Initialize PRAW reddit = praw.Reddit(client_id = config.client_id, client_secret = config.client_secret, user_agent = 'UpdatesAssistant by /u/cyclo_methane', username = config.dev_username, password = config.dev_password) print("Initializing praw...") bot_account = reddit.redditor("UpdatesAssistant") #This bot's reddit account ##only for test testing: #purge table before booting cursor.execute(purge_table) cnx.commit() ## #delete all of this bots comments before testing for comment in bot_account.comments.new(limit=None): comment.delete() #For now, we are only working with the Test Subreddit subreddit = reddit.subreddit('UpdateBotTest') for submission in subreddit.hot(): #get all of the posts in the subreddit print("Getting submission:",submission.title) comments = submission.comments.list() #Get all the comments from the post print(comments) for comment in comments: isSummons = checkIfSummons(comment) #Check each comment to see if it is a summons if(isSummons): parsedComment = parseComment(comment.body) valid = False if(parsedComment != None): valid = validateComment(parsedComment) if(valid): processRequest(parsedComment,comment) else: print("Not a valid query:",comment.body) else: print("Not a summons:",comment.body) continue #continue if this comment does not contain a summons while(True): submissions = retrieveSubmissionsFromDatabase() submission_uids = [] #list of uids to deleete for submission in submissions: # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 #Submission entry columns: (requester_id,target_id,uid,type,post_permalink,parent_permalink,hash,poster,requester,subreddit,expiration_date,num_upvotes,num_comments,clause) target_id = submission[1] #the id of the target submission oldHash = submission[6] #the old hash of the submission newHash = "" postType = getPostType(submission[3]) if(postType == "post"): post = reddit.submission(target_id) #pprint(vars(post)) postBody = post.selftext newHash = hashlib.md5(postBody.encode('utf-8')).hexdigest() elif(postType == "comment"): comment = reddit.comment(target_id) commentBody = comment.body newHash = hashlib.md5(commentBody.encode('utf-8')).hexdigest() if(oldHash != newHash): #compare the hashes #post was edited submission = submission[:6] + (newHash,) + submission[7:] #edit tuple to replace the old hash value print(submission) requester = submission[8] parent_permalink = submission[5] updateSubmission(submission) #Update submission with new hash. updateMessage = f"Hi u/{requester}! The {postType} you have been following has been updated. You can find it [here](https://reddit.com{parent_permalink})!" sendMessage(submission,updateMessage) #Send message that the post was updated expiration_date = submission[10] if(get_time_seconds() >= expiration_date): #when the request is passed its expiration date, stop updating requester and delete from database submission_uids.append(submission[2]) #uid deleteSubmissions(submission_uids)
from django.shortcuts import render from citizen_reporting_webapp.settings import MAPBOX_API_KEY # Create your views here. def index(request): context = {'mapbox_access_token': MAPBOX_API_KEY } return render(request, 'dashboard/index.html', context) def login(request): return redirect("authenticate:login")
i=input("Enter the Num") if i.isalpha(): if i in("a","e","i","o","u",): print "Vowels" else: print "Consonant" else: print "Invalid"
from ..DGFit_Models import DGFit_MRN def test_mrn_initialize(): dgmod = DGFit_MRN() assert dgmod.type == 'MRN'
""" BINARY TREE Definitions: 1. Full: every node has 0 or 2 children. 2. Complete: Every level filled except last which is left. 3. Perfect: All internal nodes have 2 children. 4. Balanced: Height is O(log(n)). 5. Degenerate: Each node has one child. """ class Node: def __init__(self, key): self.left = None self.right = None self.data = key class BinaryTree: def __init__(self): self.root = None def height_of_tree(self, node): if node is None: return 0 lheight = self.height_of_tree(node.left) rheight = self.height_of_tree(node.right) if lheight > rheight: return lheight + 1 return rheight + 1 def inorder_traversal(self, x): if x is not None: self.inorder_traversal(x.left) print(x.key) self.inorder_traversal(x.right) def nodes_in_subtree(self, x): if x is None: return 0 l_subtree_nodes = self.nodes_in_subtree(x.left) r_subtree_nodes = self.nodes_in_subtree(x.right) return l_subtree_nodes + r_subtree_nodes + 1 if __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.right = Node(1) root.right.right.left = Node(10) # print(height_of_tree(root))
from rv.modules import Behavior as B from rv.modules import Module from rv.modules.base.filter import BaseFilter class Filter(BaseFilter, Module): behaviors = {B.receives_audio, B.sends_audio}
from twitter.common.threading.periodic_thread import PeriodicThread from twitter.common.threading.stoppable_thread import StoppableThread __all__ = [ 'PeriodicThread', 'StoppableThread' ]
import pandas as pd class MarketOnClosePortfolio(object): def __init__(self, symbol, bars, initial_capital, strategy, n_shares=100): self.symbol = symbol self.initial_capital = initial_capital self.n_shares = n_shares self.strategy = strategy self.bars = bars self.make_positions() def make_positions(self): self.positions = pd.DataFrame(index=self.strategy.signals.index).fillna(0.0) self.positions[self.symbol] = self.n_shares*self.strategy.signals['signal'] def backtest_portfolio(self): self.portfolio = pd.DataFrame(index=self.bars.index) pos_diff = self.positions[self.symbol].diff() self.portfolio['holdings'] = (self.positions[self.symbol]*self.bars['Close']) self.portfolio['cash'] = self.initial_capital - (pos_diff*self.bars['Close']).cumsum() self.portfolio['total'] = self.portfolio['cash'] + self.portfolio['holdings'] self.portfolio['returns'] = self.portfolio['total'].pct_change() def score(self): init=self.initial_capital final=self.portfolio['total'].iloc[-1] return (final-init)/init*100. def plot(self): fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15,8)) ax.plot('total', data=self.portfolio, color='blue', linewidth=2) buy = self.strategy.signals.positions == 1 sell = self.strategy.signals.positions == -1 ax.plot(self.portfolio.loc[buy].index, self.portfolio.loc[buy, 'total'], '^', color='black', label='', markersize=10) ax.plot(self.portfolio.loc[sell].index, self.portfolio.loc[sell, 'total'], 'v', color='red', label='', markersize=10) return fig
## Convert celsius temp to fahrenheit def celsius_to_fahrenheit(value): if value is None: return 0 else: return (value * (9/5)) + 32
import matplotlib.pyplot as plt import networkx as nx class GraphPlot: def __init__(self, G=None, scale=[1,10,1,10], node_size = 500, node_color = [0.2,0.2,0.2], edge_color = [0,0,1], font_size = 16, font_family="sans-serif", font_weight='bold', font_color=[1,1,1], def_weight=5, def_color= [1,0,0], seed=7, ): self.seed = seed self.scale = scale self.node_size = node_size self.node_color = node_color self.edge_color = edge_color self.font_size = font_size self.font_family = font_family self.font_weight = font_weight self.font_color = font_color self.def_weight = def_weight # peso por defecto self.def_color = def_color # color de arista sin peso if G != None: self.plot(G) def __map(self, x, scale): in_min, in_max, out_min, out_max = scale[0], scale[1], scale[2], scale[3] return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min def plot(self, G): edges = [] for (u,v,d) in G.edges(data=True): try: wval = d['weight'] w = self.__map(wval, self.scale) if wval !=0 else self.def_weight color = self.edge_color if wval != 0 else self.def_color except: w = self.def_weight color = self.def_color edges += [[[(u,v)], w, color]] pos = nx.spring_layout(G, seed=self.seed) # positions for all nodes - seed for reproducibility # nodes nx.draw_networkx_nodes(G, pos, node_size = self.node_size, node_color= [self.node_color]) # edges for i in range(len(edges)): ed = edges[i][0] w = edges[i][1] color = edges[i][2] nx.draw_networkx_edges(G, pos, edgelist=ed, width=w, edge_color=[color]) # labels nx.draw_networkx_labels(G, pos, font_size=self.font_size, font_family=self.font_family, font_weight=self.font_weight, font_color=self.font_color) ax = plt.gca() ax.margins(0.08) plt.axis("off") plt.tight_layout() plt.show()
"""Contains files for handling allStar APOGEE files and converting them into numpy arrays of observed spectra""" import apogee.tools.read as apread import apogee.tools.path as apogee_path from apogee.tools import bitmask from apogee.spec import continuum import numpy as np filtered_bits = [bitmask.apogee_pixmask_int('BADPIX'), bitmask.apogee_pixmask_int('CRPIX'), bitmask.apogee_pixmask_int('SATPIX'), bitmask.apogee_pixmask_int('UNFIXABLE'), bitmask.apogee_pixmask_int('BADDARK'), bitmask.apogee_pixmask_int('BADFLAT'), bitmask.apogee_pixmask_int('BADFLAT'), bitmask.apogee_pixmask_int('BADERR')] class Dataset(): def __init__(self,allStar=None,filtered_bits=filtered_bits,filling_dataset=None,threshold=0.05): """ allStar: an allStar FITS file containg those APOGEE observations which should be included in the dataset. threshold: float A cut-off error above which pixels should be considered masked """ self.threshold = threshold self.bad_pixels_spec = [] self.bad_pixels_err = [] self.allStar = allStar self.filtered_bits = filtered_bits self.filling_dataset = filling_dataset self.spectra = self.spectra_from_allStar(allStar) self.errs = self.errs_from_allStar(allStar) self.masked_spectra = self.make_masked_spectra(self.spectra,self.errs,self.threshold) #self.mask = self.mask_from_allStar(allStar) def filter_mask(self,mask,filtered_bits): """takes a bit mask and returns an array with those elements to be included and excluded from the representation.""" mask_arrays = np.array([bitmask.bit_set(bit,mask).astype(bool) for bit in filtered_bits]) filtered_mask = np.sum(mask_arrays,axis=0)==0 return filtered_mask def idx_to_prop(self,idx): """Get the Apogee information associated to an index entry in the Allstar file""" return self.allStar[idx]["APOGEE_ID"],self.allStar[idx]["FIELD"], self.allStar[idx]["TELESCOPE"] def spectra_from_idx(self,idx): """Get the ASPCAP continium normalized spectra corresponding to an allStar entry from it's index in allStar""" apogee_id,loc,telescope = self.idx_to_prop(idx) return apread.aspcapStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=1)[0] def mask_from_idx(self,idx): """Get the APSTAR mask associated to an AllStar entry from its index in allStar""" apogee_id,loc,telescope = self.idx_to_prop(idx) return apread.apStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=3)[0][0] def errs_from_idx(self,idx): """Get the ASPCAP errs associated to an ASPCAP continuum normalized spectra from its index in allStar""" apogee_id,loc,telescope = self.idx_to_prop(idx) return apread.aspcapStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=2)[0] def spectra_from_allStar(self,allStar): """Converts an AllStar file into an array containing the ASPCAP continuum-normalized spectra. Any spectra incapable of being retrieved is added to a bad_pixels_spec list""" spectras = [] for idx in range(len(allStar)): try: spectras.append(self.spectra_from_idx(idx).astype(np.float32)) except: self.bad_pixels_spec.append(idx) return np.array(spectras) def errs_from_allStar(self,allStar): """Converts an AllStar file into an array containing the ASPCAP continuum-normalized errors associated to spectra. Any spectra incapable of being retrieved is added to a bad_pixels_spec list""" errs = [] for idx in range(len(allStar)): try: errs.append(self.errs_from_idx(idx).astype(np.float32)) except: self.bad_pixels_err.append(idx) return np.array(errs) def mask_from_allStar(self,allStar): """Converts an AllStar file into an array containing the APSTAR masks continuum-normalized spectra.""" mask = [self.mask_from_idx(idx).astype(np.float32) for idx in range(len(allStar))] return mask def add_mask(self,new_mask): self.masked_spectra.mask = np.logical_or(self.masked_spectra.mask,new_mask) def make_masked_spectra(self,spectra,errs,threshold=0.05): """set to zero all pixels for which the error is predicted to be greater than some threshold.""" mask = errs>threshold empty_bins = ~(spectra.any(axis=0)[None,:].repeat(len(spectra),axis=0)) mask = np.logical_or(empty_bins ,mask) masked_spectra = np.copy(spectra) masked_spectra[mask]= 0 masked_spectra = np.ma.masked_array(masked_spectra, mask=mask) return masked_spectra class FitDataset(Dataset): def __init__(self,allStar): self.allStar = allStar self.spectra = self.spectra_from_allStar(allStar) def spectra_from_idx(self,idx): """Get the ASPCAP continium normalized spectra corresponding to an allStar entry from it's index in allStar""" apogee_id,loc,telescope = self.idx_to_prop(idx) return apread.aspcapStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=3)[0] class ApVisitDataset(Dataset): """Dataset containing continuum-normalized visits. This code is a bit hacky so may fail on some edgecases""" def __init__(self,allStar=None,threshold=0.05): self.allStar = allStar self.threshold = threshold self.bad_pixels_spec = [] self.bad_pixels_err = [] self.spectra = self.spectra_from_allStar(allStar) self.errs = self.errs_from_allStar(allStar) #self.masked_spectra = self.make_masked_spectra(self.spectra,self.errs,self.threshold) def make_masked_spectra(self,spectra,errs,threshold=0.05): """set to zero all pixels for which the error is predicted to be greater than some threshold.""" mask = errs>threshold masked_spectra = [] for i,spec in enumerate(self.spectra): ma_spec_data = np.copy(np.array(spec)) ma_spec_data = np.nan_to_num(ma_spec_data,posinf=0,neginf=0) ma = mask[None,i].repeat(ma_spec_data.shape[0],axis=0) ma_spec_data[ma] = 0 ma_spec = np.ma.masked_array(ma_spec_data, mask=ma) masked_spectra.append(ma_spec) return masked_spectra def update_masked_spectra(self,errs,threshold=0.05): """Feed an error array to use in masked spectra""" self.masked_spectra = self.make_masked_spectra(self.spectra,errs,threshold) def visit_from_idx(self,idx,visit_idx): spec,spec_err = self.get_apstar_visit(idx,visit_idx) #if nvisit=1 --> spec dim is 8575 else spec dim is nvist+2 cont_spec = self.continium_normalize_visit(spec,spec_err) return cont_spec def continium_normalize_visit(self,spec,spec_err): spec= np.reshape(spec,(1,len(spec))) spec_err= np.reshape(spec_err,(1,len(spec_err))) cont= continuum.fit(spec,spec_err,type='aspcap',niter=0) return spec[0]/cont[0] def get_apstar_visit(self,idx,visit_idx): apogee_id,loc,telescope = self.idx_to_prop(idx) if visit_idx ==0: #visit_idx==0 spectra have different shape needing accomodating spec = apread.apStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=1)[0] spec_err = apread.apStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=2)[0] else: spec = apread.apStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=1)[0][visit_idx] spec_err = apread.apStar(loc_id=str(loc),apogee_id=apogee_id,telescope=telescope,ext=2)[0][visit_idx] return spec,spec_err def spectra_from_allStar(self,allStar): spectras = [] for idx in range(len(allStar)): n_visits = allStar["NVISITS"][idx] if n_visits>1: visits = [] for visit_idx in range(2,n_visits+2): visits.append(self.visit_from_idx(idx,visit_idx).astype(np.float32)) spectras.append(visits) else: visits = [] visits.append(self.visit_from_idx(idx,0).astype(np.float32)) spectras.append(visits) return np.array(spectras) def interpolate(spectra, filling_dataset): """ Takes a spectra and a dataset and fills the missing values in the spectra with those from the most similar spectra in the dataset --------------------- spectra: numpy.array a spectra with missing values set to zero which we wish to fill filling_dataset: numpy.array dataset of spectra we would like to use for interpolation """ print("new spectrum interpolated...") well_behaved_bins = np.sum(filling_dataset,axis=0)!=0 #we are happy to leave at zero these bins missing_values = spectra.mask similarity = np.sum((filling_dataset - spectra)**2,axis=1) similarity_argsort = list(similarity.argsort()) #1 because 0 is the spectra itself inpainted_spectra = np.copy(spectra) zeroes_exist=True while zeroes_exist: most_similar_idx = similarity_argsort.pop(0) inpainted_spectra[missing_values] = filling_dataset[most_similar_idx][missing_values] #while loop makes replacing with flagged ok missing_values = inpainted_spectra==0 if (missing_values[well_behaved_bins]==False).all(): #check whether some values are still zero. If none are break from loop zeroes_exist=False return inpainted_spectra def infill_masked_spectra(masked_dataset,masked_filling_dataset=None): infilled_dataset = [interpolate(spectra,masked_filling_dataset) for spectra in masked_dataset] return np.array(infilled_dataset)
my_list = [] my_list = [x*y for x in [20, 40, 60] for y in [2, 4, 6]] print(my_list)
from game.items.item import Pickaxe from game.skills import SkillTypes class SacredClayPickaxe(Pickaxe): name = 'Sacred Clay Pickaxe' value = 21333 skill_requirement = {SkillTypes.mining: 40} equip_requirement = {SkillTypes.attack: 1} damage = 24 accuracy = 110 weight = 2
import warnings import ansible import ansible.constants import ansible.utils import ansible.errors from ansible.runner import Runner from pytest_ansible.module_dispatcher import BaseModuleDispatcher from pytest_ansible.errors import AnsibleConnectionFailure from pytest_ansible.results import AdHocResult from pytest_ansible.has_version import has_ansible_v1 if not has_ansible_v1: raise ImportError("Only supported with ansible < 2.0") class ModuleDispatcherV1(BaseModuleDispatcher): """Pass.""" required_kwargs = ('inventory', 'inventory_manager', 'host_pattern') def has_module(self, name): # Make sure we parse module_path and pass it to the loader, # otherwise, only built-in modules will work. if 'module_path' in self.options: paths = self.options['module_path'] if isinstance(paths, (list, tuple, set)): for path in paths: ansible.utils.module_finder.add_directory(path) else: ansible.utils.module_finder.add_directory(paths) return ansible.utils.module_finder.has_plugin(name) def _run(self, *module_args, **complex_args): """Execute an ansible adhoc command returning the results in a AdHocResult object.""" # Assemble module argument string if True: module_args = ' '.join(module_args) else: if module_args: complex_args.update(dict(_raw_params=' '.join(module_args))) # Assert hosts matching the provided pattern exist hosts = self.options['inventory_manager'].list_hosts() no_hosts = False if len(hosts) == 0: no_hosts = True warnings.warn("provided hosts list is empty, only localhost is available") self.options['inventory_manager'].subset(self.options.get('subset')) hosts = self.options['inventory_manager'].list_hosts(self.options['host_pattern']) if len(hosts) == 0 and not no_hosts: raise ansible.errors.AnsibleError("Specified hosts and/or --limit does not match any hosts") # Build module runner object kwargs = dict( inventory=self.options.get('inventory_manager'), pattern=self.options.get('host_pattern'), module_name=self.options.get('module_name'), module_args=module_args, complex_args=complex_args, transport=self.options.get('connection'), remote_user=self.options.get('user'), module_path=self.options.get('module_path'), become=self.options.get('become'), become_method=self.options.get('become_method'), become_user=self.options.get('become_user'), ) # Run the module runner = Runner(**kwargs) results = runner.run() if 'dark' in results and results['dark']: raise AnsibleConnectionFailure("Host unreachable", dark=results['dark'], contacted=results['contacted']) # Success! return AdHocResult(contacted=results['contacted'])
import logging import pandas from aiogram.types import ContentType from config import API_TOKEN from aiogram import Bot, Dispatcher, executor, types from config import DST_CHAT_ID, SRC_CHAT_ID, TRIGGER_WORDS logging.basicConfig(level=logging.INFO) bot = Bot(token=API_TOKEN) dp = Dispatcher(bot) @dp.message_handler() async def message_from_momiac(message: types.Message): if message.chat.id == SRC_CHAT_ID: for i in TRIGGER_WORDS: if i in message.text.lower(): await bot.forward_message(DST_CHAT_ID, message.chat.id, message.message_id) logging.info(f"{message.date} New message from {message.from_user.full_name}") @dp.message_handler(content_types=ContentType.DOCUMENT) async def message_with_doc(document: types.Document): if document.chat.id == SRC_CHAT_ID: binary_doc = await bot.download_file_by_id(document.document.file_id) xl_file = pandas.read_excel(binary_doc) for i in TRIGGER_WORDS: if i in str(document.caption).lower() or \ "Another_trigger_words" in xl_file.to_string().lower(): await bot.forward_message(DST_CHAT_ID, document.chat.id, document.message_id) logging.info(f"{document.date} New message with document from {document.from_user.full_name}") break if __name__ == '__main__': executor.start_polling(dp)
import InsiderTrading as IT from datetime import date, timedelta import yfinance as yf stock_name = "MSFT" stock = yf.Ticker(stock_name) print(float(stock.info["previousClose"])) print(str(date.today()-timedelta(1))) print(IT.insider_trading())
#Programa: act11.py #Propósito: Suponiendo que hemos introducido una cadena por teclado que representa una frase (palabras separadas por espacios), realiza un programa que cuente cuantas palabras tiene. #Autor: Jose Manuel Serrano Palomo. #Fecha: 29/10/2019 # # Análisis: # Introduce el usuario una frase # comprobamos cada posición de la cadena y # si hay espacio es por que hemos cambiado de palabra # Diseño: # Leemos cad # para i en el rango la longitud de cad # si la posicion de la cadena es igual a espacio # se añade a un contador # fin del bucle # escribimos "el resultado es 'contador' palabras # variables: cad es la cadena, cont el contador, i el indice del for. print("Contador de palabras") print("---------------------\n") # Leemos los datos cad = str(input("Introduce una frase: ")) cont = 1 # Realizamos el contador for i in range (len(cad)): if cad[i] == " ": cont = cont + 1 # Imprimimos el resutlado print(f"Hay {cont} palabras en la frase")
""" Sorts importance files output by RandomForest_v2.0 and related SciKit-learn ML scripts and allows for other selection. Required input: -f : path to file or path to directory with multiple imp.txt files Other options: -n : Gives top n most important features -p : Gives top percent p most important features -value : default = True, if False then don't print pvalue in output """ import os, sys import operator n = "n" cutoff = "n" p = "n" value = "True" f = "help" for i in range (1,len(sys.argv),2): if sys.argv[i] == '-f': #Path to imp.txt file or to directory with files f = sys.argv[i+1] if sys.argv[i] == '-n': #Return the top n n = int(sys.argv[i+1]) if sys.argv[i] == '-cutoff': #Return all features with imp over cutoff cutoff = sys.argv[i+1] if sys.argv[i] == '-p': #Return the top p percent p = sys.argv[i+1] if sys.argv[i] == '-value': #Return the top p percent value = sys.argv[i+1] def sort(f): dic = {} for l in open(f, 'r'): kmer, val = l.strip().split("\t") dic[kmer] = float(val) sorted_dic = sorted(dic.items(), key=operator.itemgetter(1), reverse = True) if n == p == "n": name = f + "_sort" out = open(name, 'w') if value == "True": for i in sorted_dic: out.write("%s\t%s\n" % (i[0], i[1])) if value == "False" or value == "false" or value == "f": for i in sorted_dic: out.write("%s\n" % (i[0])) elif n != "n": name = f + "_top" + str(n) out = open(name, 'w') kmer_list = sorted_dic[0:n] if value == "True": for i in kmer_list: out.write("%s\t%s\n" % (i[0], i[1])) if value == "False" or value == "false" or value == "f": for i in kmer_list: out.write("%s\n" % (i[0])) elif p != "n": name = f + "_top" + str(p) + "perc" out = open(name, 'w') top = int(float(len(sorted_dic)) * float(p) * 0.01) kmer_list = sorted_dic[0:top] if value == "True": for i in kmer_list: out.write("%s\t%s\n" % (i[0], i[1])) if value == "False" or value == "false" or value == "f": for i in kmer_list: out.write("%s\n" % (i[0])) if ".txt" in f: print("Parsing given file") sort(f) else: print("Parsing all .imp files in directory") for j in os.listdir(f): if j.startswith(".") or not "_imp.txt" in j: pass else: print(j) sort(j)
# Write a function that implements a substitution cipher. In a substitution cipher one letter is substituted for another to garble the message. # For example A -> Q, B -> T, C -> G etc. your function should take two parameters, the message you want to encrypt, # and a string that represents the mapping of the 26 letters in the alphabet. Your function should return a string that is the encrypted version of the message. def substitution_cipher(str, sub_str): ciphered = '' # Initializing a variable to store the cipher text for char in str: # Loopin through each character of the string to find and replace it with the appropriate cipher if((ord(char)>=97) and (ord(char)<=122)): #To handle the lower case letter ciphered = f'{ciphered}{sub_str[ord(char)-97]}' # replacing the lower case letter with corressponding case elif((ord(char)>=65) and (ord(char)<=90)): #To handle the upper case letter and ciphered = f'{ciphered}{sub_str[ord(char)-65]}' # replacing the lower case letter with corressponding case else: ciphered = f'{ciphered}{char}' # If the char is not a valid Alphabet then using the same char # Retrun the cipher string return ciphered print(substitution_cipher('Good days are comming','qwertyuiopasdfghjklzxcvbnm'))
from time import time import json import Common.Emulation as emu import Common.base64encoder as b64 import Common.secrets as sec if sec.Raspberry: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) class Device: def __init__( self, client, clockInterval=1, *, emulation=False ): self.client = client self.emulation = emulation self.clockInterval = clockInterval self.needPublish = False self.Initialize() def Initialize(self): self.clock = time() self.Subscribe() def Update(self): t = time() if t - self.clock > self.clockInterval: self.clock = t return True return False def Subscribe(self): pass def Publish(self): if not self.needPublish: return self.Send() self.needPublish = False class AirPollutionSensor(Device): def Initialize(self): super().Initialize() self.humidity = 0 self.oxygen = 0 self.carbon = 0 self.nitric = 0 self.sulfurous = 0 self.hydrogen_sulfide = 0 self.methane = 0 self.dust = 0 def Update(self): if not super().Update(): return if self.emulation: self.humidity = emu.GetInt(40, 85) self.oxygen = emu.GetInt(15, 40) self.carbon = emu.GetInt(5, 15) self.nitric = emu.GetFloat(10 ** -5, 1) self.sulfurous = emu.GetFloat(10 ** -5, 10 ** -4) self.hydrogen_sulfide = emu.GetFloat(10 ** -5, 10 ** -4) self.methane = emu.GetFloat(0.5, 2) self.dust = emu.GetFloat(0.5, 5) self.needPublish = True def Send(self): self.client.publish("environment", json.dumps( { "humidity": self.humidity, "oxygen": self.oxygen, "carbon": self.carbon, "nitric": self.nitric, "sulfurous": self.sulfurous, "hydrogen_sulfide": self.hydrogen_sulfide, "methane": self.methane, "dust": self.dust, } ) ) class CostumeParams(Device): def Initialize(self): super().Initialize() self.active = False self.charge = 100 self.needPublish = True self.ledPin = 14 if sec.Raspberry: GPIO.setup(self.ledPin, GPIO.OUT) GPIO.output(self.ledPin, GPIO.LOW) def Subscribe(self): self.client.on_message = self.OnMessage self.client.subscribe("activation") def Update(self): if not super().Update(): return if self.emulation: if self.active: self.charge = emu.ReduceInt(self.charge, 1, 0) self.needPublish = True if sec.Raspberry: GPIO.output(self.ledPin, GPIO.HIGH if self.active else GPIO.LOW) def Send(self): self.client.publish("active", self.active) self.client.publish("charge", self.charge) def OnMessage(self, client, userdata, message): data = json.loads(message.payload.decode('utf-8')) self.active = data["activate"] self.needPublish = True class Coords(Device): def Initialize(self): super().Initialize() self.x = 0 self.y = 0 self.z = 0 def Update(self): if not super().Update(): return if self.emulation: self.x = emu.GetInt(0, 50) self.y = emu.GetInt(0, 50) self.z = emu.GetInt(-30, -25) self.needPublish = True def Send(self): self.client.publish("coords", json.dumps({ "x": self.x, "y": self.y, "z": self.z })) class Beacon(Device): def Initialize(self): super().Initialize() self.latitude = 0 self.longitude = 0 self.altitude = 0 self.time = 0 self.visible = [False] * 8 self.rssi = {'98:12': -127, '0a:35': -127, '29:39': -127, 'd3:96': -127, 'f7:41': -127, '01:dd': -127, '08:cd': -127, '0e:60': -127} def Update(self): if not super().Update(): return if self.emulation: self.latitude = emu.GetFloat(68, 69) self.longitude = emu.GetFloat(64, 66) self.altitude = emu.GetFloat(0.9, 1.75) self.time = round(time()) self.visible = emu.RandomBoolArray(8) for i, k in enumerate(self.rssi): self.rssi[k] = emu.GetInt(-127, 0) if self.visible[i] else -127 self.needPublish = True def Send(self): data = {} for k in self.rssi.keys(): if self.rssi[k] > -127: data[k] = self.rssi[k] self.client.publish( "beacon", b64.encode(self.latitude, self.longitude, self.altitude, self.time, data) ) class Buzzer(Device): def __init__( self, client, pin, clockInterval=1, *, emulation=False ): self.ledPin = pin super().__init__(client, clockInterval, emulation=emulation) def Initialize(self): super().Initialize() self.buzzer = False if sec.Raspberry: GPIO.setup(self.ledPin, GPIO.OUT) GPIO.output(self.ledPin, GPIO.LOW) def Subscribe(self): self.client.subscribe("buzzer_activation") self.client.message_callback_add("buzzer_activation", self.OnMessage) def Update(self): if not super().Update(): return self.needPublish = True if sec.Raspberry: GPIO.output(self.ledPin, GPIO.HIGH if self.buzzer else GPIO.LOW) def Send(self): self.client.publish("buzzer", self.buzzer) def OnMessage(self, client, userdata, message): data = json.loads(message.payload.decode('utf-8')) self.buzzer = data["activate"] if sec.Raspberry: GPIO.output(self.ledPin, GPIO.HIGH if self.buzzer else GPIO.LOW) self.needPublish = True class Ventilation(Device): def Initialize(self): super().Initialize() self.ventilation = False if sec.Raspberry: self.ventPin = 18 GPIO.setup(self.ventPin, GPIO.OUT) GPIO.output(self.ventPin, GPIO.LOW) def Subscribe(self): self.client.subscribe("ventilation_activation") self.client.message_callback_add("ventilation_activation", self.OnMessage) def Update(self): if not super().Update(): return self.needPublish = True if sec.Raspberry: GPIO.output(self.ventPin, GPIO.HIGH if self.ventilation else GPIO.LOW) def Send(self): self.client.publish("ventilation", self.ventilation) def OnMessage(self, client, userdata, message): data = json.loads(message.payload.decode('utf-8')) self.ventilation = data["activate"] self.needPublish = True if sec.Raspberry: GPIO.output(self.ventPin, GPIO.HIGH if self.ventilation else GPIO.LOW) class FuelSensor(Device): def Initialize(self): super().Initialize() self.adc = 5042 def Update(self): if not super().Update(): return if self.emulation: self.adc = emu.ReduceInt(self.adc, 11, 0) self.needPublish = True def Send(self): self.client.publish("adc", self.adc) class GPS(Device): def Initialize(self): super().Initialize() self.latitude = 0 self.longitude = 0 def Update(self): if not super().Update(): return if self.emulation: self.latitude = emu.GetFloat(64, 67) self.longitude = emu.GetFloat(60, 68) self.needPublish = True def Send(self): self.client.publish("lat", self.latitude) self.client.publish("lon", self.longitude) class Power(Device): def Initialize(self): super().Initialize() self.active = True def Update(self): if not super().Update(): return def Send(self): self.client.publish("electro", self.active) class NoiseSensor(Device): def Initialize(self): super().Initialize() self.noise = 0 def Update(self): if not super().Update(): return if self.emulation: self.noise = emu.GetInt(0, 80) self.needPublish = True def Send(self): self.client.publish("noise", self.noise) class Thermometer(Device): def __init__( self, client, index, clockInterval=1, *, emulation=False ): super().__init__(client, clockInterval, emulation=emulation) self.index = index def Initialize(self): super().Initialize() self.temperature = 0 def Update(self): if not super().Update(): return if self.emulation: self.temperature = emu.GetFloat(15, 60) self.needPublish = True def Send(self): self.client.publish(f"temp{self.index}", self.temperature) class MovementSensor(Device): def __init__( self, client, index, clockInterval=1, *, emulation=False ): super().__init__(client, clockInterval, emulation=emulation) self.index = index def Initialize(self): super().Initialize() self.movement = False def Update(self): if not super().Update(): return if self.emulation: self.movement = emu.GetBool() self.needPublish = True def Send(self): self.client.publish(f"move{self.index}", self.movement)
import sqlite3 from flask import g, Flask, jsonify from datetime import datetime import logging from gpiozero import OutputDevice, DigitalInputDevice DATABASE = 'database.db' POOL = 0 SPA = 1 MIN = 0 LOW = 1 HIGH = 2 MAX = 3 PIN_STOP = 5 PIN_STEP1 = 6 PIN_STEP2 = 12 PIN_HEATER = 13 PIN_IN_VALVE = 19 PIN_OUT_VALVE = 16 PIN_CLEANER = 26 PIN_VALVE_CURRENT = 20 PIN_FLOW_SWITCH = 21 app = Flask(__name__) app.logger.setLevel(logging.DEBUG) pump_stop = OutputDevice(PIN_STOP, initial_value=None) pump_step1 = OutputDevice(PIN_STEP1, initial_value=None) pump_step2 = OutputDevice(PIN_STEP2, initial_value=None) heater = OutputDevice(PIN_HEATER, initial_value=None) in_valve_spa = OutputDevice(PIN_IN_VALVE, initial_value=None) out_valve_spa = OutputDevice(PIN_OUT_VALVE, initial_value=None) cleaner = OutputDevice(PIN_CLEANER, initial_value=None) flow_switch = DigitalInputDevice(PIN_FLOW_SWITCH, pull_up=True) # Events use datetimes, but RecurringEvents only have times. # A "current" Event is one whose start/end encompass now. # A "current" Event may not yet be "activated," meaning that the system # has asserted that Event's state on all fronts (valves, pumps, heater). class Event(dict): """ Events have a start and end datetime, and those time blocks are lazy (an overlapping event does not start until the end of the earliest-starting event). """ def __init__( self, start_date, end_date, id=None, in_valve=POOL, out_valve=POOL, speed=MIN, cleaner=False, heater=False, recurring_source_id=None, activated=False): self['start_date'] = start_date self['end_date'] = end_date self['in_valve'] = in_valve self['out_valve'] = out_valve self['speed'] = speed self['cleaner'] = cleaner self['heater'] = heater self['recurring_source_id'] = recurring_source_id self['activated'] = activated self['id'] = id class RecurringEvent(dict): """ RecurringEvents are like Events, except they don't have specific dates, only times and skip_days. """ def __init__(self, start_time, end_time, id=None, in_valve=POOL, out_valve=POOL, speed=MIN, cleaner=False, heater=False, skip_days=0): self['start_time'] = start_time self['end_time'] = end_time self['in_valve'] = in_valve self['out_valve'] = out_valve self['speed'] = speed self['cleaner'] = cleaner self['heater'] = heater self['skip_days'] = skip_days self['id'] = id def should_skip_today(self): if self['skip_days'] == 0: return False days_since_previous_event = query_db( "select julianday('now', 'localtime') - julianday('start_date') " "from events where recurring_source_id = ? " "order by start_date desc limit 1", one=True) if days_since_previous_event is None: return False return days_since_previous_event > self['skip_days'] DEFAULT_RECURRING_EVENTS = [ RecurringEvent( start_time="04:00", end_time="08:00", in_valve=POOL, out_valve=POOL, speed=MAX, cleaner=False, heater=False, ), RecurringEvent( start_time="08:00", end_time="10:00", in_valve=POOL, out_valve=POOL, speed=MAX, cleaner=True, heater=False, skip_days=7, ), RecurringEvent( start_time="10:00", end_time="16:00", in_valve=POOL, out_valve=SPA, speed=MIN, cleaner=False, heater=False, ), # TODO: remove test events RecurringEvent( start_time="16:00", end_time="22:00", in_valve=SPA, out_valve=SPA, speed=HIGH, cleaner=False, heater=True, ), RecurringEvent( start_time="22:00", end_time="04:00", in_valve=POOL, out_valve=SPA, speed=MIN, cleaner=False, heater=False, ), # RecurringEvent( # start_time="00:00", # end_time="04:00", # in_valve=POOL, # out_valve=POOL, # speed=MIN, # cleaner=False, # heater=False, # ), ] def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) db.row_factory = make_dicts return db def make_dicts(cursor, row): return dict((cursor.description[idx][0], value) for idx, value in enumerate(row)) def query_db(query, args=(), one=False): # app.logger.debug("query={}, args={}, one={}".format(query, args, one)) with app.app_context(): cur = get_db().execute(query, args) rv = cur.fetchall() cur.close() return (rv[0] if rv else None) if one else rv def write_db(query, args=()): app.logger.debug("query={}, args={}".format(query, args)) with app.app_context(): db = get_db() db.execute(query, args) db.commit() @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() def init_db(): with app.app_context(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.route("/") def index(): return "<p>Hello, World!</p>" @app.route("/v0/reset", methods=['POST']) def reset(): app.logger.warning("Resetting DB to hardcoded defaults") init_db() query_db("delete from recurring_events") query_db("delete from events") for event in DEFAULT_RECURRING_EVENTS: app.logger.info("Inserting default recurring event {}".format(event)) write_db( "insert into recurring_events " "(start_time, end_time, in_valve, " "out_valve, speed, heater, cleaner, " "skip_days) " "values (time(?), time(?), ?, ?, ?, ?, ?, ?)", args=( event['start_time'], event['end_time'], event['in_valve'], event['out_valve'], event['speed'], event['heater'], event['cleaner'], event['skip_days'])) return jsonify(query_db( "select * from recurring_events " "order by start_time")) @app.route("/v0/tick", methods=['POST']) def tick(): """Main loop, externally triggered every minute""" current_event = get_current_event() if current_event and not current_event["activated"]: current_event = activate_event(current_event) return jsonify(current_event) @app.route("/v0/events/current") def current_event(): event = get_current_event() return jsonify(event) @app.route("/v0/events/recurring") def recurring_events(): r_events = query_db("select * from recurring_events") return jsonify(r_events) def activate_event(event): app.logger.warning("Activating event {}".format(event)) _validate_event(event) _stop_pump() _set_valves(in_valve=event['in_valve'], out_valve=event['out_valve']) _set_speed(event['speed']) _set_heater(event['heater']) _set_cleaner(event['cleaner']) _unstop() write_db( "update events set activated = ? where id = ?", args=(True, event['id'])) event['activated'] = True return event def _validate_event(event): """Ensure that event doesn't violate safety checks. * cleaner requires POOL+POOL, no heater * heater requires SPA+SPA, no cleaner """ if event['heater']: if event['in_valve'] != SPA or event['out_valve'] != SPA raise ValueError("heater requires in=SPA, out=SPA") if event['speed'] < HIGH: raise ValueError("heater requires pump speed = HIGH or MAX") if event['cleaner']: if event['in_valve'] != POOL or event['out_valve'] != POOL raise ValueError("cleaner requires in=POOL, out=POOL") if event['speed'] < HIGH: raise ValueError("cleaner requires pump speed = HIGH or MAX") def _stop_pump(): _set_cleaner(False) # TODO: write to pump stop pin pass def _set_valves(in_valve=POOL, out_valve=POOL): # TODO: write to in_valve pin # TODO: write to out_valve pin _stop_pump() # TODO: poll valve current sensor pin pass def _set_speed(speed=MIN): pass def _set_heater(enabled=False): pass def _set_cleaner(enabled=False): pass def _unstop(): pass def get_current_event(check_recurring=True): event = query_db( """select * from events where datetime(start_date) <= datetime('now', 'localtime') and datetime(end_date) >= datetime('now', 'localtime') order by datetime(start_date) limit 1""", one=True) if not event: app.logger.info("Found no current event, checking for recurring events") r_event = get_current_recurring_event() if r_event: event = create_event_from_recurring(r_event) return event def get_current_recurring_event(): r_events = query_db( """select * from recurring_events where (time(start_time) <= time(end_time) and time(start_time) <= time('now', 'localtime') and time(end_time) >= time('now', 'localtime')) or (time(start_time) > time(end_time) and ( time(start_time) <= time('now', 'localtime') or time(end_time) >= time('now', 'localtime'))) order by time(start_time)""") for r_event in r_events: app.logger.info("Checking skip_days for {}".format(r_event)) r_event = RecurringEvent(**r_event) if not r_event.should_skip_today(): app.logger.info("Found current recurring event {}".format(r_event)) return r_event return None def create_event_from_recurring(r_event): # TODO: this is crappy end_modifier = "+0 day" if (datetime.strptime(r_event["start_time"], "%H:%M:%S") > datetime.strptime(r_event["end_time"], "%H:%M:%S")): end_modifier = "+1 day" write_db( """insert into events (start_date, end_date, in_valve, out_valve, speed, heater, cleaner, recurring_source_id) values ( datetime(date('now', 'localtime'), + ?), datetime(date('now', 'localtime'), + ?, ?), ?, ?, ?, ?, ?, ?)""", args=( r_event['start_time'], r_event['end_time'], end_modifier, r_event['in_valve'], r_event['out_valve'], r_event['speed'], r_event['heater'], r_event['cleaner'], r_event['id'])) event = query_db( """select * from events where recurring_source_id = ? order by datetime(start_date) desc limit 1""", args=(r_event['id'],), one=True) event = Event(**event) return event # def get_next_event(): # now = datetime.now() # now_str = now.strftime("%H:%M") # event = query_db( # "select * from events " # "where start_date >= ? " # "order by start_date limit 1", # args=(now_str,), one=True) # if not event and lazy_load: # return get_next_event(False) # return event # def get_recurring_events_after(when="now"): # events = query_db( # "select * from recurring_events " # "where time(start_time) >= time(?) " # "order by start_time", args=(when,)) # return events # def fill_recurring_events(): # recurring_events = get_recurring_events_after("now") # for event in recurring_events: # app.logger.info("Inserting recurring event: {}".format(event)) # query_db( # "insert into events " # "(start_date, end_date, in_valve, out_valve, speed, heater, cleaner) " # "values (date('now') + time(?), date('now') + time(?), ?, ?, ?, ?, ?)", # args=(event['start_time'], event['end_time'], event['in_valve'], event['out_valve'], event['speed'], event['heater'], event['cleaner']) # )
import views import unittest from mock import patch class TestMidterm(unittest.TestCase): def setUp(self): self.app = views.app.test_client() self.response = self.app.get('/') def test_get_index_page(self): self.assertEquals('200 OK', self.response.status) def test_title_Midterm_Project(self): self.assertTrue("<title> Midterm Project </title>" in self.response.get_data()) def test_h1_Midterm_Project(self): self.assertTrue("<h1> Midterm Project </h1>" in self.response.get_data()) def test_h2_James_Kasakyan(self): self.assertTrue("<h2> James Kasakyan </h2>" in self.response.get_data()) @patch('views.request') @patch('views.render_template') @patch('views.datetime') class TestMidtermUnit(unittest.TestCase): def test_index(self, mock_datetime, mock_render_template, mock_request): result = views.index() mock_request.assert_not_called() mock_datetime.datetime.now.assert_called_with() self.assertEqual(result, mock_render_template()) if __name__ == '__main__': unittest.main()
############################################################################################################### # Configure Logging: WORKSPACE = "workspace/" ############################################################################################################### # Dynamic pybot variables: # Specifies an 3D-array with variables passed to the single pybot instances # Each row contains a variablename - value(s) combination (array, name at index 0, values at 1++) # One variable value will be passed to each python instance using --variable name:value # If multiple values are defined parabot will iterate over the values and assign one to each pybot DYN_ARGS = [ # specify different users ["USER", "Hans", "Klaus", "Peter", "Martin", "Eric"], # passwords ["PASS", "HansPassword", "KlausPassword", "PetersPassword", "MartinsPassword", "EricsPassword"] ] time_between_test_start_up = 0 ##### # NEW # ####### DEFAULT_TOPOLOGY_FOLDER = "/mnt/wt/pyrobot_v1.1/pyrobot/dev/resources/topology/" DEFAULT_TOPOLOGY = "topology_default.py" SAUCE_USERNAME = 'talliskane' SAUCE_ACCESSKEY = "6c3ed64b-e065-4df4-b921-75336e2cb9cf" #DEFAULT_SAUCEURL = "username=%s&access-key=%s&os=%s&browser=%s&browser-version=%s&max-duration=null&idle-timeout=null" DEFAULT_SAUCEURL = "sauce-ondemand:?username=%s&access-key=%s&os=%s&browser=%s&browser-version=%s&max-duration=null&idle-timeout=null" DEFAULT_SOLO_BROWSER = 'chrome' DEFAULT_BROWSER_DISPLAY = ":60" BROWSER_CAPABILITIES = 'name:%s,platform:%s,version:%s,browserName:%s,javascriptEnabled:True,screen-resolution:1280x1024' BASE_URL = "http://www.google.ca" #WORKSPACE_HOME = "/mnt/wt/pyrobot_2/pyrobot/workspace/" WORKSPACE_HOME = "/mnt/wt/pyro/pyrobot/workspace/"
from django.contrib.auth.hashers import check_password, make_password from django.contrib.auth import logout from django.shortcuts import redirect from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework import viewsets from rest_framework import permissions from django.conf import settings from authentication.models import Person from authentication.serializers import PersonSerializer, ChangePasswordSerializer from authentication.utils import get_tokens_for_user # Create your views here. class PersonAuthViewSet(viewsets.ModelViewSet): """ Authentication View """ queryset = Person.objects.all() serializer_class = PersonSerializer def handle_exception(self, exc): data = { "success": False, "message": exc.__str__() } return Response(data, status=status.HTTP_401_UNAUTHORIZED) def get(self, request, format=None): data = { "ok": True } return Response(data, status=status.HTTP_200_OK) def register(self, request, format=None): serializer = PersonSerializer(data=request.data) if(serializer.is_valid()): serializer.save() obj = { "success": True, "message": "Successfully Registered!" } return Response(obj, status=status.HTTP_201_CREATED) obj = { "success": False, "message": serializer.errors, } return Response(obj, status=status.HTTP_400_BAD_REQUEST) def login(self, request, format=None): queryset = Person.objects.get(email=request.data['email']) if(check_password(request.data['password'], queryset.password)): token = get_tokens_for_user(queryset) token['expires_in'] = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'] obj = { "success": True, "data": token, } return Response(obj, status=status.HTTP_200_OK) obj = { "success": False, "message": "Incorrect Password!" } return Response(obj, status=status.HTTP_401_UNAUTHORIZED) def redirectedMethod(self, request, format=None): queryset = Person.objects.get(pk=request.session['_auth_user_id']) token = get_tokens_for_user(queryset) refresh = 'refresh=' + token['refresh'] access = 'access=' + token['access'] request.session.flush() return redirect('https://easy-svelte.netlify.com/Social/Redirect?' + refresh + '&' + access) class PersonView(viewsets.ModelViewSet): """ Authenticated View """ queryset = Person.objects.all() serializer_class = PersonSerializer permission_classes = [permissions.IsAuthenticated] def handle_exception(self, exc): data = { "success": False, "message": exc.__str__() } return Response(data, status=status.HTTP_401_UNAUTHORIZED) def userInfo(self, request, format=None): queryset = Person.objects.get(email=request.user) queryset.password = None serializer = PersonSerializer(queryset) data = { "success": True, "data": serializer.data } return Response(data, status=status.HTTP_200_OK) def changePassword(self, request, format=None): serializer = ChangePasswordSerializer(data=request.data) if not (serializer.is_valid()): data = { "success": False, "message": serializer.errors, } return Response(data, status=status.HTTP_401_UNAUTHORIZED) queryset = Person.objects.get(email=request.user) queryset.password = make_password(request.data['new_password']) queryset.save() data = { "success": True, "message": "Password Changed!", } return Response(data, status=status.HTTP_200_OK) def logout(self, request, format=None): logout(request) return Response(status=status.HTTP_204_NO_CONTENT)
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ # Uses the pre-generated table of primes. See ../prime_gen.py from os.path import abspath, dirname, join PRIME_FILE = abspath(join(dirname(__file__), '..', 'data', 'primes.txt')) TARGET_PRIME_INDEX = 10001 def solve(): """ >>> solve() 104743 """ try: with open(PRIME_FILE) as fd: for index, prime in enumerate(fd, start=1): if index == TARGET_PRIME_INDEX: return int(prime.strip()) else: raise RuntimeError('Not enough primes in prime file: only {} primes present'.format(index)) except (FileNotFoundError, IOError): print('Prime file not found or not at {}'.format(PRIME_FILE)) raise if __name__ == '__main__': solve()
# Generated by Django 2.2.5 on 2020-04-25 17:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('listings', '0008_auto_20200425_2143'), ] operations = [ migrations.AlterField( model_name='mobilephone', name='brand', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='phones', to='listings.Brand'), ), ]
import socket import sys import threading import time import csv import os import secrets import pandas as pd import numpy as np import pickle import math import random from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score from PIL import Image from flask import jsonify, render_template, url_for, flash, redirect, request from flaskApp import app, db, bcrypt, mail from flaskApp.forms import RegisterationForm,LoginForm, UpdateAccountForm, RequestResetForm, ResetPasswordForm from flaskApp.model import User, Post, Dustbin from flask_login import login_user, current_user, logout_user, login_required from flask_mail import Message from datetime import datetime day_value={"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6,"Sunday":7} def data_from_server(x): x1, y1=x.split(",") return x1,y1 def is_new_hour(x): last_update = db.session.query(Dustbin).order_by(Dustbin.id.desc()).first() last_update= last_update.time_in_hour int(last_update) if int(last_update)<= x: return False else: return True def day_number(): today_now = datetime.today().strftime('%A') today_now = int(day_value.get(today_now)) return today_now def get_last_status(): newest_row = db.session.query(Dustbin).order_by(Dustbin.id.desc()).first() newest_row = newest_row.status return int(newest_row) def get_last_row(x): newest_row = db.session.query(Dustbin).order_by(Dustbin.id.desc()).first() if x == 'previous': newest_row = newest_row.previous_status elif x == 'amount_per_day': newest_row = newest_row.amount_per_day else: newest_row = newest_row.full return newest_row def get_amount_per_day(x): hour_now = datetime.now().strftime('%H') try: first_amount = db.session.query(Dustbin).filter_by(day_of_week= day_number(), time_in_hour = int(hour_now)).order_by(Dustbin.id.desc()).first() first_amount= int(first_amount) if x>= first_amount: return x- first_amount else: return (100-first_amount)+ x except: return x def day_year(): d = datetime.datetime.now().strftime('%j') return int(d) def is_full(): full_day = db.session.query(Dustbin).filter_by(day_in_year= day_year(), full= 1).order_by(Dustbin.id.desc()).first() full_day = full_day.full if full_day==0 or full_day==1: return full_day else: return 0 @app.route('/') @app.route('/home' ,methods=['POST','GET']) def home(): if not current_user.is_authenticated: return redirect(url_for('login')) return render_template('home.html') host='192.168.1.7' port = 65431 @app.route('/data',methods=['GET']) def test(): try: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((host, port)) my_input='Data' my_inp=my_input.encode('utf-8') s.sendall(my_inp) data=s.recv(1024).decode('utf-8') #status x_tem,y_tem= data_from_server(data) x = datetime.now().strftime('%H') #time_in_hour x = int(x) if is_new_hour(x) or int(x_tem) == 100: #day_of_week day_of_week = day_number() #holiday holi=is_holiday(day_of_week) #last_status previous_status = get_last_status() #amount_per_day amount = get_amount_per_day(x_tem) day_in_year = day_year() full = is_full() range_k= 0 range_r = 1 if x_tem>= 75: range_k=1 range_r=4 if x_tem>25 and x_tem<= 50: range_r =2 elif x_tem >50 and x_tem< 75: range_r=3 d=Dustbin( day_of_week = day_number, holiday = holi, time_in_hour = x, status =x_tem , previous_status = previous_status, amount_per_day = amount, full = full, range_knn = 0, range_rf =3, day_in_year=day_in_year) db.session.add(d) db.session.commit() my_input='Quit' my_inp=my_input.encode('utf-8') s.sendall(my_inp) return jsonify(x_tem) except: pass finally: s.close() @app.route('/about') def about(): return render_template('about.html', title='About') @app.route("/login", methods=['GET','POST']) def login(): if current_user.is_authenticated: return redirect(url_for('home')) form=LoginForm() if form.validate_on_submit(): user= User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page= request.args.get('next') return redirect(next_page) if next_page else redirect(url_for('home')) else: flash('Login Unsuccessful. Please check email and password','danger') return render_template('login.html',title='Login', form=form) @app.route("/register", methods=['GET','POST']) def register(): form= RegisterationForm() if form.validate_on_submit(): hash_password=bcrypt.generate_password_hash(form.password.data).decode('utf-8') user= User(username=form.username.data, email=form.email.data, password=hash_password) db.session.add(user) db.session.commit() flash('Your account has been created!', 'success') return redirect(url_for('home')) return render_template('register.html', title='Register', form=form) @app.route("/logout") def logout(): logout_user() return redirect(url_for('login')) def save_picture(form_picture): random_hex=secrets.token_hex(8) _, f_ext= os.path.splitext(form_picture.filename) picture_fn= random_hex + f_ext picture_path=os.path.join(app.root_path,'static/pics',picture_fn) output_size= (125,125) i= Image.open(form_picture) i.thumbnail(output_size) i.save(picture_path) return picture_fn @app.route("/account", methods=['GET','POST']) @login_required def account(): form= UpdateAccountForm() if form.validate_on_submit(): if form.picture.data: picture_file=save_picture(form.picture.data) current_user.image_file=picture_file current_user.username= form.username.data current_user.email= form.email.data db.session.commit() flash('Your account has been updated!', 'success') return redirect(url_for('account')) elif request.method == 'GET': form.username.data= current_user.username form.email.data= current_user.email image_file= url_for('static',filename='pics/'+ current_user.image_file) return render_template('account.html',title='Account', image_file=image_file, form=form) @app.route("/predict",methods=['GET','POST']) def pre(): return render_template('predict.html') def is_holiday(day_of_week): if day_of_week==6 or day_of_week==7: return 1 else: return 0 @app.route("/result",methods=['GET','POST']) def result(): """ with open('flaskApp\data\wasteManagment.csv','w') as output_file: output_csv=csv.writer(output_file) output_csv.writerow(['day_of_week','time_in_hour','status','range_knn','range_rf' ]) for row in db.session.query(Dustbin).all(): output_csv.writerow([row.day_of_week, row.status]) df = pd.read_csv("flaskApp\data\wasteManagment.csv") df_data=df[['day_of_week','time_in_hour','status','range_knn','range_rf']] df_x= df_data['day_of_week'] df_y=df_data.status corpus=df_x cv= CountVectorizer() X=cv.fit_transform(corpus) from sklearn.model_selection import train_test_split X_train,X_test, y_train,y_test= train_test_split(X,df_y,test_size=0.70, random_state=42) from sklearn.naive_bayes import MultinomialNB clf=MultinomialNB() clf.fit(X_train,y_train) clf.score(X_test,y_test) if request.method=='POST': comment=request.form['comment'] data=[comment] vect= cv.transform(data).toarray() my_prediction=clf.predict(vect) my_prediction=int(my_prediction) return render_template('result.html',prediction=my_prediction) """ #knn df = pd.read_csv("flaskApp\data\wasteManagment.csv", header=None, skiprows=1) X = df.iloc[:,0:7] y = df.iloc[:,7] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size= 0.3) sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) n=math.sqrt(len(y_test)) m=int(n) if m%2 == 0: m=m-1 classifier = KNeighborsClassifier(n_neighbors= m, p=2,metric='euclidean') classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) holiday=0 if request.method=='POST': comment=request.form['comment'] comment =int(day_value.get(comment)) holiday=is_holiday(comment) dt = datetime.now().strftime('%H') previous_status='previous_status' data=[comment,holiday,dt,get_last_status(),get_last_row('previous'),get_last_row('amount_per_day'),get_last_row('full')] ww=np.array(data).reshape(1,-1) result_predict=classifier.predict(ww) #random forest dataset = pd.read_csv("flaskApp\data\wasteManagment.csv", header=None, skiprows=1) target_names = ['not recommended','slightly recommended','recommended','highly recommended'] feature_names = ['day_of_week','holiday','time_in_hour','status','previous_status','amount_per_day','full'] X = dataset.iloc[:, :-3].values y = dataset.iloc[:, 8].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20) clf = RandomForestClassifier(n_estimators = 4) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) rf_resutl=clf.predict([[comment,holiday,dt,get_last_status(),get_last_row('previous'),get_last_row('amount_per_day'),get_last_row('full')]]) rf_resutl[0]=rf_resutl[0]*25 return render_template('result.html',prediction=result_predict[0], rf= rf_resutl[0]) def send_reset_email(user): token = user.get_reset_token() msg = Message('Password Reset Request', sender= 'noreply@demo.com',recipients=[user.email]) msg.body = f'''To reset you password, visit the following link: {url_for('reset_token', token=token, _external= True)} If you did not make this request then simply ignore this email and no change will be made. ''' mail.send(msg) @app.route("/reset_password", methods=['GET','POST']) def reset_request(): if current_user.is_authenticated: return redirect(url_for('home')) form= RequestResetForm() if form.validate_on_submit(): user= User.query.filter_by(email= form.email.data).first() send_reset_email(user) flash('AN email has been sent to reset your passeord','info') return redirect(url_for('login')) return render_template('reset_request.html', title= 'Reset Password', form=form) @app.route("/reset_password/<token>", methods=['GET','POST']) def reset_token(token): if current_user.is_authenticated: return redirect(url_for('home')) user = User.verify_reset_token(token) if user is None: flash('That is an invalid or expired token','warning') return redirect(url_for('reset_request')) form= ResetPasswordForm() if form.validate_on_submit(): hash_password=bcrypt.generate_password_hash(form.password.data).decode('utf-8') user.password = hash_password db.session.commit() flash('Your password has been updated! You are now able to log in', 'success') return redirect(url_for('login')) return render_template('reset_token.html', title= 'Reset Password', form = form)
from collections import OrderedDict class BaseModel(object): _properties = None _serializable = None def __init__(self, obj=None): if obj is None: obj = {} if isinstance(obj, BaseModel): properties = obj.serialize() else: properties = obj self._properties = {} self._serializable = OrderedDict() self.init() for key, value in properties.items(): if hasattr(self, key): setattr(self, key, value) def init(self): pass def __getattr__(self, key): if key in self._properties: return self._properties[key][0]() raise AttributeError def __setattr__(self, key, value): if self._properties is None: super().__setattr__(key, value) return if key in self._properties: self._properties[key][1](value) return super().__setattr__(key, value) def add_property(self, key, default=None, writable=True): self._serializable[key] = default def getter(): return self._serializable[key] def setter(value): if writable: self._serializable[key] = value self._properties[key] = [getter, setter] def add_array_property(self, key, allow_none=False): self._serializable[key] = None if allow_none else [] def getter(): return self._serializable[key] def setter(value): assert value is None or isinstance(value, list) self._serializable[key] = [] if value is None and not allow_none else value self._properties[key] = [getter, setter] def add_model_property(self, key, model_class, allow_none=False): self._serializable[key] = None if allow_none else model_class() def getter(): return self._serializable[key] def setter(value): assert value is None or isinstance(value, (dict, OrderedDict, model_class)) if value is None and not allow_none: self._serializable[key] = model_class() else: self._serializable[key] = model_class(value) self._properties[key] = [getter, setter] @staticmethod def _serialize(obj): if isinstance(obj, OrderedDict): output = OrderedDict() for key, value in obj.items(): output[key] = BaseModel._serialize(value) return output if isinstance(obj, list): return [BaseModel._serialize(item) for item in obj] if isinstance(obj, BaseModel): return obj.serialize() return obj def serialize(self): return self._serialize(self._serializable)
""" Creación del tipo especifico del sensor de temperatura """ from agentes_sensores.proxy_sensor_temperatura import * class FactoryProxySensorTemperatura: @staticmethod def crear(tipo: str) -> AbsProxySensorTemperatura: if tipo == "archivo": return ProxySensorTemperaturaArchivo() elif tipo == "socket": return ProxySensorTemperaturaSocket() else: return None
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or 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 threading from twitter.common.lang import Lockable def test_basic_mutual_exclusion(): class Foo(Lockable): def __init__(self): self.counter = 0 self.start_event = threading.Event() self.finish_event = threading.Event() Lockable.__init__(self) @Lockable.sync def pooping(self): self.counter += 1 self.start_event.set() self.finish_event.wait() f = Foo() class FooSetter(threading.Thread): def run(self): f.pooping() fs1 = FooSetter() fs2 = FooSetter() fs1.start() fs2.start() # yield threads f.start_event.wait(timeout=1.0) assert f.start_event.is_set() # assert mutual exclusion assert f.counter == 1 # unblock ==> other wakes up f.start_event.clear() f.finish_event.set() f.start_event.wait(timeout=1.0) assert f.start_event.is_set() assert f.counter == 2
class Truck: def __init__(self, brand, photo_file_name, carrying, body_whl): self.brand = brand self.photo_file_name = photo_file_name self.carrying = carrying self.body_whl = body_whl try: raw_body_whl = body_whl.split('x') body_length = float(raw_body_whl[0]) body_width = float(raw_body_whl[1]) body_height = float(raw_body_whl[2]) except ValueError: body_length = 0 body_width = 0 body_height = 0 self.body_length = body_length self.body_width = body_width self.body_height = body_height def get_body_volume(self): return self.body_height * self.body_width * self.body_length
import os import numpy if __name__ == '__main__': loadPath = 'D:/PythonProjects_Data/CMU_MOSEI/Step1_StartEndCut/' labelCounter = {1: 0, 0: 0} for fileName in os.listdir(loadPath): data = numpy.reshape(numpy.genfromtxt(fname=os.path.join(loadPath, fileName), dtype=float, delimiter=','), [-1, 3]) for sample in data: # print(sample) if sample[0] > 0: labelCounter[1] += 1 else: labelCounter[0] += 1 for sample in labelCounter.keys(): print(sample, labelCounter[sample])
from matrix_utils import getReflection def getPlotData(resultMatrix, superResultMatrix): r = getReflection(resultMatrix) T = 1 / (superResultMatrix[0][0]) print(T) R = superResultMatrix[1][0]/superResultMatrix[0][0] return [r, T, R]
#!/usr/bin/env python from aiokafka import ConsumerRecord import logging from sqlalchemy.engine import RowProxy from typing import ( Dict, List, Optional, ) import ujson from hummingbot.logger import HummingbotLogger from hummingbot.connector.exchange.loopring.loopring_order_book_message import LoopringOrderBookMessage from hummingbot.core.event.events import TradeType from hummingbot.core.data_type.order_book cimport OrderBook from hummingbot.core.data_type.order_book_message import ( OrderBookMessage, OrderBookMessageType, ) _dob_logger = None cdef class LoopringOrderBook(OrderBook): @classmethod def logger(cls) -> HummingbotLogger: global _dob_logger if _dob_logger is None: _dob_logger = logging.getLogger(__name__) return _dob_logger @classmethod def snapshot_message_from_exchange(cls, msg: Dict[str, any], timestamp: float, metadata: Optional[Dict] = None) -> LoopringOrderBookMessage: if metadata: msg.update(metadata) return LoopringOrderBookMessage(OrderBookMessageType.SNAPSHOT, msg, timestamp) @classmethod def diff_message_from_exchange(cls, msg: Dict[str, any], timestamp: Optional[float] = None, metadata: Optional[Dict] = None) -> OrderBookMessage: if metadata: msg.update(metadata) return LoopringOrderBookMessage(OrderBookMessageType.DIFF, msg, timestamp) @classmethod def trade_message_from_exchange(cls, msg: Dict[str, any], metadata: Optional[Dict] = None): ts = metadata["ts"] return OrderBookMessage(OrderBookMessageType.TRADE, { "trading_pair": metadata["topic"]["market"], "trade_type": float(TradeType.SELL.value) if (msg[2] == "SELL") else float(TradeType.BUY.value), "trade_id": msg[1], "update_id": ts, "price": msg[4], "amount": msg[3] }, timestamp=ts * 1e-3) @classmethod def snapshot_message_from_db(cls, record: RowProxy, metadata: Optional[Dict] = None) -> OrderBookMessage: msg = record.json if type(record.json)==dict else ujson.loads(record.json) return LoopringOrderBookMessage(OrderBookMessageType.SNAPSHOT, msg, timestamp=record.timestamp * 1e-3) @classmethod def diff_message_from_db(cls, record: RowProxy, metadata: Optional[Dict] = None) -> OrderBookMessage: return LoopringOrderBookMessage(OrderBookMessageType.DIFF, record.json) @classmethod def snapshot_message_from_kafka(cls, record: ConsumerRecord, metadata: Optional[Dict] = None) -> OrderBookMessage: msg = ujson.loads(record.value.decode()) return LoopringOrderBookMessage(OrderBookMessageType.SNAPSHOT, msg, timestamp=record.timestamp * 1e-3) @classmethod def diff_message_from_kafka(cls, record: ConsumerRecord, metadata: Optional[Dict] = None) -> OrderBookMessage: msg = ujson.loads(record.value.decode()) return LoopringOrderBookMessage(OrderBookMessageType.DIFF, msg) @classmethod def trade_receive_message_from_db(cls, record: RowProxy, metadata: Optional[Dict] = None): return LoopringOrderBookMessage(OrderBookMessageType.TRADE, record.json) @classmethod def from_snapshot(cls, snapshot: OrderBookMessage): raise NotImplementedError("loopring order book needs to retain individual order data.") @classmethod def restore_from_snapshot_and_diffs(self, snapshot: OrderBookMessage, diffs: List[OrderBookMessage]): raise NotImplementedError("loopring order book needs to retain individual order data.")
import sys import math sys.path.insert(0, '/home/machen/face_expr') from dataset_toolkit.compress_utils import get_zip_ROI_AU import os from collections import defaultdict from config import DATA_PATH,ROOT_PATH from functools import lru_cache import copy import numpy as np import math from PIL import Image, ImageEnhance import config import multiprocessing as mp import time def AU_stats_DISFA(label_file_dir, skip_frame=1): AU_count = defaultdict(int) img_idx_AU = defaultdict(set) for file_name in os.listdir(label_file_dir): subject_name = file_name for au_file in os.listdir(label_file_dir+"/"+file_name): AU = au_file[au_file.index("_au")+3:au_file.rindex(".")] with open(label_file_dir + os.sep + file_name + os.sep + au_file, "r") as file_obj: for idx, line in enumerate(file_obj): if idx % skip_frame != 0: # 每一行是一个frame图片 continue lines = line.strip().split(",") frame = int(lines[0]) AU_level = lines[1] if AU_level != "0": AU_count[AU] += 1 img_idx_AU["DISFA:{0}/{1}".format(subject_name, frame)].add(AU) return AU_count, img_idx_AU def AU_stats_BP4D(label_file_dir, skip_frame=1): ''' :param label_file_dir: dict which contain all AU label file :return: dict = {AU : sample_count} ''' AU_count = defaultdict(int) img_idx_AU = defaultdict(set) for file_name in os.listdir(label_file_dir): subject_name = file_name[:file_name.index("_")] sequence_name = file_name[file_name.index("_") + 1:file_name.rindex(".")] AU_column_idx = {} with open(label_file_dir + "/" + file_name, "r") as au_file_obj: for idx, line in enumerate(au_file_obj): # 每行是一帧画面的label if idx == 0: # header specify Action Unit for col_idx, AU in enumerate(line.split(",")[1:]): AU_column_idx[AU] = col_idx + 1 # read header continue # read head over , continue if idx % skip_frame != 0: continue lines = line.split(",") frame = lines[0] au_label_set = set([AU for AU in AU_ROI.keys() \ if int(lines[AU_column_idx[AU]]) == 1]) if len(au_label_set) > 0: img_idx_AU["BP4D:{0}/{1}/{2}".format(subject_name, sequence_name, frame)].update(au_label_set) for AU in au_label_set: AU_count[AU] += 1 return AU_count, img_idx_AU def AU_repeat_level(level_num, AU_count): ''' :param level_num: how many AU (repeat) level are there in AU class number AU_count: dict key=AU, value=count :return: AU_level is a dict, which value is level_index, lower level_index means lower repeat level, higher level means higher repeat level ''' split_list = lambda A, n=level_num: [A[i:i + n] for i in range(0, len(A), n)] AU_level = dict() # print("sublist:{}".format(split_list(sorted(AU_count.items(), key=lambda e:e[1], reverse=True)))) for idx, sub in enumerate(split_list(sorted(AU_count.items(), key=lambda e:e[1], reverse=True))): for AU, count in sub: AU_level[AU] = idx return AU_level # 混合不同数据库,再用锐化之类的增多小类的样本 def database_mix_enhance_balance_check(): ''' 结论:仍然会被捆绑效应所限,不会平衡 :return: ''' AU_count, img_idx_AU_DISFA = AU_stats_DISFA("/home/machen/dataset/DISFA/AU_labels/", skip_frame=1) AU_count_BP4D, img_idx_AU_BP4D = AU_stats_BP4D("/home/machen/dataset/BP4D/AUCoding/") for AU, count in AU_count_BP4D.items(): AU_count[AU] += count #mix level_repeat = {0: 0, 1: 4, # 锐化,模糊,原图, 翻转 2: 8,} # 左右翻转 x 锐化,模糊,原图 或 左右翻转 x 对比度增强,对比度降低,原图 #3: 10} # 左右翻转 x (锐化,模糊,对比度增强,对比度降低, 原图) AU_level = AU_repeat_level(math.ceil(len(AU_count)/len(level_repeat)), AU_count) img_idx_AU_DISFA.update(img_idx_AU_BP4D) #mix mix_database = img_idx_AU_DISFA enhance_mix_database = copy.deepcopy(mix_database) for img_id, AU_labels in mix_database.items(): AU_labels = list(AU_labels) max_repeat_times = level_repeat[max(AU_level[AU] for AU in AU_labels)] # 计算每个图的label中需要重复最多的那个AU for repeat_idx in range(max_repeat_times): enhance_mix_database["{0}_{1}".format(img_id, repeat_idx)].update(AU_labels) # now stats enhance_mix_database enhance_AU_count = defaultdict(int) for img_id, AU_labels in enhance_mix_database.items(): for AU in AU_labels: enhance_AU_count[AU] += 1 print("remains lost count:{0} interset count:{1}".format(len(set(list(mix_database.keys())) - set(list(enhance_mix_database.keys()))), len(set(list(mix_database.keys())) & set(list(enhance_mix_database.keys()))))) return enhance_AU_count def make_dir_not_exists(abs_path): dir_name = os.path.dirname(abs_path) if not os.path.exists(dir_name): os.makedirs(dir_name, exist_ok=True) def AU_calcuate_from_dataset(dataset): AU_count = defaultdict(int) for img_path, AU_set in dataset.items(): for AU in AU_set: if not AU.startswith("?"): AU_count[AU]+=1 return AU_count all_new_path_lst = [] enhance_mix_database = defaultdict(set) img_from = {} def append_new_path_result(result): new_path_lst, orig_AU_labels, img_path = result print("a job done:{}".format(img_path)) all_new_path_lst.extend(new_path_lst) for new_img_path in new_path_lst: enhance_mix_database[new_img_path].update(orig_AU_labels) # enhance img_from[new_img_path] = img_path def async_generate_image_save(new_path_lst, repeat_level, subject_name, sequence_name, frame_name, orig_AU_labels, img_path, need_generate): transform_func = { "sharp": lambda im: ImageEnhance.Sharpness(im).enhance(3.0), "fuzzy": lambda im: ImageEnhance.Sharpness(im).enhance(0.0), "contrast_improve": lambda im: ImageEnhance.Contrast(im).enhance(1.6), "contrast_decrease": lambda im: ImageEnhance.Contrast(im).enhance(0.6), "flip": lambda im: im.transpose(Image.FLIP_LEFT_RIGHT) } abs_new_path = lambda subject_name, sequence_name, frame, trans: ENHANCE_BALANCE_PATH["BP4D"] + \ os.sep + "{0}/{1}/{2}({3}).jpg".format(subject_name, sequence_name, frame, trans) relative_new_path = lambda subject_name, sequence_name, frame, trans: "BP4D/BP4D_enhance_balance/{0}/{1}/{2}({3}).jpg".format(subject_name, sequence_name, frame, trans) print("opening file :{}".format(img_path)) im = Image.open(ROOT_PATH+os.sep+img_path) if repeat_level == 1: enhance_names = ["fuzzy", "sharp", "flip","flip_sharp","flip_fuzzy"] for enhance_name in enhance_names: rel_im_path = relative_new_path(subject_name, sequence_name, frame_name, enhance_name) new_path_lst.append(rel_im_path) if need_generate: fuzzy_im = transform_func["fuzzy"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "fuzzy") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): fuzzy_im.save(new_im_path) sharp_im = transform_func["sharp"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "sharp") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): sharp_im.save(new_im_path) flip_im = transform_func["flip"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): flip_im.save(new_im_path) flip_sharp_im = transform_func["sharp"](flip_im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip_sharp") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): flip_sharp_im.save(new_im_path) fuzzy_sharp_im = transform_func["fuzzy"](flip_im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip_fuzzy") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): fuzzy_sharp_im.save(new_im_path) elif repeat_level == 2: enhance_names = ["fuzzy", "sharp", "contrast+", "contrast-", "flip", "flip_sharp", "flip_fuzzy", "flip_contrast+", "flip_contrast-"] for enhance_name in enhance_names: rel_im_path = relative_new_path(subject_name, sequence_name, frame_name, enhance_name) new_path_lst.append(rel_im_path) if need_generate: fuzzy_im = transform_func["fuzzy"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "fuzzy") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): fuzzy_im.save(new_im_path) sharp_im = transform_func["sharp"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "sharp") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): sharp_im.save(new_im_path) contrast_improve_im = transform_func["contrast_improve"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "contrast+") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): contrast_improve_im.save(new_im_path) contrast_decrease_im = transform_func["contrast_decrease"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "contrast-") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): contrast_decrease_im.save(new_im_path) flip_im = transform_func["flip"](im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): flip_im.save(new_im_path) flip_sharp_im = transform_func["sharp"](flip_im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip_sharp") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): flip_sharp_im.save(new_im_path) fuzzy_sharp_im = transform_func["fuzzy"](flip_im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip_fuzzy") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): fuzzy_sharp_im.save(new_im_path) flip_contrast_improve_im = transform_func["contrast_improve"](flip_im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip_contrast+") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): flip_contrast_improve_im.save(new_im_path) flip_contrast_decrease_im = transform_func["contrast_decrease"](flip_im) new_im_path = abs_new_path(subject_name, sequence_name, frame_name, "flip_contrast-") make_dir_not_exists(new_im_path) if not os.path.exists(new_im_path): flip_contrast_decrease_im.save(new_im_path) return new_path_lst, orig_AU_labels, img_path # 最终外界程序调用这个函数进行平衡化, 这个函数再平衡化的过程中也会生成锐化模糊过的图片存到硬盘 def database_enhance_balance(dataset, AU_count, drop_big_label=False): ''' :param dataset: key是img_path, value是AU_label set,包含AU=0,表示背景 :param AU_count: key是AU str类型, value是count, 包含AU=0,表示背景 :param drop_big_label: :return: ''' level_repeat = {0: 0, 1: 5, # 翻转 x (锐化,模糊,原图) 原图不能算一次多生成的图 2: 9, } # 左右翻转 x (锐化,模糊,对比度增强,对比度降低, 原图) 翻转后啥事都不干算一张新图 AU_level = AU_repeat_level(math.ceil(len(AU_count) / (len(level_repeat))), AU_count) AU_level['0'] = 0 # 全都是背景那就是0 print(AU_level) mix_database = dataset enhance_mix_database.update(mix_database) print("after deep copy") pool = mp.Pool(processes=mp.cpu_count()) for idx,(img_path, AU_labels) in enumerate(mix_database.items()): orig_AU_labels = copy.copy(AU_labels) AU_labels = list(filter(lambda AU: not AU.startswith("?"), list(AU_labels))) if len(AU_labels) == 0: print("no AU occur! {}".format(img_path)) max_repeat_times = level_repeat[max(AU_level[AU] for AU in AU_labels)] # 计算每个图的label中需要重复最多的那个AU repeat_level = max(AU_level[AU] for AU in AU_labels) subject_name = img_path.split("/")[-3] sequence_name = img_path.split("/")[-2] frame_name = img_path.split("/")[-1] frame_name = frame_name[:frame_name.rindex(".")] new_path_lst = [] need_generate = False #FIXME pool.apply_async(async_generate_image_save, args=(new_path_lst, repeat_level, subject_name, sequence_name, frame_name, orig_AU_labels, img_path,need_generate ), callback=append_new_path_result) pool.close() pool.join() print("all process done, img_from:{}".format(len(img_from))) if not drop_big_label: return enhance_mix_database, img_from print("img enhance generate done, new_database:{}".format(len(enhance_mix_database))) AU_img_path = defaultdict(list) for img_path, AU_labels in enhance_mix_database.items(): # enhance AU_labels = filter(lambda AU: not AU.startswith("?"), list(AU_labels)) for AU in AU_labels: AU_img_path[AU].append(img_path) picked_set = set() picked_AU_count = defaultdict(int) pick_count = 40000 # FIXME int(np.median(sorted([len(lst) for lst in AU_img_path.values()]))) for AU, img_id_lst in sorted(AU_img_path.items(), key=lambda e: len(e[1])): # print(AU, len(img_id_lst)) pick_set = set(img_id_lst) & picked_set remain_set = set(img_id_lst) - pick_set current_pick_count = min(pick_count, len(pick_set)) remain_len = np.min([pick_count - current_pick_count, len(remain_set), max(0, pick_count - picked_AU_count[AU])]) # 应该修改为看看历史上已选择AU有多少个了 choice_array = np.array([]) if len(pick_set) > 0: choice_array = np.random.choice(list(pick_set), current_pick_count, replace=False) # 先挑选以前已经挑过的 remain_array = np.random.choice(list(remain_set), remain_len, replace=False) # 再挑补集 # print("choice_array:{0}, remain_array:{1} add:{2}".format(len(choice_array), len(remain_array), len(choice_array)+ len(remain_array))) choice_array = np.hstack((choice_array, remain_array)) picked_set.update(choice_array.tolist()) new_enhance_dataset = defaultdict(set) for pick_img_path in picked_set: new_enhance_dataset[pick_img_path] = enhance_mix_database[pick_img_path] return new_enhance_dataset, img_from # 下面这个函数解决分类不平衡问题的最佳方案,但会丢失大类的训练数据 def database_mixenhance_uniform_pick_check(): # AU_count, img_idx_AU_DISFA = AU_stats_DISFA("/home/machen/dataset/DISFA/AU_labels/", skip_frame=1) AU_count_BP4D, img_idx_AU_BP4D = AU_stats_BP4D(config.DATA_PATH["BP4D"]+"/AUCoding/") # img_idx_AU_DISFA.update(img_idx_AU_BP4D) # mix # # for AU, count in AU_count_BP4D.items(): # AU_count[AU] += count # mix add level_repeat = {0: 0, 1: 5, # 锐化,模糊,原图, 翻转 2: 9, } # 左右翻转 x 锐化,模糊,原图 或 左右翻转 x 对比度增强,对比度降低,原图 #3: 10} # 左右翻转 x (锐化,模糊,对比度增强,对比度降低, 原图) AU_level = AU_repeat_level(math.ceil(len(AU_count_BP4D) /(len(level_repeat))), AU_count_BP4D) print(AU_level) mix_database = img_idx_AU_BP4D enhance_mix_database = copy.deepcopy(mix_database) for img_id, AU_labels in mix_database.items(): AU_labels = list(AU_labels) max_repeat_times = level_repeat[max(AU_level[AU] for AU in AU_labels)] # 计算每个图的label中需要重复最多的那个AU for repeat_idx in range(max_repeat_times): enhance_mix_database["{0}_{1}".format(img_id, repeat_idx)].update(AU_labels) # enhance AU_imgid = defaultdict(list) for img_id, AU_labels in enhance_mix_database.items(): # enhance for AU in AU_labels: AU_imgid[AU].append(img_id) picked_set = set() picked_AU_count = defaultdict(int) pick_count =30000 # int(np.median(sorted([len(lst) for lst in AU_imgid.values()]))) for AU, img_id_lst in sorted(AU_imgid.items(), key=lambda e:len(e[1])): # print(AU, len(img_id_lst)) pick_set = set(img_id_lst) & picked_set remain_set = set(img_id_lst) - pick_set current_pick_count = min(pick_count, len(pick_set)) remain_len = np.min([pick_count - current_pick_count, len(remain_set), max(0, pick_count - picked_AU_count[AU])]) # 应该修改为看看历史上已选择AU有多少个了 choice_array = np.array([]) if len(pick_set) > 0: choice_array = np.random.choice(list(pick_set), current_pick_count, replace=False) # 先挑选以前已经挑过的 remain_array = np.random.choice(list(remain_set), remain_len, replace=False) # 再挑补集 # print("choice_array:{0}, remain_array:{1} add:{2}".format(len(choice_array), len(remain_array), len(choice_array)+ len(remain_array))) choice_array = np.hstack((choice_array, remain_array)) for choice_img_id in choice_array: if choice_img_id not in picked_set: for enhance_AU_label in enhance_mix_database[choice_img_id]: picked_AU_count[enhance_AU_label] += 1 picked_set.update(choice_array.tolist()) choice_AU_count = defaultdict(int) print("all choice count:{}".format(len(picked_set))) #stats again for img_id in picked_set: AU_labels = enhance_mix_database[img_id] for AU in AU_labels: choice_AU_count[AU] += 1 print("remains lost count:{0} interset count:{1}".format(len(set(list(mix_database.keys())) - picked_set), len(set(list(mix_database.keys())) & picked_set))) return choice_AU_count if __name__ == "__main__": stats_DISFA, _ = AU_stats_DISFA(config.DATA_PATH["DISFA"] + "/AU_labels/", skip_frame=1) stats_BP4D, img_idx_AU = AU_stats_BP4D(config.DATA_PATH["BP4D"]+"/AUCoding/") print("BP4D all len:{}".format(len(img_idx_AU))) # for AU, count in stats2.items(): # stats[AU] += count print("--------------------------------------------------------------") orig_first_count = list(sorted(stats_BP4D.items(), key=lambda e:e[1], reverse=True))[0][1] for AU, count in sorted(stats_BP4D.items(), key=lambda e:e[1], reverse=True): print("BP4D AU={0}, count={1}, ratio={2}".format(AU, count, orig_first_count/count)) print("---------------------------------------------------") orig_first_count = list(sorted(stats_DISFA.items(), key=lambda e: e[1], reverse=True))[0][1] for AU, count in sorted(stats_DISFA.items(), key=lambda e: e[1], reverse=True): print("DISFA AU={0}, count={1}, ratio={2}".format(AU, count, orig_first_count / count)) print("---------------------------------------------------") print("===================================") import config print("DISFA - BP4D", sorted(set(stats_DISFA.keys()) - set(stats_BP4D.keys()))) print("BP4D - DISFA", set(stats_BP4D.keys()) - set(stats_DISFA.keys())) print("BP4D sorted AU: ", sorted(stats_BP4D.keys())) print("DISFA sorted AU: ", sorted(stats_DISFA.keys())) print("AU_ROI config & BP4D:", sorted(map(int , set(config.AU_ROI.keys()) & set(stats_BP4D.keys())))) print("AU_ROI config & DISFA:", sorted(map(int , set(config.AU_ROI.keys()) & set(stats_DISFA.keys())))) print("===================================") choice_AU_count = database_mixenhance_uniform_pick_check() first_count = list(sorted(choice_AU_count.items(), key=lambda e:e[1], reverse=True))[0][1] for AU, count in sorted(choice_AU_count.items(), key=lambda e:e[1], reverse=True): print("AU={0}, count={1}, ratio={2}".format(AU, count, first_count/count)) '''BP4D dataset AU=10, count=87271 AU=12, count=82531 AU=7, count=80617 AU=14, count=68376 AU=6, count=67677 AU=17, count=50407 AU=1, count=31043 AU=4, count=29755 AU=2, count=25110 AU=15, count=24869 AU=23, count=24288 AU=24, count=22229 AU=9, count=8512 AU=11, count=7184 AU=16, count=6593 AU=28, count=5697 AU=5, count=5693 AU=20, count=3644 AU=27, count=1271 AU=22, count=606 AU=18, count=568 AU=13, count=138 ''' ''' BP4D and DISFA mix combine AU=12, count=113325 combine AU=10, count=87271 combine AU=6, count=87161 combine AU=7, count=80617 combine AU=14, count=68376 combine AU=17, count=63337 combine AU=4, count=54349 combine AU=25, count=46052 combine AU=1, count=39821 combine AU=15, count=32731 combine AU=2, count=32474 combine AU=26, count=24976 combine AU=23, count=24288 combine AU=24, count=22229 combine AU=9, count=15644 combine AU=5, count=8422 combine AU=20, count=8176 combine AU=11, count=7184 combine AU=16, count=6593 combine AU=28, count=5697 combine AU=27, count=1271 combine AU=22, count=606 combine AU=18, count=568 combine AU=13, count=138 '''
#!/usr/bin/env python """ _ApMonLite_ Lighter more API friendly way to send data to ApMon """ __all__ = []
def minSubarray(self, nums: List[int], p: int) -> int: n = len(nums) mod = sum(nums)%p if mod==0: return 0 res = n s = 0 hashmap = {0: -1} for i, num in enumerate(nums): s += num key = (s%p - mod) # key = key % p if key<0: key +=p if key in hashmap: res = min(res, i-hashmap[key]) hashmap[s%p] = i return res if res < n else -1
import load sample = '8 0 0 2 0 0 0 4 6 0 0 7 9 0 0 0 0 0 1 0 0 0 0 0 5 0 0 0 0 0 5 0 0 0 3 2 4 0 8 0 0 0 7 0 1 3 2 0 0 0 7 0 0 0 0 0 6 0 0 0 0 0 9 0 0 0 0 0 3 2 0 0 2 8 0 0 0 6 0 0 3' puz = load.Constructor(sample) puzzle = puz.convert_to_puzzle() print(puzzle.total_possibilities_left) puzzle.pretty_print() puzzle.solve() puzzle.pretty_print()
""" Contains upgrade tasks that are executed when the application is being upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`. """ from sqlalchemy import Column from onegov.core.orm.types import UTCDateTime from onegov.core.upgrade import upgrade_task from sqlalchemy.sql.expression import text from typing import TYPE_CHECKING if TYPE_CHECKING: from onegov.core.upgrades import UpgradeContext @upgrade_task('Add parent order index') def add_parent_order_index(context: 'UpgradeContext') -> None: context.operations.create_index( 'page_order', 'pages', [ text('"parent_id" NULLS FIRST'), text('"order" NULLS FIRST') ] ) @upgrade_task('Adds publication dates to pages') def add_publication_dates_to_pages(context: 'UpgradeContext') -> None: if not context.has_column('pages', 'publication_start'): context.operations.add_column( 'pages', Column('publication_start', UTCDateTime, nullable=True) ) if not context.has_column('pages', 'publication_end'): context.operations.add_column( 'pages', Column('publication_end', UTCDateTime, nullable=True) ) @upgrade_task('Make pages polymorphic type non-nullable') def make_pages_polymorphic_type_non_nullable( context: 'UpgradeContext' ) -> None: if context.has_table('pages'): context.operations.execute(""" UPDATE pages SET type = 'generic' WHERE type IS NULL; """) context.operations.alter_column('pages', 'type', nullable=False)
from django import forms from advertising.models import AdvertisingCampaign, AdvertisingType from cities.models import Region from django.core.files.images import get_image_dimensions from djmoney.forms.fields import MoneyField from moneyed import Money, CAD from decimal import Decimal from accounts.widgets import ChooseUserContextWidget class AdvertisingSetupForm(forms.ModelForm): regions = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Region.objects.filter(country__code="CA"), required=False ) types = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=AdvertisingType.objects.filter(active=True), required=False ) active_from = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), required=False) active_to = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), required=False) class Meta: model = AdvertisingCampaign fields = ( 'name', 'regions', 'all_of_canada', 'website', 'venue_account', 'active_from', 'active_to' ) def __init__(self, account, *args, **kwargs): super(AdvertisingSetupForm, self).__init__(*args, **kwargs) self.account = account self.fields['venue_account'].widget = ChooseUserContextWidget(account) self.fields['name'].error_messages['required'] = 'Campaign name is required' self.fields['website'].error_messages['required'] = 'Website URL is required' def clean(self): cleaned_data = self.cleaned_data all_of_canada = cleaned_data["all_of_canada"] regions = cleaned_data["regions"] if not all_of_canada and not regions: raise forms.ValidationError("You should choose at least one region") if "advertising_types" not in self.data: raise forms.ValidationError("You should create at least one advertising type") advertising_types = self.data.getlist("advertising_types") advertising_payment_types = { int(key.split(".")[1]): value for key, value in self.data.iteritems() if key.startswith("advertising_payment_type") } advertising_images = { int(key.split(".")[1]): value for key, value in self.files.iteritems() if key.startswith("advertising_image") } advertising_types = AdvertisingType.objects.filter(active=True, id__in=map(lambda s: int(s), advertising_types)) cleaned_data["advertising_payment_types"] = advertising_payment_types cleaned_data["advertising_images"] = advertising_images for advertising_type in advertising_types: if advertising_type.id not in advertising_images: raise forms.ValidationError("You should upload image for all advertising types") dimensions = get_image_dimensions(advertising_images[advertising_type.id]) if dimensions is None: raise forms.ValidationError("You can upload only image") width, height = dimensions if advertising_type.width != width or advertising_type.height != height: raise forms.ValidationError("Advertising %s should have %dx%d dimension, you upload image with %dx%d" % ( advertising_type.name, advertising_type.width, advertising_type.height, width, height ) ) return cleaned_data class AdvertisingCampaignEditForm(AdvertisingSetupForm): def clean(self): cleaned_data = self.cleaned_data all_of_canada = cleaned_data["all_of_canada"] regions = cleaned_data["regions"] if not all_of_canada and not regions: raise forms.ValidationError("You should choose at least one region") if "advertising_types" not in self.data: raise forms.ValidationError("You should create at least one advertising type") advertising_types = self.data.getlist("advertising_types") advertising_payment_types = { int(key.split(".")[1]): value for key, value in self.data.iteritems() if key.startswith("advertising_payment_type") } advertising_images = { int(key.split(".")[1]): value for key, value in self.files.iteritems() if key.startswith("advertising_image") } advertising_types = AdvertisingType.objects.filter(active=True, id__in=map(lambda s: int(s), advertising_types)) cleaned_data["advertising_payment_types"] = advertising_payment_types cleaned_data["advertising_images"] = advertising_images for advertising_type in advertising_types: if advertising_type.id in advertising_images: dimensions = get_image_dimensions(advertising_images[advertising_type.id]) if dimensions is None: raise forms.ValidationError("You can upload only image") width, height = dimensions if advertising_type.width != width or advertising_type.height != height: raise forms.ValidationError("Advertising %s should have %dx%d dimension, you upload image with %dx%d" % ( advertising_type.name, advertising_type.width, advertising_type.height, width, height ) ) elif int(advertising_type.id) not in self.instance.advertising_set.values_list("ad_type_id", flat=True): raise forms.ValidationError("You should upload image for all advertising types") return cleaned_data
height = 165 weight = 168 body_ratio = weight/height print(body_ratio)
import json if __name__ == "__main__": with open('testforms/old_infra.json', encoding='utf-8') as f: forms = json.load(f) for idx, form in enumerate(forms): with open('old_infras/' + str(idx) + '.json', 'w+', encoding='utf-8') as f: f.write(json.dumps(form, ensure_ascii=False, indent=4).encode('utf-8').decode())
class Triangulo: def __init__(self, a, b, c): self.lado_a = a self.lado_b = b self.lado_c = c def calcular_perimetro(self): return self.lado_a + self.lado_b + self.lado_c def maior_lado(self): if self.lado_a > self.lado_b and self.lado_a > self.lado_c: return self.lado_a elif self.lado_b > self.lado_a and self.lado_b > self.lado_c: return self.lado_b else: return self.lado_c a = float(input('Digite o lado A do triângulo: ')) b = float(input('Digite o lado B do triângulo: ')) c = float(input('Digite o lado C do triângulo: ')) meu_objeto = Triangulo(a, b, c) print('Perímetro: ', meu_objeto.calcular_perimetro()) print('Maior lado: ', meu_objeto.maior_lado())
from abc import ABCMeta class Sized(metaclass=ABCMeta): @classmethod def __subclasshook__(cls, C): if cls is Sized: if any("__len__" in B.__dict__ for B in C.__mro__): return True # else: # return False return NotImplemented class A(Sized): pass class B(Sized): def __len__(self): return 0 print(issubclass(A, Sized)) # True - should be False print(issubclass(B, Sized)) # True print(A.__mro__)
from rest_framework import routers from kratos.apps.log.views import LogViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('log', LogViewSet, basename='log') urlpatterns = router.urls
import numpy as np import cv2 def find_keypoints(img_list): sift = cv2.xfeatures2d.SIFT_create() keypoints = [] descriptors = [] img_keypoints = [] for img in img_list: cur_keypoints, cur_descriptors = sift.detectAndCompute(img, None) keypoints.append(cur_keypoints) descriptors.append(cur_descriptors) img_keypoints.append(cv2.drawKeypoints(img, cur_keypoints, None)) return keypoints, descriptors, img_keypoints def normalize_descriptor(descriptor): return (descriptor - np.min(descriptor)) / (np.max(descriptor) - np.min(descriptor)) def create_distance_matrix(descriptor1, descriptor2): distance_matrix = np.zeros([descriptor1.shape[0], descriptor2.shape[0]]) for i in range(descriptor1.shape[0]): dist = np.linalg.norm(descriptor2 - descriptor1[i], axis=1) distance_matrix[i,:] = dist return distance_matrix def get_eligible_matches(distance_matrix, descriptors, nndr_threshold): min_key_points_val = np.min((descriptors[0].shape[0], descriptors[1].shape[0])) min_key_points_ind = 1 min_idx = distance_matrix.argmin(axis=min_key_points_ind) min_vals = distance_matrix.min(axis=min_key_points_ind) if min_key_points_ind == 1: distance_matrix[np.arange(len(distance_matrix)), min_idx] = np.inf elif min_key_points_ind == 0: distance_matrix[min_idx, np.arange(descriptors[1].shape[0])] = np.inf min_idx2 = distance_matrix.argmin(axis=min_key_points_ind) min_vals2 = distance_matrix.min(axis=min_key_points_ind) min_distance = np.concatenate([np.expand_dims(min_vals, axis=0), np.expand_dims(min_vals2, axis=0)], axis=0) min_indices = np.concatenate([np.expand_dims(min_idx, axis=0), np.expand_dims(min_idx2, axis=0)], axis=0) all_matches = [[] for _ in range(len(min_idx))] for i in range(len(min_vals)): for j in range(2): all_matches[i].append(cv2.DMatch(i, min_indices[j, i], min_distance[j, i])) eligible_matches = [] for i in range(len(min_vals)): if all_matches[i][0].distance < nndr_threshold * all_matches[i][1].distance: eligible_matches.append(all_matches[i][0]) return eligible_matches def find_matches(descriptors, use_nndr=True, nndr_threshold=0.35, number_of_matches=100): if use_nndr: distance_matrix = create_distance_matrix(descriptors[0], descriptors[1]) eligible_matches = get_eligible_matches(distance_matrix, descriptors, nndr_threshold) matched_points = [(eligible_matches[i].queryIdx, eligible_matches[i].trainIdx) for i in range(len(eligible_matches))] matches1to2 = [cv2.DMatch(i, i, 0) for i in range(len(eligible_matches))] return matched_points, matches1to2, eligible_matches else: pairwise_distances = create_distance_matrix(normalize_descriptor(descriptors[0]), normalize_descriptor(descriptors[1])) matched_points = [] for _ in range(number_of_matches): min_index = np.argmin(pairwise_distances) first_point = min_index // pairwise_distances.shape[1] second_point = min_index % pairwise_distances.shape[1] matched_points.append((first_point, second_point)) pairwise_distances[min_index // pairwise_distances.shape[1],:] = np.inf pairwise_distances[:,min_index % pairwise_distances.shape[1]] = np.inf matches1to2 = [cv2.DMatch(i, i, 0) for i in range(number_of_matches)] return matched_points, matches1to2
# question https://www.hackerrank.com/challenges/py-hello-world/problem # solution if __name__ == '__main__': print("Hello, World!")
import random from abc import ABC, abstractmethod from Event import Event, EventPayload class AbstractObject(ABC): def __init__(self, fixture=None, position=None): self._fixture = fixture self._position = position @property def fixture(self): return self._fixture @fixture.setter def fixture(self, value): self._fixture = value @property def position(self): return self._position @position.setter def position(self, value): self._position = value def draw(self, display): display.draw_object(self.fixture, self.position) class Interactive(ABC): @abstractmethod def interact(self, engine, hero): pass class Ally(AbstractObject, Interactive): class InteractedWithHeroEventPayload(EventPayload): def __init__(self, hero): self.__hero = hero @property def hero(self): return self.__hero def __init__(self, fixture, action, position): super().__init__(fixture, position) self._action = action def interact(self, engine, hero): engine.notify(Event(self._action, Ally.InteractedWithHeroEventPayload(hero))) class Creature(AbstractObject): def __init__(self, fixture, stats, position): super().__init__(fixture, position) self._stats = stats self._max_hp = self.calc_max_HP() self._hp = self._max_hp @property def hp(self): return self._hp @hp.setter def hp(self, value): self._hp = value @property def stats(self): return self._stats @stats.setter def stats(self, value): self._stats = value @property def strength(self): return self._stats.strength @strength.setter def strength(self, value): self._stats.strength = value @property def endurance(self): return self._stats.endurance @endurance.setter def endurance(self, value): self._stats.endurance = value @property def intelligence(self): return self._stats.intelligence @intelligence.setter def intelligence(self, value): self._stats.intelligence = value @property def luck(self): return self._stats.luck @luck.setter def luck(self, value): self._stats.luck = value @property def max_hp(self): return self._max_hp @max_hp.setter def max_hp(self, value): self._max_hp = value # noinspection PyPep8Naming def calc_max_HP(self): return 5 + self.stats.endurance * 2 class Hero(Creature): _default_position = [1, 1] def __init__(self, stats, fixture): self._level = 1 self._exp = 0 self._prev_level_exp = 0 self._next_level_exp = self.calc_next_level_exp() self._gold = 0 super().__init__(fixture, stats, self._default_position.copy()) @property def level(self): return self._level @level.setter def level(self, value): self._level = value @property def exp(self): return self._exp @exp.setter def exp(self, value): self._exp = value @property def next_level_exp(self): return self._next_level_exp @next_level_exp.setter def next_level_exp(self, value): self._next_level_exp = value @property def prev_level_exp(self): return self._prev_level_exp @prev_level_exp.setter def prev_level_exp(self, value): self._prev_level_exp = value @property def gold(self): return self._gold @gold.setter def gold(self, value): self._gold = value def level_up(self): old_level = self.level while self.exp >= self.next_level_exp: self.level += 1 self.strength += 2 self.endurance += 2 self.max_hp = self.calc_max_HP() self.restore_hp() self.prev_level_exp = self.next_level_exp self.next_level_exp = self.calc_next_level_exp() return old_level, self.level def restore_hp(self): self.hp = self.max_hp def reset_position(self): self.position = self._default_position.copy() def calc_next_level_exp(self): return 100 * (2 ** (self.level - 1)) def update_health_points(self): self.max_hp = self.calc_max_HP() self.hp = min(self.hp, self.max_hp) class Effect(Hero): # noinspection PyMissingConstructor def __init__(self, base): self._base = base self._stats = base.stats.copy() self.apply_effect() @property def base(self): return self._base @base.setter def base(self, value): self._base = value @property def stats(self): return self._stats @stats.setter def stats(self, value): self._stats = value @property def hp(self): return self._base.hp @hp.setter def hp(self, value): self._base.hp = value @property def max_hp(self): return self._base.max_hp @max_hp.setter def max_hp(self, value): self._base.max_hp = value @property def position(self): return self._base.position @position.setter def position(self, value): self._base.position = value @property def level(self): return self._base.level @level.setter def level(self, value): self._base.level = value @property def gold(self): return self._base.gold @gold.setter def gold(self, value): self._base.gold = value @property def exp(self): return self._base.exp @exp.setter def exp(self, value): self._base.exp = value @property def fixture(self): return self._base.fixture @property def next_level_exp(self): return self._base.next_level_exp @next_level_exp.setter def next_level_exp(self, value): self._base.next_level_exp = value @property def prev_level_exp(self): return self._base.prev_level_exp @prev_level_exp.setter def prev_level_exp(self, value): self._base.prev_level_exp = value @property def strength(self): return self._stats.strength @strength.setter def strength(self, value): difference = self._stats.strength - value self._stats.strength = value self._base.strength -= difference @property def endurance(self): return self._stats.endurance @endurance.setter def endurance(self, value): difference = self._stats.endurance - value self._stats.endurance = value self._base.endurance -= difference @property def intelligence(self): return self._stats.intelligence @intelligence.setter def intelligence(self, value): difference = self._stats.intelligence - value self._stats.intelligence = value self._base.intelligence -= difference @property def luck(self): return self._stats.luck @luck.setter def luck(self, value): difference = self._stats.luck - value self._stats.luck = value self._base.luck -= difference @abstractmethod def apply_effect(self): raise NotImplementedError class Enemy(Creature, Interactive): class InteractedWithHeroEventPayload(EventPayload): def __init__(self, damage, hero, enemy): self.__damage = damage self.__hero = hero self.__enemy = enemy @property def damage(self): return self.__damage @property def hero(self): return self.__hero @property def enemy(self): return self.__enemy def __init__(self, fixture, stats, xp, position): self.xp = xp super().__init__(fixture, stats, position) def interact(self, engine, hero): # min damage is 50% of the strength of enemy min_damage = int(0.5 * self.stats.strength) # max damage is 100% of the strength of enemy max_damage = self.stats.strength damage = random.randint(min_damage, max_damage) engine.notify(Event("enemy_interacted_with_hero", Enemy.InteractedWithHeroEventPayload(damage, hero, self))) class Berserk(Effect): def apply_effect(self): self._stats.strength += 7 self._stats.endurance += 7 self._stats.luck += 7 self._stats.intelligence -= 3 self.update_health_points() class Blessing(Effect): def apply_effect(self): self._stats.strength += 2 self._stats.endurance += 3 self._stats.luck += 4 self._stats.intelligence += 5 self.update_health_points() class Weakness(Effect): def apply_effect(self): self._stats.strength -= 4 self._stats.endurance -= 6 self._stats.intelligence -= 2 self.update_health_points() class Anger(Effect): def apply_effect(self): self._stats.strength += 10 self._stats.endurance += 15 self._stats.luck -= 5 self._stats.intelligence -= 5 self.update_health_points()
#-*- coding:utf8 -*- import time import datetime import json import urllib2 import cgi from lxml import etree from StringIO import StringIO from celery.task import task from celery.task.sets import subtask from celery import Task from django.db.models import Q from .models import WeixinUserAward from .service import WeixinSaleService class NotifyReferalAwardTask(Task): max_retries = 1 def run(self,user_openid): wx_service = WeixinSaleService(user_openid) wx_service.notifyReferalAward() class NotifyParentAwardTask(Task): max_retries = 1 def run(self): end_remind_time = datetime.datetime.now() - datetime.timedelta(seconds=10*60) remind_filter = Q(remind_count__gte=3)|Q(remind_time__lte=end_remind_time) wx_awards = WeixinUserAward.objects.filter(remind_filter, is_notify=False, is_share=False) for award in wx_awards: try: wx_service = WeixinSaleService(award.user_openid) wx_service.notifyAward() award.is_notify = True award.save() except Exception,exc: pass
import os import sys from functools import partial import click from flask import current_app from flask.cli import ( AppGroup, routes_command, ScriptInfo, with_appcontext, pass_script_info) from flask_migrate.cli import db as db_command import opsy from opsy.flask_extensions import db from opsy.app import create_app from opsy.config import load_config from opsy.exceptions import NoConfigFile from opsy.server import create_server from opsy.auth.schema import AppPermissionSchema, UserSchema, RoleSchema from opsy.utils import ( print_error, print_notice, get_protected_routes, get_valid_permissions) from opsy.auth.models import Role, User, Permission from opsy.inventory.models import Zone, Host, Group, HostGroupMapping click_option = partial( # pylint: disable=invalid-name click.option, show_default=True, show_envvar=True) @click.group(cls=AppGroup, help='The Opsy management cli.') @click_option('--config', type=click.Path(), default=f'{os.path.abspath(os.path.curdir)}/opsy.toml', envvar='OPSY_CONFIG', help='Config file for opsy.') @click_option('--app_database_uri', type=click.STRING, envvar='OPSY_APP_DATABASE_URI', help='The SQLAlchemy compatible database URI') @click_option('--app_secret_key', type=click.STRING, envvar='OPSY_APP_SECRET_KEY', help='The key used for crypto features.') @click_option('--app_uri_prefix', type=click.STRING, envvar='OPSY_APP_URI_PREFIX', help='URL prefix if mounted behind a reverse proxy.') @click_option('--server_host', type=click.STRING, envvar='OPSY_SERVER_HOST', help='Host address.') @click_option('--server_port', type=click.INT, envvar='OPSY_SERVER_PORT', help='Port number to listen on.') @click_option('--server_threads', type=click.INT, envvar='OPSY_SERVER_THREADS', help='Amount of threads.') @click_option('--server_ssl_enabled', type=click.BOOL, is_flag=True, envvar='OPSY_SERVER_SSL_ENABLED', help='Set to enable SSL.') @click_option('--server_certificate', type=click.Path(), envvar='OPSY_SERVER_CERTIFICATE', help='SSL cert.') @click_option('--server_private_key', type=click.Path(), envvar='OPSY_SERVER_PRIVATE_KEY', help='SSL key.') @click_option('--server_ca_certificate', type=click.Path(), envvar='OPSY_SERVER_CA_CERTIFICATE', help='SSL CA cert.') @click.pass_context def cli(ctx, config, **kwargs): overrides = { 'app': {}, 'auth': {}, 'logging': {}, 'server': {} } for key, value in kwargs.items(): top_key, sub_key = key.split('_', 1) if value is not None: overrides[top_key][sub_key] = value try: ctx.obj.data['config'] = load_config(config, overrides) except NoConfigFile as error: print_error(error, exit_script=False) ctx.obj.data['config'] = None cli.add_command(routes_command) cli.add_command(db_command) @cli.command('run') @pass_script_info def run(script_info): """Run the Opsy server.""" app = script_info.load_app() server = create_server(app) try: host = app.config.opsy['server']['host'] port = app.config.opsy['server']['port'] proto = 'https' if server.ssl_adapter else 'http' app.logger.info(f'Starting Opsy server at {proto}://{host}:{port}/...') app.logger.info(f'API docs available at {proto}://{host}:{port}/docs/') server.start() except KeyboardInterrupt: app.logger.info('Stopping Opsy server...') finally: server.stop() @cli.command('shell') def shell(): """Run a shell in the app context.""" from flask.globals import _app_ctx_stack banner = 'Welcome to Opsy!' app = _app_ctx_stack.top.app shell_ctx = {'create_app': create_app, 'db': db, 'User': User, 'Role': Role, 'Permission': Permission, 'Zone': Zone, 'Host': Host, 'Group': Group, 'HostGroupMapping': HostGroupMapping} shell_ctx.update(app.make_shell_context()) try: from IPython import embed embed(user_ns=shell_ctx, banner1=banner) return except ImportError: import code code.interact(banner, local=shell_ctx) @db_command.command('init-db') @click.confirmation_option( prompt='This will delete everything. Do you want to continue?') @with_appcontext def init_db(): """Drop everything in database and rebuild the schema.""" current_app.logger.info('Creating database...') db.drop_all() db.create_all() db.session.commit() @cli.command('permission-list') @click_option('--resource', type=click.STRING) @click_option('--method', type=click.STRING) def permission_list(**kwargs): """List all permissions the app is aware of.""" print(AppPermissionSchema(many=True).dumps( get_protected_routes(ignored_methods=["HEAD", "OPTIONS"]), indent=4)) @cli.command('create-admin-user') @click_option('--password', '-p', hide_input=True, confirmation_prompt=True, envvar='OPSY_ADMIN_PASSWORD', prompt='Password for the new admin user', help='Password for the new admin user.') @click_option('--force', '-f', type=click.BOOL, is_flag=True, help='Recreate admin user and role if they already exist.') def create_admin_user(password, force): """Create the default admin user.""" admin_user = User.query.filter_by(name='admin').first() admin_role = Role.query.filter_by(name='admin').first() if admin_user and not force: print_notice('Admin user already found, exiting. ' 'Use "--force" to force recreation.') sys.exit(0) if admin_role and not force: print_notice('Admin role already found, exiting. ' 'Use "--force" to force recreation.') sys.exit(0) if admin_user: print_notice('Admin user already found, deleting.') admin_user.delete() if admin_role: print_notice('Admin role already found, deleting.') admin_role.delete() admin_user = User.create( 'admin', password=password, full_name='Default admin user') admin_role = Role.create('admin', description='Default admin role') for permission in get_valid_permissions(): admin_role.add_permission(permission) admin_role.add_user(admin_user) admin_role.save() admin_user = User.query.filter_by(name='admin').first() admin_role = Role.query.filter_by(name='admin').first() print_notice('Admin user created with the specified password:') print(UserSchema().dumps(admin_user, indent=4)) print_notice('Admin role created:') print(RoleSchema().dumps(admin_role, indent=4)) @cli.command('version', with_appcontext=False) def version(): """Just show the version and quit.""" print(opsy.__version__) def main(): def create_opsy_app(script_info): if not script_info.data['config']: print_error('Config file not loaded, unable to start app.') return create_app(script_info.data['config']) cli( # pylint: disable=unexpected-keyword-arg,no-value-for-parameter obj=ScriptInfo(create_app=create_opsy_app))
print('n>> TRIANGULO') primeiroLado = float(input('Comprimento do lado 01: ')) segundoLado = float(input('Comprimento do lado 02: ')) terceiroLado = float(input('Comprimento do lado 03: ')) if primeiroLado + segundoLado > terceiroLado and segundoLado + terceiroLado > primeiroLado and terceiroLado + primeiroLado > segundoLado: print('Podemos formar um triangulo.') else: print('Nao podemos formar um triangulo.')
from graph_utils import * class Graph: def __init__(self): self.nodes: dict[int:Node] = {} self.edges: List[Edge] = [] def add_node(self, node: Node) -> None: self.nodes.update({node.id: node}) def connect(self, node1: int, node2: int) -> None: if node1 not in self.nodes.keys() or node2 not in self.nodes.keys(): raise Exception("nodes not in graph") e = Edge(self.nodes[node1], self.nodes[node2]) self.edges.append(e) self.nodes[node1].connectedEdges.append(e) self.nodes[node2].connectedEdges.append(e) def num_of_nodes(self) -> int: return len(self.nodes) def num_of_edges(self) -> int: return len(self.edges)
# -*- coding: utf-8 -*- """ Created on Thu Jul 12 15:15:10 2018 @author: ragoh """ import unittest from Computer import * class test_isWin(unittest.TestCase): #test empty board def test_emptyBoard(self): self.assertFalse(Player.isWin(Player([0, 0, 0, 0, 0, 0, 0, 0, 0]))[0]) #test board of one element def test_lose1(self): self.assertFalse(Player.isWin(Player([1, 0, 0, 0, 0, 0, 0, 0, 0]))[0]) #test board with two in a row def test_lose2(self): self.assertFalse(Player.isWin(Player([1, 0, 0, 1, 0, 0, 0, 0, 0]))[0]) #test three in a row horizontally def test_winH(self): self.assertTrue(Player.isWin(Player([0, 0, 0, 0, 0, 0, 1, 1, 1]))[0]) #test three in a row vertically def test_winV(self): self.assertTrue(Player.isWin(Player([0, 0, 1, 0, 0, 1, 0, 0, 1]))[0]) #test three in a row diagonally def test_winD(self): self.assertTrue(Player.isWin(Player([1, 0, 0, 0, 1, 0, 0, 0, 1]))[0]) #test with human win def test_winHum(self): self.assertTrue(Player.isWin(Player([0, 0, 0, -1, -1, -1, 0, 0, 0]))[0]) #tests playMove class test_playMove(unittest.TestCase): def test_win(self): p = Player([0, 0, 1, 0, 1, 0, 0, 0, 0]) p.playMove(1, 'C') #move shouldn't be played p.playMove(6, 'X') self.assertTrue(p.isWin()[0]) #test compMove methods class test_tryWin(unittest.TestCase): #test tryWin() def test_tryWin_vert(self): comp = Computer([1, -1, 0, 1, 0, 0, 0, -1, 0])#try vertical win comp.compMove() self.assertTrue(comp.isWin()[0]) def test_tryWin_hor(self): comp = Computer([-1, -1, 0, 0, 0, 0, 1, 0, 1])#try horizontal win comp.compMove() self.assertTrue(comp.isWin()[0]) def test_tryWin_dia(self): comp = Computer([1, 0, 0, -1, 0, 0, -1, 0, 1])#try diagonal win comp.compMove() self.assertTrue(comp.isWin()[0]) class test_tryWin_Block(unittest.TestCase): #test tryWin_Block def test_tryWin_Block_vert(self): #block human's vertical win comp = Computer([-1, 0, 0, 0, 1, 0, -1, 0, 1])#try vertical win comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 0, 0, 1, 1, 0, -1, 0, 1]) def test_tryWin_Block_hor(self): #block human's horizontal win comp = Computer([-1, 0, -1, 0, 1, 0, 0, 0, 1])#try horizontal win comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 1, -1, 0, 1, 0, 0, 0, 1]) def test_tryWin__Block_dia(self): #block human's diagonal win comp = Computer([-1, 0, 0, 1, 0, 0, 1, 0, -1])#try diagonal win comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 0, 0, 1, 1, 0, 1, 0, -1]) #CANT THINK OF ANY MORE TEST CASES class test_tryFork(unittest.TestCase): #test tryFork() def test_tryFork_1(self): comp = Computer([0, 0, -1, -1, 1, 0, 1, 0, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [0, 0, -1, -1, 1, 0, 1, 1, 0]) def test_tryFork_3(self): comp = Computer([0, -1, 1, 0, -1, 0, 0, 1, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [0, -1, 1, 0, -1, 0, 0, 1, 1]) #I DONT THINK WELL EVER REACH THIS CASE BECAUSE COMP WONT ALLOW IT class test_tryFork_Block(unittest.TestCase): def test_tryFork_noFork2Block(self): #if there is no fork, force opponent to block a 2 in a row comp = Computer([-1, 0, 0, 0, 1, 0, 0, 0, -1]) comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 1, 0, 0, 1, 0, 0, 0, -1]) def test_tryFork_isFork2Block(self): comp = Computer([0, 0, 1, 0, -1, 0, -1, 1, 0]) #two forks here, at 0 and 3 comp.compMove() self.assertEqual(comp.getMatrix(), [1, 0, 1, 0, -1, 0, -1, 1, 0]) comp = Computer([-1, 1, 0, 0, -1, 0, 0, 0, 1]) #two forks here, at 0 and 3 comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 1, 0, 0, -1, 0, 1, 0, 1]) comp = Computer([0, 1, -1, 0, 1, 0, 0, -1, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [0, 1, -1, 0, 1, 0, 0, -1, 1]) comp = Computer([0, 0, 1, 1, -1, 0, -1, 0, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [0, 0, 1, 1, -1, 0, -1, 0, 1]) comp = Computer([-1, 0, 0, 1, -1, 0, 0, 0, 1]) comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 0, 1, 1, -1, 0, 0, 0, 1]) class test_tryCenter(unittest.TestCase): def test_empty(self): comp = Computer([0, 0, 0, 0, 0, 0, 0, 0, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [0, 0, 0, 0, 1, 0, 0, 0, 0]) def test_1stCompMove_1(self): comp = Computer([-1, 0, 0, 0, 0, 0, 0, 0, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 0, 0, 0, 1, 0, 0, 0, 0]) def test_1stCompMove_2(self): comp = Computer([0, 0, 0, 0, 0, 0, 0, -1, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [0, 0, 0, 0, 1, 0, 0, -1, 0]) def test_lastMove(self): comp = Computer([1, 1, -1, -1, 0, 1, 1, -1, -1]) comp.compMove() self.assertEqual(comp.getMatrix(), [1, 1, -1, -1, 1, 1, 1, -1, -1]) class test_tryCorner_Opp(unittest.TestCase): def test_1(self): comp = Computer([-1, 0, 0, 0, 1, 0, 0, 0, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [-1, 0, 0, 0, 1, 0, 0, 0, 1]) def test_2(self): comp = Computer([0, 0, 0, 0, 1, 0, 0, 0, -1]) comp.compMove() self.assertEqual(comp.getMatrix(), [1, 0, 0, 0, 1, 0, 0, 0, -1]) class test_tryCorner(unittest.TestCase): def test_1(self): comp = Computer([0, 0, 0, 0, -1, 0, 0, 0, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [1, 0, 0, 0, -1, 0, 0, 0, 0]) def test_2(self): comp = Computer([0, -1, 0, 0, 1, 0, 0, -1, 0]) comp.compMove() self.assertEqual(comp.getMatrix(), [1, -1, 0, 0, 1, 0, 0, -1, 0]) class test_trySide(unittest.TestCase): def test_1(self): comp = Computer([1, -1, 1, 1, -1, 0, -1, 1, -1]) comp.compMove() self.assertEqual(comp.getMatrix(), [1, -1, 1, 1, -1, 1, -1, 1, -1]) def test_2(self): comp = Computer([1, 0, -1, -1, -1, 1, 1, 1, -1]) comp.compMove() self.assertEqual(comp.getMatrix(), [1, 1, -1, -1, -1, 1, 1, 1, -1]) class test_is2inRow(unittest.TestCase): def test1(self): comp = Computer([1, 0, 0, 0, 0, 0, 0, 0, 0]) self.assertEqual(2, comp.is2inRow(comp.getMatrix(), 1)) def test2(self): comp = Computer([1, 0, 0, 0, 0, 0, 0, 0, 0]) self.assertEqual(8, comp.is2inRow(comp.getMatrix(), 4)) def test3(self): comp = Computer([1, 0, 0, 0, 0, 0, 0, 0, 0]) self.assertEqual(-1, comp.is2inRow(comp.getMatrix(), 5)) def test4(self): comp = Computer([1, 0, -1, 0, 0, 0, -1, 0, 0]) self.assertEqual(8, comp.is2inRow(comp.getMatrix(), 4)) def test5(self): #the two in a row dont have to be necessarily adjacent comp = Computer([1, 0, 0, 0, 0, 0, 0, 0, 0]) self.assertEqual(1, comp.is2inRow(comp.getMatrix(), 2)) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # coding=utf-8 ''' Author: John Email: johnjim0816@gmail.com Date: 2020-10-07 20:57:11 LastEditor: John LastEditTime: 2021-04-28 10:13:21 Discription: Environment: ''' import matplotlib.pyplot as plt import seaborn as sns def plot_rewards(rewards,ma_rewards,tag="train",env='CartPole-v0',algo = "DQN",save=True,path='./'): sns.set() plt.title("average learning curve of {} for {}".format(algo,env)) plt.xlabel('epsiodes') plt.plot(rewards,label='rewards') plt.plot(ma_rewards,label='ma rewards') plt.legend() if save: plt.savefig(path+"rewards_curve_{}".format(tag)) plt.show() # def plot_rewards(dic,tag="train",env='CartPole-v0',algo = "DQN",save=True,path='./'): # sns.set() # plt.title("average learning curve of {} for {}".format(algo,env)) # plt.xlabel('epsiodes') # for key, value in dic.items(): # plt.plot(value,label=key) # plt.legend() # if save: # plt.savefig(path+algo+"_rewards_curve_{}".format(tag)) # plt.show() def plot_losses(losses,algo = "DQN",save=True,path='./'): sns.set() plt.title("loss curve of {}".format(algo)) plt.xlabel('epsiodes') plt.plot(losses,label='rewards') plt.legend() if save: plt.savefig(path+"losses_curve") plt.show()
from practicas.tiempo import Tiempo t1 = Tiempo(10, 20, 30) # Establecemos los valores de Tiempo # Sumamos y restamos Horas print(f"T1: {t1}") h = int(input(f"Horas a sumar a {t1}")) t1.suma_horas(h) print(f"Ahora T1 es {t1}") h = int(input(f"Horas a restar a {t1}")) t1.resta_horas(h) print(f"Ahora T1 es {t1}") # Sumamos y restamos minutos m = int(input(f"Minutos a sumar a {t1}")) t1.suma_minutos(m) print(f"Ahora T1 es {t1}") m = int(input(f"Minutos a restar a {t1}")) t1.resta_minutos(m) print(f"Ahora T1 es {t1}") # Sumamos y restamos segundos s = int(input(f"Segundos a sumar a {t1}")) t1.suma_segundos(s) print(f"Ahora T1 es {t1}") s = int(input(f"Segundos a restar a {t1}")) t1.resta_segundos(s) print(f"Ahora T1 es {t1}") # Sumamos y restamos otro objeto de la clase Tiempo print("Para sumar T2 a T1 introduce los valores de T2") h = int(input("Horas de T2: ")) m = int(input("Minutos de T2: ")) s = int(input("Segundos de T2: ")) t2 = Tiempo(h, m, s) t1.suma(t2) print(f"Ahora T1 es {t1}") print("Para restar T2 a T1 introduce los valores de T2") h = int(input("Horas de T2: ")) m = int(input("Minutos de T2: ")) s = int(input("Segundos de T2: ")) t2 = Tiempo(h, m, s) t1.resta(t2) print(f"Ahora T1 es {t1}")
#!/usr/bin/env python from os.path import join, realpath import sys import pandas as pd from typing import List import unittest from hummingsim.backtest.backtest_market import BacktestMarket from hummingsim.backtest.market import ( AssetType, Market, MarketConfig, QuantizationParams ) from hummingsim.backtest.mock_order_book_loader import MockOrderBookLoader from hummingbot.core.clock import Clock, ClockMode from hummingbot.core.event.event_logger import EventLogger from hummingbot.core.event.events import ( MarketEvent, OrderBookTradeEvent, TradeType, OrderType, OrderFilledEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, TradeFee, BuyOrderCreatedEvent, SellOrderCreatedEvent, ) from math import floor, ceil from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_row import OrderBookRow from hummingbot.core.data_type.limit_order import LimitOrder from hummingbot.strategy.cross_exchange_market_making import CrossExchangeMarketMakingStrategy from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_pair import CrossExchangeMarketPair from nose.plugins.attrib import attr from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from decimal import Decimal import logging sys.path.insert(0, realpath(join(__file__, "../../"))) logging.basicConfig(level=logging.ERROR) @attr("stable") class HedgedMarketMakingUnitTest(unittest.TestCase): start: pd.Timestamp = pd.Timestamp("2019-01-01", tz="UTC") end: pd.Timestamp = pd.Timestamp("2019-01-01 01:00:00", tz="UTC") start_timestamp: float = start.timestamp() end_timestamp: float = end.timestamp() maker_trading_pairs: List[str] = ["COINALPHA-WETH", "COINALPHA", "WETH"] taker_trading_pairs: List[str] = ["coinalpha/eth", "COINALPHA", "ETH"] def setUp(self): self.clock: Clock = Clock(ClockMode.BACKTEST, 1.0, self.start_timestamp, self.end_timestamp) self.min_profitbality = Decimal("0.005") self.maker_market: BacktestMarket = BacktestMarket() self.taker_market: BacktestMarket = BacktestMarket() self.maker_data: MockOrderBookLoader = MockOrderBookLoader(*self.maker_trading_pairs) self.taker_data: MockOrderBookLoader = MockOrderBookLoader(*self.taker_trading_pairs) self.maker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.01, 10) self.taker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.001, 4) self.maker_market.add_data(self.maker_data) self.taker_market.add_data(self.taker_data) self.maker_market.set_balance("COINALPHA", 5) self.maker_market.set_balance("WETH", 5) self.maker_market.set_balance("QETH", 5) self.taker_market.set_balance("COINALPHA", 5) self.taker_market.set_balance("ETH", 5) self.maker_market.set_quantization_param(QuantizationParams(self.maker_trading_pairs[0], 5, 5, 5, 5)) self.taker_market.set_quantization_param(QuantizationParams(self.taker_trading_pairs[0], 5, 5, 5, 5)) self.market_pair: CrossExchangeMarketPair = CrossExchangeMarketPair( MarketTradingPairTuple(self.maker_market, *self.maker_trading_pairs), MarketTradingPairTuple(self.taker_market, *self.taker_trading_pairs), ) logging_options: int = ( CrossExchangeMarketMakingStrategy.OPTION_LOG_ALL & (~CrossExchangeMarketMakingStrategy.OPTION_LOG_NULL_ORDER_SIZE) ) self.strategy: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy( [self.market_pair], order_size_portfolio_ratio_limit=Decimal("0.3"), min_profitability=Decimal(self.min_profitbality), logging_options=logging_options, ) self.strategy_with_top_depth_tolerance: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy( [self.market_pair], order_size_portfolio_ratio_limit=Decimal("0.3"), min_profitability=Decimal(self.min_profitbality), logging_options=logging_options, top_depth_tolerance=1 ) self.logging_options = logging_options self.clock.add_iterator(self.maker_market) self.clock.add_iterator(self.taker_market) self.clock.add_iterator(self.strategy) self.maker_order_fill_logger: EventLogger = EventLogger() self.taker_order_fill_logger: EventLogger = EventLogger() self.cancel_order_logger: EventLogger = EventLogger() self.maker_order_created_logger: EventLogger = EventLogger() self.taker_order_created_logger: EventLogger = EventLogger() self.maker_market.add_listener(MarketEvent.OrderFilled, self.maker_order_fill_logger) self.taker_market.add_listener(MarketEvent.OrderFilled, self.taker_order_fill_logger) self.maker_market.add_listener(MarketEvent.OrderCancelled, self.cancel_order_logger) self.maker_market.add_listener(MarketEvent.BuyOrderCreated, self.maker_order_created_logger) self.maker_market.add_listener(MarketEvent.SellOrderCreated, self.maker_order_created_logger) self.taker_market.add_listener(MarketEvent.BuyOrderCreated, self.taker_order_created_logger) self.taker_market.add_listener(MarketEvent.SellOrderCreated, self.taker_order_created_logger) def simulate_maker_market_trade(self, is_buy: bool, quantity: Decimal, price: Decimal): maker_trading_pair: str = self.maker_trading_pairs[0] order_book: OrderBook = self.maker_market.get_order_book(maker_trading_pair) trade_event: OrderBookTradeEvent = OrderBookTradeEvent( maker_trading_pair, self.clock.current_timestamp, TradeType.BUY if is_buy else TradeType.SELL, price, quantity ) order_book.apply_trade(trade_event) @staticmethod def simulate_order_book_widening(order_book: OrderBook, top_bid: float, top_ask: float): bid_diffs: List[OrderBookRow] = [] ask_diffs: List[OrderBookRow] = [] update_id: int = order_book.last_diff_uid + 1 for row in order_book.bid_entries(): if row.price > top_bid: bid_diffs.append(OrderBookRow(row.price, 0, update_id)) else: break for row in order_book.ask_entries(): if row.price < top_ask: ask_diffs.append(OrderBookRow(row.price, 0, update_id)) else: break order_book.apply_diffs(bid_diffs, ask_diffs, update_id) @staticmethod def simulate_limit_order_fill(market: Market, limit_order: LimitOrder): quote_currency_traded: Decimal = limit_order.price * limit_order.quantity base_currency_traded: Decimal = limit_order.quantity quote_currency: str = limit_order.quote_currency base_currency: str = limit_order.base_currency config: MarketConfig = market.config if limit_order.is_buy: market.set_balance(quote_currency, market.get_balance(quote_currency) - quote_currency_traded) market.set_balance(base_currency, market.get_balance(base_currency) + base_currency_traded) market.trigger_event( MarketEvent.BuyOrderCreated, BuyOrderCreatedEvent( market.current_timestamp, OrderType.LIMIT, limit_order.trading_pair, limit_order.quantity, limit_order.price, limit_order.client_order_id ) ) market.trigger_event( MarketEvent.OrderFilled, OrderFilledEvent( market.current_timestamp, limit_order.client_order_id, limit_order.trading_pair, TradeType.BUY, OrderType.LIMIT, limit_order.price, limit_order.quantity, TradeFee(Decimal(0)), ), ) market.trigger_event( MarketEvent.BuyOrderCompleted, BuyOrderCompletedEvent( market.current_timestamp, limit_order.client_order_id, base_currency, quote_currency, base_currency if config.buy_fees_asset is AssetType.BASE_CURRENCY else quote_currency, base_currency_traded, quote_currency_traded, Decimal(0), OrderType.LIMIT, ), ) else: market.set_balance(quote_currency, market.get_balance(quote_currency) + quote_currency_traded) market.set_balance(base_currency, market.get_balance(base_currency) - base_currency_traded) market.trigger_event( MarketEvent.BuyOrderCreated, SellOrderCreatedEvent( market.current_timestamp, OrderType.LIMIT, limit_order.trading_pair, limit_order.quantity, limit_order.price, limit_order.client_order_id ) ) market.trigger_event( MarketEvent.OrderFilled, OrderFilledEvent( market.current_timestamp, limit_order.client_order_id, limit_order.trading_pair, TradeType.SELL, OrderType.LIMIT, limit_order.price, limit_order.quantity, TradeFee(Decimal(0)), ), ) market.trigger_event( MarketEvent.SellOrderCompleted, SellOrderCompletedEvent( market.current_timestamp, limit_order.client_order_id, base_currency, quote_currency, base_currency if config.sell_fees_asset is AssetType.BASE_CURRENCY else quote_currency, base_currency_traded, quote_currency_traded, Decimal(0), OrderType.LIMIT, ), ) def test_both_sides_profitable(self): self.clock.backtest_til(self.start_timestamp + 5) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.99452"), bid_order.price) self.assertEqual(Decimal("1.0056"), ask_order.price) self.assertEqual(Decimal("3.0"), bid_order.quantity) self.assertEqual(Decimal("3.0"), ask_order.quantity) self.simulate_maker_market_trade(False, Decimal("10.0"), bid_order.price * Decimal("0.99")) self.clock.backtest_til(self.start_timestamp + 10) self.assertEqual(1, len(self.maker_order_fill_logger.event_log)) self.assertEqual(1, len(self.taker_order_fill_logger.event_log)) maker_fill: OrderFilledEvent = self.maker_order_fill_logger.event_log[0] taker_fill: OrderFilledEvent = self.taker_order_fill_logger.event_log[0] self.assertEqual(TradeType.BUY, maker_fill.trade_type) self.assertEqual(TradeType.SELL, taker_fill.trade_type) self.assertAlmostEqual(Decimal("0.99452"), maker_fill.price) self.assertAlmostEqual(Decimal("0.9995"), taker_fill.price) self.assertAlmostEqual(Decimal("3.0"), maker_fill.amount) self.assertAlmostEqual(Decimal("3.0"), taker_fill.amount) def test_top_depth_tolerance(self): # TODO self.clock.remove_iterator(self.strategy) self.clock.add_iterator(self.strategy_with_top_depth_tolerance) self.clock.backtest_til(self.start_timestamp + 5) bid_order: LimitOrder = self.strategy_with_top_depth_tolerance.active_bids[0][1] ask_order: LimitOrder = self.strategy_with_top_depth_tolerance.active_asks[0][1] self.taker_market.trigger_event( MarketEvent.BuyOrderCreated, BuyOrderCreatedEvent( self.start_timestamp + 5, OrderType.LIMIT, bid_order.trading_pair, bid_order.quantity, bid_order.price, bid_order.client_order_id ) ) self.taker_market.trigger_event( MarketEvent.SellOrderCreated, SellOrderCreatedEvent( self.start_timestamp + 5, OrderType.LIMIT, ask_order.trading_pair, ask_order.quantity, ask_order.price, ask_order.client_order_id ) ) self.assertEqual(Decimal("0.99452"), bid_order.price) self.assertEqual(Decimal("1.0056"), ask_order.price) self.assertEqual(Decimal("3.0"), bid_order.quantity) self.assertEqual(Decimal("3.0"), ask_order.quantity) self.simulate_order_book_widening(self.taker_data.order_book, 0.99, 1.01) self.clock.backtest_til(self.start_timestamp + 100) self.assertEqual(2, len(self.cancel_order_logger.event_log)) self.assertEqual(1, len(self.strategy_with_top_depth_tolerance.active_bids)) self.assertEqual(1, len(self.strategy_with_top_depth_tolerance.active_asks)) bid_order = self.strategy_with_top_depth_tolerance.active_bids[0][1] ask_order = self.strategy_with_top_depth_tolerance.active_asks[0][1] self.assertEqual(Decimal("0.98457"), bid_order.price) self.assertEqual(Decimal("1.0156"), ask_order.price) def test_market_became_wider(self): # TODO self.clock.backtest_til(self.start_timestamp + 5) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.99452"), bid_order.price) self.assertEqual(Decimal("1.0056"), ask_order.price) self.assertEqual(Decimal("3.0"), bid_order.quantity) self.assertEqual(Decimal("3.0"), ask_order.quantity) self.taker_market.trigger_event( MarketEvent.BuyOrderCreated, BuyOrderCreatedEvent( self.start_timestamp + 5, OrderType.LIMIT, bid_order.trading_pair, bid_order.quantity, bid_order.price, bid_order.client_order_id ) ) self.taker_market.trigger_event( MarketEvent.SellOrderCreated, SellOrderCreatedEvent( self.start_timestamp + 5, OrderType.LIMIT, ask_order.trading_pair, ask_order.quantity, ask_order.price, ask_order.client_order_id ) ) self.simulate_order_book_widening(self.taker_data.order_book, 0.99, 1.01) self.clock.backtest_til(self.start_timestamp + 100) self.assertEqual(2, len(self.cancel_order_logger.event_log)) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order = self.strategy.active_bids[0][1] ask_order = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.98457"), bid_order.price) self.assertEqual(Decimal("1.0156"), ask_order.price) def test_market_became_narrower(self): self.clock.backtest_til(self.start_timestamp + 5) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.99452"), bid_order.price) self.assertEqual(Decimal("1.0056"), ask_order.price) self.assertEqual(Decimal("3.0"), bid_order.quantity) self.assertEqual(Decimal("3.0"), ask_order.quantity) self.maker_data.order_book.apply_diffs([OrderBookRow(0.996, 30, 2)], [OrderBookRow(1.004, 30, 2)], 2) self.clock.backtest_til(self.start_timestamp + 10) self.assertEqual(0, len(self.cancel_order_logger.event_log)) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order = self.strategy.active_bids[0][1] ask_order = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.99452"), bid_order.price) self.assertEqual(Decimal("1.0056"), ask_order.price) def test_order_fills_after_cancellation(self): # TODO self.clock.backtest_til(self.start_timestamp + 5) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.99452"), bid_order.price) self.assertEqual(Decimal("1.0056"), ask_order.price) self.assertEqual(Decimal("3.0"), bid_order.quantity) self.assertEqual(Decimal("3.0"), ask_order.quantity) self.taker_market.trigger_event( MarketEvent.BuyOrderCreated, BuyOrderCreatedEvent( self.start_timestamp + 5, OrderType.LIMIT, bid_order.trading_pair, bid_order.quantity, bid_order.price, bid_order.client_order_id ) ) self.taker_market.trigger_event( MarketEvent.SellOrderCreated, SellOrderCreatedEvent( self.start_timestamp + 5, OrderType.LIMIT, ask_order.trading_pair, ask_order.quantity, ask_order.price, ask_order.client_order_id ) ) self.simulate_order_book_widening(self.taker_data.order_book, 0.99, 1.01) self.clock.backtest_til(self.start_timestamp + 10) self.assertEqual(2, len(self.cancel_order_logger.event_log)) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order = self.strategy.active_bids[0][1] ask_order = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.98457"), bid_order.price) self.assertEqual(Decimal("1.0156"), ask_order.price) self.clock.backtest_til(self.start_timestamp + 20) self.simulate_limit_order_fill(self.maker_market, bid_order) self.simulate_limit_order_fill(self.maker_market, ask_order) self.clock.backtest_til(self.start_timestamp + 25) fill_events: List[OrderFilledEvent] = self.taker_order_fill_logger.event_log bid_hedges: List[OrderFilledEvent] = [evt for evt in fill_events if evt.trade_type is TradeType.SELL] ask_hedges: List[OrderFilledEvent] = [evt for evt in fill_events if evt.trade_type is TradeType.BUY] self.assertEqual(1, len(bid_hedges)) self.assertEqual(1, len(ask_hedges)) self.assertGreater( self.maker_market.get_balance(self.maker_trading_pairs[2]) + self.taker_market.get_balance(self.taker_trading_pairs[2]), Decimal("10"), ) self.assertEqual(2, len(self.taker_order_fill_logger.event_log)) taker_fill1: OrderFilledEvent = self.taker_order_fill_logger.event_log[0] self.assertEqual(TradeType.SELL, taker_fill1.trade_type) self.assertAlmostEqual(Decimal("0.9895"), taker_fill1.price) self.assertAlmostEqual(Decimal("3.0"), taker_fill1.amount) taker_fill2: OrderFilledEvent = self.taker_order_fill_logger.event_log[1] self.assertEqual(TradeType.BUY, taker_fill2.trade_type) self.assertAlmostEqual(Decimal("1.0105"), taker_fill2.price) self.assertAlmostEqual(Decimal("3.0"), taker_fill2.amount) def test_with_conversion(self): self.clock.remove_iterator(self.strategy) self.market_pair: CrossExchangeMarketPair = CrossExchangeMarketPair( MarketTradingPairTuple(self.maker_market, *["COINALPHA-QETH", "COINALPHA", "QETH"]), MarketTradingPairTuple(self.taker_market, *self.taker_trading_pairs), ) self.maker_data: MockOrderBookLoader = MockOrderBookLoader("COINALPHA-QETH", "COINALPHA", "QETH") self.maker_data.set_balanced_order_book(1.05, 0.55, 1.55, 0.01, 10) self.maker_market.add_data(self.maker_data) self.strategy: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy( [self.market_pair], Decimal("0.01"), order_size_portfolio_ratio_limit=Decimal("0.3"), logging_options=self.logging_options, taker_to_maker_base_conversion_rate=Decimal("0.95") ) self.clock.add_iterator(self.strategy) self.clock.backtest_til(self.start_timestamp + 5) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] self.assertAlmostEqual(Decimal("1.0417"), round(bid_order.price, 4)) self.assertAlmostEqual(Decimal("1.0637"), round(ask_order.price, 4)) self.assertAlmostEqual(Decimal("2.9286"), round(bid_order.quantity, 4)) self.assertAlmostEqual(Decimal("2.9286"), round(ask_order.quantity, 4)) def test_maker_price(self): buy_taker_price: Decimal = self.strategy.get_effective_hedging_price(self.market_pair, False, 3) sell_taker_price: Decimal = self.strategy.get_effective_hedging_price(self.market_pair, True, 3) price_quantum = Decimal("0.0001") self.assertEqual(Decimal("1.0005"), buy_taker_price) self.assertEqual(Decimal("0.9995"), sell_taker_price) self.clock.backtest_til(self.start_timestamp + 5) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] bid_maker_price = sell_taker_price * (1 - self.min_profitbality) bid_maker_price = (floor(bid_maker_price / price_quantum)) * price_quantum ask_maker_price = buy_taker_price * (1 + self.min_profitbality) ask_maker_price = (ceil(ask_maker_price / price_quantum) * price_quantum) self.assertEqual(bid_maker_price, round(bid_order.price, 4)) self.assertEqual(ask_maker_price, round(ask_order.price, 4)) self.assertEqual(Decimal("3.0"), bid_order.quantity) self.assertEqual(Decimal("3.0"), ask_order.quantity) def test_with_adjust_orders_enabled(self): self.clock.remove_iterator(self.strategy) self.clock.remove_iterator(self.maker_market) self.maker_market: BacktestMarket = BacktestMarket() self.maker_data: MockOrderBookLoader = MockOrderBookLoader(*self.maker_trading_pairs) self.maker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.1, 10) self.maker_market.add_data(self.maker_data) self.market_pair: CrossExchangeMarketPair = CrossExchangeMarketPair( MarketTradingPairTuple(self.maker_market, *self.maker_trading_pairs), MarketTradingPairTuple(self.taker_market, *self.taker_trading_pairs), ) self.strategy: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy( [self.market_pair], order_size_portfolio_ratio_limit=Decimal("0.3"), min_profitability=Decimal("0.005"), logging_options=self.logging_options, ) self.maker_market.set_balance("COINALPHA", 5) self.maker_market.set_balance("WETH", 5) self.maker_market.set_balance("QETH", 5) self.maker_market.set_quantization_param(QuantizationParams(self.maker_trading_pairs[0], 4, 4, 4, 4)) self.clock.add_iterator(self.strategy) self.clock.add_iterator(self.maker_market) self.clock.backtest_til(self.start_timestamp + 5) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] # place above top bid (at 0.95) self.assertAlmostEqual(Decimal("0.9501"), bid_order.price) # place below top ask (at 1.05) self.assertAlmostEqual(Decimal("1.049"), ask_order.price) self.assertAlmostEqual(Decimal("3"), round(bid_order.quantity, 4)) self.assertAlmostEqual(Decimal("3"), round(ask_order.quantity, 4)) def test_with_adjust_orders_disabled(self): self.clock.remove_iterator(self.strategy) self.clock.remove_iterator(self.maker_market) self.maker_market: BacktestMarket = BacktestMarket() self.maker_data: MockOrderBookLoader = MockOrderBookLoader(*self.maker_trading_pairs) self.maker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.1, 10) self.taker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.001, 20) self.maker_market.add_data(self.maker_data) self.market_pair: CrossExchangeMarketPair = CrossExchangeMarketPair( MarketTradingPairTuple(self.maker_market, *self.maker_trading_pairs), MarketTradingPairTuple(self.taker_market, *self.taker_trading_pairs), ) self.strategy: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy( [self.market_pair], order_size_portfolio_ratio_limit=Decimal("0.3"), min_profitability=Decimal("0.005"), logging_options=self.logging_options, adjust_order_enabled=False ) self.maker_market.set_balance("COINALPHA", 5) self.maker_market.set_balance("WETH", 5) self.maker_market.set_balance("QETH", 5) self.maker_market.set_quantization_param(QuantizationParams(self.maker_trading_pairs[0], 4, 4, 4, 4)) self.clock.add_iterator(self.strategy) self.clock.add_iterator(self.maker_market) self.clock.backtest_til(self.start_timestamp + 5) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] self.assertEqual(Decimal("0.9945"), bid_order.price) self.assertEqual(Decimal("1.006"), ask_order.price) self.assertAlmostEqual(Decimal("3"), round(bid_order.quantity, 4)) self.assertAlmostEqual(Decimal("3"), round(ask_order.quantity, 4)) def test_price_and_size_limit_calculation(self): self.taker_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.001, 20) bid_size = self.strategy.get_market_making_size(self.market_pair, True) bid_price = self.strategy.get_market_making_price(self.market_pair, True, bid_size) ask_size = self.strategy.get_market_making_size(self.market_pair, False) ask_price = self.strategy.get_market_making_price(self.market_pair, False, ask_size) self.assertEqual((Decimal("0.99452"), Decimal("3")), (bid_price, bid_size)) self.assertEqual((Decimal("1.0056"), Decimal("3")), (ask_price, ask_size)) def test_empty_maker_orderbook(self): self.clock.remove_iterator(self.strategy) self.clock.remove_iterator(self.maker_market) self.maker_market: BacktestMarket = BacktestMarket() self.maker_data: MockOrderBookLoader = MockOrderBookLoader(*self.maker_trading_pairs) # Orderbook is empty self.maker_market.add_data(self.maker_data) self.market_pair: CrossExchangeMarketPair = CrossExchangeMarketPair( MarketTradingPairTuple(self.maker_market, *self.maker_trading_pairs), MarketTradingPairTuple(self.taker_market, *self.taker_trading_pairs), ) self.strategy: CrossExchangeMarketMakingStrategy = CrossExchangeMarketMakingStrategy( [self.market_pair], order_amount=1, min_profitability=Decimal("0.005"), logging_options=self.logging_options, adjust_order_enabled=False ) self.maker_market.set_balance("COINALPHA", 5) self.maker_market.set_balance("WETH", 5) self.maker_market.set_balance("QETH", 5) self.maker_market.set_quantization_param(QuantizationParams(self.maker_trading_pairs[0], 4, 4, 4, 4)) self.clock.add_iterator(self.strategy) self.clock.add_iterator(self.maker_market) self.clock.backtest_til(self.start_timestamp + 5) self.assertEqual(1, len(self.strategy.active_bids)) self.assertEqual(1, len(self.strategy.active_asks)) bid_order: LimitOrder = self.strategy.active_bids[0][1] ask_order: LimitOrder = self.strategy.active_asks[0][1] # Places orders based on taker orderbook self.assertEqual(Decimal("0.9945"), bid_order.price) self.assertEqual(Decimal("1.006"), ask_order.price) self.assertAlmostEqual(Decimal("1"), round(bid_order.quantity, 4)) self.assertAlmostEqual(Decimal("1"), round(ask_order.quantity, 4))
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2016/3/1 10:22 import bisect # the complexity of the this algorithm is O(n^2) def length_of_lis(nums): length_list = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j] and length_list[i] < length_list[j] + 1: length_list[i] = length_list[j] + 1 if length_list: return max(length_list) else: return 0 # https://leetcode.com/discuss/82155/share-my-8-line-o-nlgn-java-code-with-comments-in-mandarin # cap[i] store the minimum value of the last element of list which length is i + 1 def length_of_lis_2(nums): cap = [] for num in nums: if not cap or num > cap[len(cap) - 1]: cap.append(num) else: index = bisect.bisect_left(cap, num) cap[index] = num return len(cap) test_nums = [10, 9, 2, 5, 3, 7, 101, 18] test_nums = [2, 2] test_nums = [3, 5, 6, 2, 5, 4, 19, 5, 6, 7, 12] print(length_of_lis_2(test_nums))
#!/usr/bin/env python3 #learning pygame from programarcadegames.com #pong game ''' sounds from: http://opengameart.org/content/3-ping-pong-sounds-8-bit-style The first code a Pygame program needs to do is load and initialize the Pygame library. Every program that uses Pygame should start with these lines: ''' # Import a library of functions called 'pygame' import pygame import random # Initialize the game engine pygame.init() # Next, we need to add variables that define our program's colors. # Define some colors BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) GREEN = ( 0, 255, 0) RED = ( 255, 0, 0) BLUE = ( 0, 0, 255) GREY = ( 128, 128, 128) SENS = 10 # Keyboard repeat interval constant, the lower the number the faster the paddle class Pong(pygame.sprite.Sprite): ''' Class for the pong ball. Pong(color, size=10) ''' def __init__(self, color, size=10): # Call to parent class super().__init__() # Class attributions self.color = color self.size = size #load the image self.image = pygame.Surface([self.size, self.size]).convert() self.image.fill(self.color) #set transparent color self.image.set_colorkey(BLACK) #Fetch the image rect. self.rect = self.image.get_rect() def reset_pos(self): ''' Reset pong to center of screen, give random x, y speed ''' self.rect.x, self.rect.y = SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 self.x_speed = random.randrange(-2 , 3, 4) #random left or right needed here self.y_speed = random.randint(-5, 5) #random up or down def wall_bounce(self): hit_wall.play() self.y_speed *= -1 def score(self): point_score.play() self.reset_pos() class Paddle(pygame.sprite.Sprite): ''' Class for paddle Paddle(paddle_x, paddle_y, color=WHITE, paddle_width=10, paddle_height=80, paddle_speed=10) ''' def __init__(self, paddle_x, paddle_y , color = WHITE, paddle_width = 10, paddle_height = 80, paddle_speed = 10): # Call to parent class super().__init__() # Class attributions self.color = color self.width = paddle_width self.height = paddle_height self.speed = paddle_speed # score keeper self.score = 0 #load the image self.image = pygame.Surface([self.width, self.height]).convert() self.image.fill(self.color) #set transparent color self.image.set_colorkey(BLACK) #Fetch the image rect. self.rect = self.image.get_rect() self.rect.x = paddle_x self.rect.y = paddle_y def add_point(self, point): self.score += point # player input configuration player_left_up = pygame.K_a player_left_down = pygame.K_z player_right_up = pygame.K_k player_right_down = pygame.K_m SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT) title = "PyPong" netwidth = 10 hit_paddle = pygame.mixer.Sound('paddle.wav') hit_wall = pygame.mixer.Sound('wall.wav') point_score = pygame.mixer.Sound('miss.wav') score_down = 20 # how far down the score text is placed on the screen score_text_size = 60 # size of the scoreboard text max_score = 10 # play until someone gets the max_score # create the display screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption(title) # Create lists to hold the sprites all_sprites_list = pygame.sprite.Group() paddle_list = pygame.sprite.Group() def paddle_bounce(paddle, pong): if pong.x_speed > 0: pong.x_speed +=1 elif pong.x_speed < 0: pong.x_speed -=1 pong.x_speed *= -1 if pong.rect.y < ( paddle.height/5 + paddle.rect.y ): pong.y_speed = -5 elif pong.rect.y > (paddle.height/5 + paddle.rect.y) and pong.rect.y < (2 * (paddle.height/5) + paddle.rect.y ): pong.y_speed = -3 elif pong.rect.y > (2 * (paddle.height/5) + paddle.rect.y ) and pong.rect.y < (3 * (paddle.height/5) + paddle.rect.y): pong.y_speed = 0 elif pong.rect.y > (3 * (paddle.height/5) + paddle.rect.y) and pong.rect.y < (4 * (paddle.height/5) + paddle.rect.y): pong.y_speed = 3 else: pong.y_speed = 5 hit_paddle.play() # Select the font to use, size, bold, italics font = pygame.font.SysFont('Calibri', score_text_size, False, False) def draw_score(paddle): return font.render(str(paddle.score), True, WHITE) def draw_net(screen): pygame.draw.line(screen, GREY, [(SCREEN_WIDTH/2) - (netwidth/2), 0] , [(SCREEN_WIDTH/2) - (netwidth/2) , SCREEN_HEIGHT], netwidth) def reset_all(pong, paddle1, paddle2): pong.reset_pos() paddle1.score = 0 paddle2.score = 0 # Create the pong pong = Pong(WHITE, size=10) pong.reset_pos() def get_center_y(screen_height, paddle_height): ''' Returns the y axis where object, if drawn, will sit on the center of screen ''' return (screen_height / 2) - (paddle_height / 2) paddle_width = 10 paddle_height = 80 # Set initial position of paddle left_paddle_init_x = paddle_width # magic number ? left_paddle_init_y = get_center_y(SCREEN_HEIGHT, paddle_height) # Set initial position of paddle right_paddle_init_x = SCREEN_WIDTH - (2 * paddle_width) # magic number ? right_paddle_init_y = get_center_y(SCREEN_HEIGHT, paddle_height) # Create the left paddle left_paddle = Paddle(paddle_x=left_paddle_init_x, paddle_y=left_paddle_init_y) # Create the right paddle right_paddle = Paddle(paddle_x=right_paddle_init_x, paddle_y=right_paddle_init_y) # Group related sprite together paddle_list.add(right_paddle) paddle_list.add(left_paddle) all_sprites_list.add(pong) all_sprites_list.add(left_paddle) all_sprites_list.add(right_paddle) # set the scores for rendering for each paddle left_paddle_score = draw_score(left_paddle) right_paddle_score = draw_score(right_paddle) # Used to manage how fast the screen updates clock = pygame.time.Clock() # Set the repeat interval of held keys pygame.key.set_repeat(SENS, SENS) # Loop until the user clicks the close button. done = False # -------- Main Program Loop ----------- while not done: # --- Main event loop for paddle in paddle_list: if paddle.score == max_score: #what to do at max_score--could end game or just reset and keep playing reset_all(pong, left_paddle, right_paddle) left_paddle_score = draw_score(left_paddle) right_paddle_score = draw_score(right_paddle) ''' pong.reset_pos() left_paddle.score = 0 right_paddle.score = 0 left_paddle_score = draw_score(left_paddle) right_paddle_score = draw_score(right_paddle) ''' for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # This will handle multiple key presses, allowing both paddles to # move simultaneously elif event.type == pygame.KEYDOWN: key = pygame.key.get_pressed() if key[player_left_up]: left_paddle.rect.y -= left_paddle.speed if key[player_left_down]: left_paddle.rect.y += left_paddle.speed if key[player_right_up]: right_paddle.rect.y -= right_paddle.speed if key[player_right_down]: right_paddle.rect.y += right_paddle.speed # move stuff pong.rect.x += pong.x_speed pong.rect.y += pong.y_speed # determine collision or miss # if the pong hits the left paddle if pygame.sprite.collide_rect(pong, left_paddle): paddle_bounce(left_paddle, pong) # if the pong hits the right paddle elif pygame.sprite.collide_rect(pong, right_paddle): paddle_bounce(right_paddle, pong) # if the pong hits top/bottom of the screen if pong.rect.y >= SCREEN_HEIGHT - pong.size or pong.rect.y <= 0: pong.wall_bounce() # if the pong goes off the left, point for right paddle if pong.rect.x <= 0 - pong.size: right_paddle.add_point(1) right_paddle_score = draw_score(right_paddle) pong.score() # if the pong goes off the right, point for the left paddle elif pong.rect.x >= SCREEN_WIDTH: left_paddle.add_point(1) left_paddle_score = draw_score(left_paddle) pong.score() # --- Drawing code should go here # First, clear the screen to white (or black, or whatever). # Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(BLACK) draw_net(screen) # draw the score screen.blit(left_paddle_score, [SCREEN_WIDTH/4, score_down]) screen.blit(right_paddle_score, [3 * (SCREEN_WIDTH/4), score_down]) # Draw all sprites all_sprites_list.draw(screen) # update the screen with what has been drawn pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) pygame.quit() #required to actually quit and close the window without hanging
from stream import Stream from generator import Generator from car import Car
import os import sys REDMINE_HOME = '/opt/redmine-3.1.1-0' REDMINE_HOME = '/opt/redmine-3.4.3-1' REDMINE_HOME = '/opt/redmine-4.0.2-1' def redmine_redcase(): os.system('wget https://bitbucket.org/bugzinga/redcase/downloads/redcase-1.0.zip') os.system('unzip redcase-1.0.zip') os.system('mv redcase '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/') cmds=('cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/bundle install', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(';'.join(cmds)) os.system(REDMINE_HOME+'/ctlscript.sh restart') def redmine_usability(): #os.system('git clone https://github.com/tdvsdv/usability.git') #os.system('mv usability '+REDMINE_HOME+'/apps/redmine/htdocs/plugins') #cmds=('cd '+REDMINE_HOME+'/apps/redmine/htdocs', # REDMINE_HOME+'/ruby/bin/bundle install', # REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') #print ';'.join(cmds) #os.system(';'.join(cmds)) #os.system(REDMINE_HOME+'/ctlscript.sh restart') pass def wiki_extensions(): version = '0.9.0' cmds = ['cd /tmp', 'rm -rf /tmp/redmine_wiki_extensions'+version, 'wget https://github.com/haru/redmine_wiki_extensions/releases/download/0.9.0/redmine_wiki_extensions-0.9.0.zip', 'unzip redmine_wiki_extensions-0.9.0.zip', 'mv redmine_wiki_extensions '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/bundle install', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production'] os.system(';'.join(cmds)) os.system(REDMINE_HOME+'/ctlscript.sh restart') def theme(): #os.system('git https://github.com/FabriceSalvaire/redmine-improved-theme.git') #os.system('mv redmine-improved-theme.git '+REDMINE_HOME+'/apps/redmine/htdocs/public/themes/') #os.system('git clone https://bitbucket.org/dkuk/redmine_alex_skin.git') #os.system('mv redmine_alex_skin '+REDMINE_HOME+'/apps/redmine/htdocs/public/themes/') #os.system('git clone https://github.com/makotokw/redmine-theme-gitmike.git') #os.system('mv redmine-theme-gitmike '+REDMINE_HOME+'/apps/redmine/htdocs/public/themes/') pass def before(): os.system('yum groupinstall "Development Tools" -y') os.system('yum install unzip -y') os.system('yum install zlib-devel libuuid-devel -y') os.system('yum install xapian-core-devel xapian-bindings-ruby -y') os.system('rm -rf master stable') def after(): """ Alternative without changing system: Add the following code at the end of /public/javascripts/application.js function addTargetExternalLinks() { $('a.external').each(function() { $(this).attr('target','_blank'); }); } $(document).ready(addTargetExternalLinks); """ pass def redmine_agile(): """ cmds = ['cd /tmp', 'rm -rf /tmp/redmine_agile', 'git clone https://github.com/RCRM/redmine_agile.git', 'rm -rf '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_agile', 'mv redmine_agile '+REDMINE_HOME+'/apps/redmine/htdocs/plugins', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/bundle install --without development test RAILS_ENV=production', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '*** ',';'.join(cmds) os.system(';'.join(cmds)) """ version = '1.4.6-light' cmds = ['cd /tmp', 'rm -rf /tmp/redmine_agile' 'wget https://github.com/bitnami/bitnami-docker-redmine/files/2078617/redmine_agile-1_4_6-light.zip', 'rm -rf '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_agile', 'unzip v'+' '+'/redmine_agile-1_4_6-light.zip', 'rm -rf '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_agile', 'mv redmine_agile'+' '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_agile', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/bundle install --without development test RAILS_ENV=production', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '*** ',';'.join(cmds) os.system(';'.join(cmds)) def redmine_checklists(): cmds = ['cd /tmp', 'git clone https://github.com/RCRM/redmine_checklists.git', 'mv redmine_checklists '+REDMINE_HOME+'/apps/redmine/htdocs/plugins', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print "*** ",';'.join(cmds) os.system(';'.join(cmds)) def redmine_sidebar_hide(): version = '0.0.8' os.system('wget http://www.redmine.org/attachments/download/17394/sidebar_hide-'+version+'.zip') os.system('unzip sidebar_hide-'+version+'.zip') os.system('mv sidebar_hide '+REDMINE_HOME+'/apps/redmine/htdocs/plugins') os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') """ def redmine_dashboard(): os.system('rm -rf master stable') os.system('wget https://github.com/jgraichen/redmine_dashboard/archive/master.zip') os.system('unzip master') os.system('mv redmine_dashboard-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_dashboard') os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/gem install json -v 1.8.1') os.system(REDMINE_HOME+'/ruby/bin/bundle install --no-deployment') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') """ def redmine_github_master_zip(owner,repo): url = "/".join(['https://github.com',owner,repo,'archive/master.zip']) cmds = ['cd /tmp', 'rm -rf master stable master.zip', 'wget '+url, 'unzip master.zip'] print '***',';'.join(cmds) os.system(';'.join(cmds)) do_install_plugin(repo,repo+'-master') def do_install_plugin(plugin,folder): cmds = ['rm -rf '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/'+plugin, 'cd /tmp', 'mv '+folder+' '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/'+plugin, 'cd '+REDMINE_HOME+'/apps/redmine/htdocs/plugins', REDMINE_HOME+'/ruby/bin/bundle install --without xapian --no-deployment', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '***',';'.join(cmds) os.system(';'.join(cmds)) def redmine_easy_gantt_free(): plugin_zip = 'EasyGanttFree.zip' cmds = ['cd /tmp', 'rm -rf easy_gantt', 'unzip '+plugin_zip] print '***',';'.join(cmds) os.system(';'.join(cmds)) do_install_plugin('easy_gantt','easy_gantt') def redmine_issue_dynamic_edit(): pass def redmine_ckeditor(): cmds = ['cd /tmp', 'rm -rf master stable master.zip', 'wget https://github.com/a-ono/redmine_ckeditor/archive/master.zip', 'unzip master.zip', 'rm -rf '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_ckeditor', 'mv redmine_ckeditor-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_ckeditor', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs/plugins', REDMINE_HOME+'/ruby/bin/bundle install --no-deployment', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '***',';'.join(cmds) os.system(';'.join(cmds)) def redmine_dmsf(): cmds = ['yum install libuuid-devel -y'] print '***',';'.join(cmds) os.system(';'.join(cmds)) cmds = ['yum install xapian-omega libxapian-dev xpdf poppler-utils antiword \ unzip catdoc libwpd-tools libwps-tools gzip unrtf catdvi djview djview3 \ uuid uuid-dev xz libemail-outlook-message-perl -y'] print '***',';'.join(cmds) os.system(';'.join(cmds)) """ cmds = ['cd /tmp', 'rm -rf master stable master.zip', 'wget https://github.com/danmunn/redmine_dmsf/archive/master.zip', 'unzip master.zip', 'mv redmine_dmsf-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_dmsf', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/bundle install', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '***',';'.join(cmds) os.system(';'.join(cmds)) """ cmds = ['cd /tmp', 'rm -rf master stable master.zip', 'wget https://github.com/danmunn/redmine_dmsf/archive/master.zip', 'unzip master.zip', 'yum install zlib-devel libuuid-devel -y', 'mv redmine_dmsf-master'+' '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_dmsf', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOMe+'/ruby/bin/gem install xapian-full-alaveteli -v 1.2.9.5', REDMINE_HOME+'/ruby/bin/bundle install', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '***',';'.join(cmds) os.system(';'.join(cmds)) """ version = '1.5.6' #version = '1.6.0' cmds = ['cd /tmp', 'rm -rf master stable master.zip', 'rm -rf '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_dmsf', 'wget https://github.com/danmunn/redmine_dmsf/archive/v'+version+'.zip', 'unzip v'+version+'.zip', 'mv redmine_dmsf-'+version+' '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_dmsf', 'cd '+REDMINE_HOME+'/apps/redmine/htdocs', REDMINE_HOME+'/ruby/bin/bundle install --without xapian', REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production', REDMINE_HOME+'/ctlscript.sh restart'] print '***',';'.join(cmds) os.system(';'.join(cmds)) #os.system(REDMINE_HOME+'/ruby/bin/gem install xapian-full-alaveteli -v 1.2.9.5') #os.system(REDMINE_HOME+'/ruby/bin/gem install xapian-full-alaveteli -v 1.2.21.1') #os.system(REDMINE_HOME+'/ruby/bin/gem install rubyzip --version 1.2.0') """ def scrum(): os.system('wget https://redmine.ociotec.com/attachments/download/440/scrum%20v0.16.2.tar.gz --no-check-certificate') os.system('tar xvfz scrum\ v0.16.2.tar.gz') #os.system('mv scrum\ v0.16.2 '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/scrum') os.system('mv scrum '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/scrum') os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') def redmine_contacts(): os.system('wget http://redminecrm.com/license_manager/12403/redmine_contacts-3_2_17-light.zip') os.system('unzip redmine_contacts-3_2_17-light.zip') os.system('mv redmine_contacts '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/') os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') def clipboard_image_paste(): os.system('rm -rf master stable') os.system('wget https://github.com/peclik/clipboard_image_paste/archive/master.zip') os.system('unzip master') os.system('mv clipboard_image_paste-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/clipboard_image_paste') os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') def redmine_impassed(): """ os.system('rm -rf master stable') os.system('wget https://github.com/kawasima/redmine_impasse/archive/master.zip') os.system('unzip master') os.system('mv redmine_impasse-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_impasse'); os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') """ pass def redmine_monitoring_controlling(): os.system('rm -rf master stable') os.system('wget https://github.com/alexmonteiro/Redmine-Monitoring-Controlling/archive/master.zip') os.system('unzip master') os.system('mv Redmine-Monitoring-Controlling-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_monitoring_controlling'); os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') def redmine_issue_templates(): os.system('rm -rf master stable') os.system('wget https://bitbucket.org/akiko_pusu/redmine_issue_templates/downloads/redmine_issue_templates-0.0.8.zip -O redmine_issue_templates-0.0.8.zip') os.system('unzip redmine_issue_templates-0.0.8.zip') os.system('mv redmine_issue_templates '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_issue_templates'); os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') def redmine_smart_ganttchart(): os.system('rm -rf master stable') os.system('wget https://github.com/mizoguche/redmine_smart_ganttchart/archive/master.zip') os.system('unzip master.zip') os.system('mv redmine_smart_ganttchart-master '+REDMINE_HOME+'/apps/redmine/htdocs/plugins/redmine_smart_ganttchart') os.system('cd '+REDMINE_HOME+'/apps/redmine/htdocs') os.system(REDMINE_HOME+'/ruby/bin/bundle install') os.system(REDMINE_HOME+'/ruby/bin/rake redmine:plugins:migrate RAILS_ENV=production') os.system(REDMINE_HOME+'/ctlscript.sh restart') def change_issuses_sql(): """ ================Redmine Calendar view not working========================= You need to modify the redmine/app/controller/calendars_controller.rb file. Add issues before start_date and due_date like this: events += @query.issues(:include => [:tracker, :assigned_to, :priority], :conditions => ["((issues.start_date BETWEEN ? AND ?) OR (issues.due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt] ) restart redmine. """ pass def email(): """ ================ ./apps/redmine/htdocs/config/configuration.yml====== default: # Outgoing emails configuration (see examples above) email_delivery: delivery_method: :smtp smtp_settings: address: smtp.gmail.com port: 587 domain: dnssentry.net authentication: :login user_name: unknown@gmail.com password: dpfflwldh """ pass def main(): #redmine_agile() #redmine_issue_templates() #redmine_checklists() #redmine_ckeditor() #redmine_dmsf() #wiki_extensions() #redmine_usability() #redmine_smart_ganttchart() #redmine_redcase() #redmine_sidebar_hide() #redmine_github_master_zip('kulesa','redmine_better_gantt_chart') #redmine_github_master_zip('Ilogeek','redmine_issue_dynamic_edit') #redmine_github_master_zip('jgraichen','redmine_dashboard') #redmine_github_master_zip('MadEgg','redmine_planning') #redmine_github_master_zip('mizoguche','redmine_smart_ganttchart') #redmine_github_master_zip('osamax2','easy_gantt') #redmine_github_master_zip('canidas','redmine_issue_todo_lists') #redmine_github_master_zip('Emergya','redmine_traceability') #redmine_github_master_zip('akiko-pusu','redmine_issue_templates') #redmine_github_master_zip('syntacticvexation','redmine_favourite_projects') #redmine_github_master_zip('suer','redmine_absolute_dates') redmine_github_master_zip('mintow','cuckoos') #redmine_easy_gantt_free() pass if __name__ == "__main__": main()
#!/usr/bin/env python import matplotlib as mpl def rundark(): mpl.rc('lines', linewidth=1, color='w') mpl.rc('patch', edgecolor='w') mpl.rc('text', color='w') mpl.rc('font', size=9, family='sans-serif') mpl.rc('axes', facecolor='k', edgecolor='w', labelcolor='w',\ color_cycle=[ 'w','r','g','y', 'c', 'm', 'b', 'k'],\ labelsize=9) mpl.rc('xtick', color='w') mpl.rc('ytick', color='w') mpl.rc('grid', color='w') mpl.rc('figure', facecolor='k', edgecolor='k') mpl.rc('savefig', dpi=100, facecolor='k', edgecolor='k') #mpl.rc('text', usetex=True) #mpl.rc('text.latex', preamble='\usepackage{sfmath}') def runbright(): mpl.rc('lines', linewidth=1, color='w') mpl.rc('patch', edgecolor='w') mpl.rc('text', color='k') mpl.rc('font', size=9, family='sans-serif') mpl.rc('axes', facecolor='w', edgecolor='k', labelcolor='k', \ color_cycle=[ 'k','r','g','y', 'c', 'm', 'b', 'w'],\ labelsize=9) mpl.rc('xtick', color='k') mpl.rc('ytick', color='k') mpl.rc('grid', color='k') mpl.rc('figure', facecolor='w', edgecolor='w') mpl.rc('savefig', dpi=100, facecolor='w', edgecolor='w') #mpl.rc('text', usetex=True) #mpl.rc('text.latex', preamble='\usepackage{sfmath}') class Line(object): def __init__(self): orange = '#FF6500' green = '#07D100' lightblue = '#00C8FF' blue = '#0049FF' purple = '#BD00FF' self.red = dict(c='r', ls="-", lw=1, alpha=1.0) self.orange = dict(c=orange, ls="-", lw=1, alpha=1.0) self.yellow = dict(c='y', ls="-", lw=1, alpha=1.0) self.green = dict(c=green, ls="-", lw=1, alpha=1.0) self.purple = dict(c=purple, ls="-", lw=1, alpha=1.0) self.lightblue = dict(c=lightblue, ls="-", lw=1, alpha=1.0) self.cyan = dict(c='c', ls="-", lw=1, alpha=1.0) self.blue = dict(c=blue, ls="-", lw=1, alpha=1.0) self.magenta = dict(c='m', ls="-", lw=1, alpha=1.0) self.white = dict(c='w', ls="-", lw=1, alpha=1.0) self.black = dict(c='k', ls="-", lw=1, alpha=1.0) class Dots(object): def __init__(self): orange = '#FF6500' green = '#07D100' lightblue = '#00C8FF' blue = '#0049FF' purple = '#BD00FF' self.red = dict(c='r', ls="o", mfc="r", mec="r", marker='o', alpha=1.0, ms=1) self.orange = dict(c=orange, ls="o", mfc=orange, mec=orange, marker='o', alpha=1.0, ms=1) self.yellow = dict(c='y', ls="o", mfc="y", mec="y", marker='o', alpha=1.0, ms=1) self.green = dict(c=green, ls="o", mfc=green, mec=green, marker='o', alpha=1.0, ms=1) self.purple = dict(c=purple, ls="o", mfc=purple, mec=purple, marker='o', alpha=1.0, ms=1) self.lightblue = dict(c=lightblue, ls="o", mfc=lightblue, mec=lightblue, marker='o', alpha=1.0, ms=1) self.cyan = dict(c='c', ls="o", mfc="c", mec="c", marker='o', alpha=1.0, ms=1) self.blue = dict(c=blue, ls="o", mfc=blue, mec=blue, marker='o', alpha=1.0, ms=1) self.magenta = dict(c='m', ls="o", mfc="m", mec="m", marker='o', alpha=1.0, ms=1) self.white = dict(c='w', ls="o", mfc="w", mec="w", marker='o', alpha=1.0, ms=1) self.black = dict(c='k', ls="o", mfc="k", mec="k", marker='o', alpha=1.0, ms=1) class ErrDots(object): def __init__(self): orange = '#FF6500' green = '#07D100' lightblue = '#00C8FF' blue = '#0049FF' purple = '#BD00FF' self.red = dict(fmt='o', ls="o", ecolor= 'r', alpha=1.0) self.orange = dict(fmt='o', ls="o", ecolor= orange, alpha=1.0) self.yellow = dict(fmt='o', ls="o", ecolor= 'y', alpha=1.0) self.green = dict(fmt='o', ls="o", ecolor= green, alpha=1.0) self.purple = dict(fmt='o', ls="o", ecolor= purple, alpha=1.0) self.lightblue = dict(fmt='o', ls="o", ecolor= lightblue, alpha=1.0) self.cyan = dict(fmt='o', ls="o", ecolor= 'c', alpha=1.0) self.blue = dict(fmt='o', ls="o", ecolor= blue, alpha=1.0) self.magenta = dict(fmt='o', ls="o", ecolor= 'm', alpha=1.0) self.white = dict(fmt='o', ls="o", ecolor= 'w', alpha=1.0) self.black = dict(fmt='o', ls="o", ecolor= 'k', alpha=1.0)
from datetime import datetime import getpass import requests import json from lxml import etree import os import re import sys import uuid if sys.version_info[:2] <= (2, 7): # Python 2 get_input = raw_input import ConfigParser as configparser else: # Python 3 get_input = input import configparser class ArchivesSpaceError(Exception): pass class ConnectionError(ArchivesSpaceError): pass class AuthenticationError(ArchivesSpaceError): pass class CommunicationError(ArchivesSpaceError): def __init__(self, status_code, response): message = "ArchivesSpace server responded {}".format(status_code) self.response = response super(CommunicationError, self).__init__(message) class ASpaceAPIClient(object): def __init__(self, instance_name=None, repository=2, expiring="true"): self.config_file = os.path.join(os.path.expanduser("~"), ".aspaceapi") configuration = self._load_config(instance_name) self.backend_url = configuration["backend_url"] self.frontend_url = configuration["frontend_url"] self.repository = "/repositories/{}".format(repository) self.username = configuration["username"] password = configuration.get("password") if not password: password = getpass.getpass("Enter password: ") self.expiring = expiring self._login(password) def _load_config(self, instance_name): config = configparser.RawConfigParser() config.read(self.config_file) instances = config.sections() if len(instances) == 0: print("No ArchivesSpace instances configured. Configure an instance? (y/n)") configure = get_input(": ") if configure.lower().strip() == "y" or configure.lower().strip() == "yes": configuration = self._add_instance(config) return configuration else: sys.exit() elif instance_name and instance_name in instances: configuration = {key: value for ( key, value) in config.items(instance_name)} return configuration else: instance_mapping = {} instance_number = 0 print("*** CONFIGURED INSTANCES ***") for instance in instances: instance_number += 1 instance_mapping[str(instance_number)] = instance instance_url = config.get(instance, "backend_url") print("{} - {} [{}]".format(instance_number, instance, instance_url)) print("A - Add Instance") option = get_input("Select an option: ") if option.strip() in instance_mapping.keys(): instance = instance_mapping[option] configuration = {key: value for ( key, value) in config.items(instance)} return configuration elif option.lower().strip() == "a": configuration = self._add_instance(config) return configuration else: sys.exit() def _save_config(self, config): with open(self.config_file, "wb") as f: config.write(f) def _add_instance(self, config): instance_name = get_input("Instance name: ") backend_url = get_input("Backend URL: ") frontend_url = get_input("Frontend URL: ") username = get_input("Default username: ") store_password = get_input( "Store a password for this instance? (y/n) ") if store_password == "y": password = getpass.getpass("Enter password: ") else: password = False config.add_section(instance_name) config.set(instance_name, "backend_url", backend_url) config.set(instance_name, "frontend_url", frontend_url) config.set(instance_name, "username", username) if password: config.set(instance_name, "password", password) self._save_config(config) return {"backend_url": backend_url, "frontend_url": frontend_url, "username": username, "password": password} def _login(self, password): url = self.backend_url + "/users/" + self.username + "/login" params = {"password": password, "expiring": self.expiring} authenticate = requests.post(url, params=params).json() if authenticate.get("session", ""): self.session = requests.Session() token = authenticate["session"] self.session.headers.update({"X-ArchivesSpace-Session": token}) else: print("Error logging in:") print(authenticate) sys.exit() def _request(self, method, url, params, expected_response, data=None): response = method(url, params=params, data=data) if response.status_code != expected_response: raise CommunicationError(response.status_code, response) try: response.json() except Exception: raise ArchivesSpaceError( "ArchivesSpace server responded with status {}, but returned a non-JSON document".format(response.status_code)) return response def _get(self, url, params={}, expected_response=200): return self._request(self.session.get, url, params=params, expected_response=expected_response) def _put(self, url, params={}, data=None, expected_response=200): return self._request(self.session.put, url, params=params, data=data, expected_response=expected_response) def _post(self, url, params={}, data=None, expected_response=200): return self._request(self.session.post, url, params=params, data=data, expected_response=expected_response) def _delete(self, url, params={}, expected_response=200): return self._request(self.session.delete, url, params=params, expected_response=expected_response) def logout(self): url = self.backend_url + "/logout" self._post(url) def get_aspace_json(self, aspace_uri, params={}): url = "{}{}".format(self.backend_url, aspace_uri) return self._get(url, params=params).json() def post_aspace_json(self, aspace_uri, data=[], params={}): url = "{}{}".format(self.backend_url, aspace_uri) return self._post(url, params=params, data=json.dumps(data)).json() def delete_aspace_object(self, aspace_uri, params={}): url = "{}{}".format(self.backend_url, aspace_uri) return self._delete(url, params=params).json() def update_aspace_object(self, aspace_uri, aspace_json, params={}): if aspace_uri == aspace_json["uri"]: return self.post_aspace_json(aspace_uri, aspace_json, params=params) else: raise ArchivesSpaceError("Unable to update object. Supplied URI {} does not match {}".format( aspace_uri, aspace_json["uri"])) def list_resources(self): uri = self.repository + "/resources" params = {"all_ids": True} return self.get_aspace_json(uri, params=params) def get_resource(self, resource_id): resource_uri = self.repository + "/resources/{}".format(resource_id) return self.get_aspace_json(resource_uri) def get_accession(self, accession_id): accession_uri = self.repository + "/accessions/{}".format(accession_id) return self.get_aspace_json(accession_uri) def get_subject(self, subject_id): subject_uri = "/subjects/{}".format(subject_id) return self.get_aspace_json(subject_uri) def get_agent(self, agent_uri): return self.get_aspace_json(agent_uri) def get_person(self, agent_person_id): agent_uri = "/agents/people/{}".format(agent_person_id) return self.get_agent(agent_uri) def get_corporate_entity(self, corporate_entity_id): agent_uri = "/agents/corporate_entities/{}".format(corporate_entity_id) return self.get_agent(agent_uri) def get_family(self, family_id): agent_uri = "/agents/families/{}".format(family_id) return self.get_agent(agent_uri) def get_digital_object(self, digital_object_id): digital_object_uri = self.repository + \ "/digital_objects/{}".format(digital_object_id) return self.get_aspace_json(digital_object_uri) def get_archival_object(self, archival_object_id): archival_object_uri = self.repository + \ "/archival_objects/{}".format(archival_object_id) return self.get_aspace_json(archival_object_uri) def get_archival_object_children(self, archival_object_id): uri = self.repository + \ "/archival_objects/{}/children".format(archival_object_id) return self.get_aspace_json(uri) def post_archival_object_children(self, children, archival_object_id): uri = self.backend_url + self.repository + \ "/archival_objects/{}/children".format(archival_object_id) archival_object_children = { "children": children, "jsonmodel_type": "archival_record_children"} response = self._post(uri, data=json.dumps(archival_object_children)) return response.json() def get_bhl_classifications(self, aspace_json): classifications = [] classification_fields = ["enum_1", "enum_2", "enum_3"] user_defined_fields = aspace_json["user_defined"] for classification_field in classification_fields: if user_defined_fields.get(classification_field): classifications.append(user_defined_fields[classification_field]) return classifications def find_by_id(self, id_type, id_value): id_lookup_uri = self.repository + "/find_by_id/archival_objects" params = {"{}[]".format(id_type): id_value} id_lookup = self.get_aspace_json(id_lookup_uri, params=params) resolved_archival_objects = id_lookup["archival_objects"] if len(resolved_archival_objects) == 1: return {"success": resolved_archival_objects[0]["ref"]} else: return {"error": "Error resolving {} {}: {} archival objects returned".format(id_type, id_value, len(resolved_archival_objects))} def resolve_component_id(self, component_id): return self.find_by_id("component_id", component_id) def resolve_refid(self, ref_id): if ref_id.startswith("aspace_"): ref_id = ref_id.replace("aspace_", "") return self.find_by_id("ref_id", ref_id) def make_resource_link(self, resource_number): return "{}/resources/{}".format(self.frontend_url, resource_number) def transfer_archival_object(self, archival_object_uri, resource_uri): uri = "/repositories/2/component_transfers" params = {"target_resource": resource_uri, "component": archival_object_uri} response = self.post_aspace_json(uri, params=params) event_to_delete = response["event"] self.delete_aspace_object(event_to_delete) return response def set_archival_object_parent(self, archival_object_id, parent_id, position=0): uri = "/repositories/2/archival_objects/{}/parent".format( archival_object_id) params = {"parent": int(parent_id), "position": position} response = self.post_aspace_json(uri, params=params) return response def make_archival_object_link_from_id(self, archival_object_id): archival_object = self.get_archival_object(archival_object_id) resource_ref = archival_object["resource"]["ref"] resource_number = resource_ref.split("/")[-1] return "{0}/resources/{1}#tree::archival_object_{2}".format(self.frontend_url, resource_number, archival_object_id) def make_archival_object_link_from_json(self, archival_object): resource_ref = archival_object["resource"]["ref"] resource_id = resource_ref.split("/")[-1] archival_object_uri = archival_object["uri"] return self.make_archival_object_link(resource_id, archival_object_uri) def make_archival_object_link(self, resource_number, aspace_uri): archival_object_number = aspace_uri.split("/")[-1] return "{0}/resources/{1}#tree::archival_object_{2}".format(self.frontend_url, resource_number, archival_object_number) def create_digital_object(self, title, link, identifier=False, publish=True, note_content="access item"): digital_object_json = {} digital_object_json["title"] = title if identifier: digital_object_json["digital_object_id"] = identifier else: digital_object_json["digital_object_id"] = str(uuid.uuid4()) digital_object_json["publish"] = publish digital_object_json["notes"] = [{"type": "note", "content": [ note_content], "publish": True, "jsonmodel_type":"note_digital_object"}] digital_object_json["file_versions"] = [ {"file_uri": link, "xlink_show_attribute": "new", "xlink_actuate_attribute": "onRequest"}] return digital_object_json def post_digital_object(self, digital_object_json): uri = self.repository + "/digital_objects" return self.post_aspace_json(uri, data=digital_object_json) def make_digital_object_instance(self, digital_object_uri): return {'instance_type': 'digital_object', 'digital_object': {'ref': digital_object_uri}} def make_container_instance(self, top_container_uri): pass def post_archival_object(self, title="", begin_date="", end_date="", date_expression="", digital_object_uri=False, top_container_uri=False, general_note=False): pass def get_export_metadata(self, resource_number): uri = self.repository + \ "/bhl_resource_descriptions/{}.xml/metadata".format( resource_number) return self.get_aspace_json(uri) def convert_ead_to_aspace_json(self, ead_filepath): self.session.headers.update( {"Content-type": "text/html; charset=utf-8"}) uri = self.backend_url + "/plugins/jsonmodel_from_format/resource/ead" with open(ead_filepath, "rb") as f: response = self.session.post(uri, data=f).json() return response def export_ead(self, resource_number, include_unpublished=False, include_daos=True, numbered_cs=True, digitization_ead=False, default_ead=False): if digitization_ead: resource_description_uri = "/bhl_resource_descriptions_digitization/" elif default_ead: resource_description_uri = "/resource_descriptions/" else: resource_description_uri = "/bhl_resource_descriptions/" uri = self.backend_url + self.repository + \ resource_description_uri + "{}.xml".format(resource_number) params = { "include_unpublished": include_unpublished, "include_daos": include_daos, "numbered_cs": numbered_cs } ead = self.session.get(uri, params=params) return ead def unpublish_aspace_object(self, uri): object_json = self.get_aspace_json(uri) if object_json["publish"]: object_json["publish"] = False resource_uri = self.backend_url + uri response = self.session.post(resource_uri, json=object_json).json() else: response = "{} already unpublished".format(uri) return response def unpublish_resource(self, resource_number): uri = self.repository + "/resources/{}".format(resource_number) response = self.unpublish_aspace_object(uri) return response def get_top_container_by_barcode(self, barcode): uri = self.repository + "/find_by_barcode/container" params = {"barcode": barcode} return self.get_aspace_json(uri, params=params) def get_top_container(self, container_id): uri = self.repository + "/top_containers/{}".format(container_id) return self.get_aspace_json(uri) def update_top_container(self, container_id, container_json): uri = self.repository + "/top_containers/{}".format(container_id) self.post_aspace_json(uri, container_json) def post_top_container(self, container_type, indicator, barcode=False): uri = self.backend_url + self.repository + "/top_containers" top_container = {"indicator": indicator, "type": container_type, "jsonmodel_type": "top_container"} if barcode: top_container["barcode"] = barcode response = self._post(uri, data=json.dumps(top_container)) return response.json()["uri"] def get_metadata_for_container(self, top_container_id): uri = self.repository + \ "/metadata_for_container/{}".format(top_container_id) response = self.get_aspace_json(uri) return response def merge_top_containers(self, source_id, target_id): # replace all references to source with references to target and delete source archival_objects = self.get_metadata_for_container(source_id)[ "archival_objects"] source_uri = self.repository + "/top_containers/{}".format(source_id) target_uri = self.repository + "/top_containers/{}".format(target_id) archival_object_uris = [archival_object["archival_object_uri"] for archival_object in archival_objects] for archival_object_uri in archival_object_uris: archival_object = self.get_aspace_json(archival_object_uri) instances = archival_object["instances"] matching_instances = [ instance for instance in instances if instance["sub_container"]["top_container"]["ref"] == source_uri] for matching_instance in matching_instances: matching_instance["sub_container"]["top_container"]["ref"] = target_uri self.update_aspace_object(archival_object_uri, archival_object) self.delete_aspace_object(source_uri) def get_resource_tree(self, resource_number): # /repositories/:repo_id/resources/:id/tree uri = self.backend_url + self.repository + \ "/resources/{}/tree".format(resource_number) response = self._get(uri) return response.json() def get_enumeration(self, enumeration_id): uri = "/config/enumerations/{}".format(enumeration_id) enumeration = self.get_aspace_json(uri) return enumeration def update_enumeration(self, enumeration_id, enumeration): uri = "/config/enumerations/{}".format(enumeration_id) self.post_aspace_json(uri, enumeration) def add_enumeration_values(self, enumeration_id, new_enumeration_values): enumeration = self.get_enumeration(enumeration_id) values_to_add = [ value for value in new_enumeration_values if value not in enumeration["values"]] if values_to_add: enumeration["values"].extend(values_to_add) self.update_enumeration(enumeration_id, enumeration) def remove_resource_associations(self, resource_number): resource_tree = self.get_resource_tree(resource_number) children_with_instances = find_children_with_instances( resource_tree["children"]) instance_uris = [] for child_uri in children_with_instances: instance_uris.extend(self.find_instance_uris(child_uri)) for instance_uri in set(instance_uris): self.delete_single_resource_instances(instance_uri) def get_resource_children_with_instances(self, resource_number, instance_type=False): resource_tree = self.get_resource_tree(resource_number) children_with_instances = find_children_with_instances( resource_tree["children"], instance_type=instance_type) return children_with_instances def delete_single_resource_instances(self, instance_uri): if "digital_objects" in instance_uri: digital_object = self.get_aspace_json(instance_uri) if len(digital_object["linked_instances"]) == 1: self.delete_aspace_object(instance_uri) elif "top_containers" in instance_uri: top_container = self.get_aspace_json(instance_uri) if len(top_container["collection"]) == 1: self.delete_aspace_object(instance_uri) def find_instance_uris(self, aspace_uri, instance_type=False): instance_uris = [] aspace_json = self.get_aspace_json(aspace_uri) instances = aspace_json["instances"] if instance_type: instances = [ instance for instance in instances if instance["instance_type"] == instance_type] for instance in instances: if instance["instance_type"] == "digital_object": instance_uris.append(instance["digital_object"]["ref"]) else: instance_uris.append( instance["sub_container"]["top_container"]["ref"]) return instance_uris def build_hierarchy(self, aspace_json, delimiter=">"): parent_titles = [] while aspace_json.get("parent"): parent_ref = aspace_json["parent"]["ref"] parent_json = self.get_aspace_json(parent_ref) parent_title = self.make_display_string(parent_json) parent_titles.append(parent_title) aspace_json = parent_json parent_titles.reverse() if parent_titles: return " {} ".format(delimiter).join(parent_titles) else: return "" def make_display_string(self, aspace_json, add_parent_title=False): if aspace_json.get("title") and aspace_json.get("dates"): return self.sanitize_title(aspace_json["title"]) + ", " + self.format_dates(aspace_json) elif aspace_json.get("title") and not aspace_json.get("dates"): return self.sanitize_title(aspace_json["title"]) elif aspace_json.get("dates") and not aspace_json.get("title"): if add_parent_title: parent_ref = aspace_json["parent"]["ref"] parent_json = self.get_aspace_json(parent_ref) parent_title = self.sanitize_title( parent_json["display_string"]) return parent_title + ", " + self.format_dates(aspace_json) else: return self.format_dates(aspace_json) def get_most_proximate_date(self, aspace_json): while not aspace_json.get("dates") and aspace_json.get("parent"): parent_ref = aspace_json["parent"]["ref"] aspace_json = self.get_aspace_json(parent_ref) return self.format_dates(aspace_json) def format_dates(self, aspace_json): if aspace_json.get("dates"): inclusive_dates = [] bulk_dates = [] for date in aspace_json["dates"]: expression = date.get("expression", "") if not expression: begin = date.get("begin", "") end = date.get("end", "") if begin and end: expression = "{}-{}".format(begin, end) elif begin: expression = begin if date["date_type"] == "inclusive": inclusive_dates.append(expression.strip()) if date["date_type"] == "bulk": bulk_dates.append(expression.strip()) dates = ", ".join(inclusive_dates) if bulk_dates: dates += " (bulk {})".format(bulk_dates[0]) return dates else: return "" def sanitize_title(self, title): return re.sub(r"<.*?>", "", title).strip() def find_notes_by_type(self, aspace_json, note_type): matching_notes = [note for note in aspace_json["notes"] if note.get("type") == note_type] if matching_notes: return matching_notes else: return "" def find_note_by_type(self, aspace_json, note_type): matching_notes = [note for note in aspace_json["notes"] if note.get("type") == note_type] if matching_notes: return self.format_note(matching_notes[0]) else: return "" def format_note(self, note): if note["jsonmodel_type"] == "note_singlepart": return note["content"][0] else: return note["subnotes"][0]["content"] def get_resource_archival_object_uris(self, resource_number): resource_tree = self.get_resource_tree(resource_number) archival_object_uris = extract_archival_object_uris_from_children( resource_tree["children"]) return archival_object_uris def unpublish_expired_restrictions_for_resource(self, resource_number): today = datetime.today().strftime("%Y-%m-%d") archival_object_uris = self.get_resource_archival_object_uris( resource_number) unpublished_log = [] for archival_object_uri in archival_object_uris: update_archival_object = False archival_object = self.get_aspace_json(archival_object_uri) for note in archival_object["notes"]: if note["type"] == "accessrestrict" and note["publish"]: accessrestrict = self.format_note(note) accessrestrict_xml = etree.fromstring( "<accessrestrict>{}</accessrestrict>".format(accessrestrict)) accessrestrict_date = accessrestrict_xml.xpath("./date") if accessrestrict_date and (accessrestrict_date[0].attrib["normal"] < today): note["publish"] = False update_archival_object = True unpublished_log.append( {"uri": archival_object_uri, "title": archival_object["display_string"], "restriction": accessrestrict}) if update_archival_object: self.session.post(self.backend_url + archival_object_uri, json=archival_object).json() return unpublished_log def unpublish_restrictions_by_text(self, resource_number, restriction_text=False): if not restriction_text: return "No restriction text provided" archival_object_uris = self.get_resource_archival_object_uris( resource_number) unpublished_log = [] for archival_object_uri in archival_object_uris: update_archival_object = False archival_object = self.get_aspace_json(archival_object_uri) for note in archival_object["notes"]: if note["type"] == "accessrestrict" and note["publish"]: accessrestrict = self.format_note(note) if accessrestrict == restriction_text: note["publish"] = False update_archival_object = True unpublished_log.append( {"uri": archival_object_uri, "title": archival_object["display_string"], "restriction": accessrestrict}) if update_archival_object: self.session.post(self.backend_url + archival_object_uri, json=archival_object).json() return unpublished_log def parse_extents(self, aspace_json): parsed_extents = [] if aspace_json.get("extents"): for extent in aspace_json["extents"]: parsed_extent = "{} {}".format( extent["number"], extent["extent_type"]) container_summary = extent.get("container_summary") physical_details = extent.get("physical_details") dimensions = extent.get("dimensions") parenthetical_parts = [attribute for attribute in [ container_summary, physical_details, dimensions] if attribute] if parenthetical_parts: parenthetical = "; ".join(parenthetical_parts) parsed_extent = "{} ({})".format( parsed_extent, parenthetical) parsed_extents.append(parsed_extent) if parsed_extents: return "; ".join(parsed_extents) else: return "" def get_collection_id(self, resource_json): ead_id = resource_json.get("ead_id") identifier = resource_json["id_0"].strip() collection_id_regex = re.compile(r"^[\d\.]+") if ead_id: collection_id = "-".join(ead_id.split("-")[2:]) elif collection_id_regex.match(identifier): collection_id = re.findall(r"^[\d\.]+", identifier)[0] else: collection_id = "" return collection_id def parse_link_from_digital_object(self, digital_object): if digital_object.get("file_versions"): return digital_object["file_versions"][0]["file_uri"] else: return digital_object["digital_object_id"] def get_digital_object_instance_links(self, aspace_json, match_pattern=False): links = [] digital_object_instances = [instance for instance in aspace_json["instances"] if instance["instance_type"] == "digital_object"] for digital_object_instance in digital_object_instances: digital_object_uri = digital_object_instance["digital_object"]["ref"] digital_object = self.get_aspace_json(digital_object_uri) links.append(self.parse_link_from_digital_object(digital_object)) if match_pattern: links = [link for link in links if match_pattern in link] return links def get_agents_by_role(self, aspace_json, role): agents = [agent["ref"] for agent in aspace_json["linked_agents"] if agent["role"] == role] return agents def get_first_agent_by_role(self, aspace_json, role): agents = self.get_agents_by_role(aspace_json, role) if agents: agent_uri = agents[0] agent_name = self.get_aspace_json(agent_uri)["title"] return self.verify_punctuation(agent_name) else: return "" def get_accession_source(self, accession_json): return self.get_first_agent_by_role(accession_json, "source") def get_resource_creator(self, resource_json): return self.get_first_agent_by_role(resource_json, "creator") def get_linked_agents(self, aspace_json): linked_agents = [agent for agent in aspace_json["linked_agents"]] return [self.construct_agent_name(linked_agent) for linked_agent in linked_agents] def construct_agent_name(self, linked_agent): agent_ref = linked_agent["ref"] agent_name = self.get_aspace_json(agent_ref)["title"] if linked_agent.get("terms"): if agent_name.endswith("."): agent_name = agent_name.rstrip(".") parts = [agent_name] parts.extend([term["term"] for term in linked_agent["terms"]]) agent_name = " -- ".join(parts) return self.verify_punctuation(agent_name) def verify_punctuation(self, subject_or_agent): if not (subject_or_agent.endswith(".") or subject_or_agent.endswith(")") or subject_or_agent.endswith("-")): subject_or_agent += "." return subject_or_agent def get_linked_subjects(self, aspace_json, ignore_types=[]): subject_uris = [subject["ref"] for subject in aspace_json["subjects"]] subjects_json = [self.get_aspace_json( subject_uri) for subject_uri in subject_uris] return [self.verify_punctuation(subject["title"]) for subject in subjects_json if subject["terms"][0]["term_type"] not in ignore_types] def extract_archival_object_uris_from_children(children, archival_object_uris=[]): for child in children: archival_object_uris.append(child["record_uri"]) if child["has_children"]: extract_archival_object_uris_from_children( child["children"], archival_object_uris=archival_object_uris) return archival_object_uris def find_children_with_instances(children, children_with_instances=[], instance_type=False): for child in children: if child["instance_types"]: if instance_type and instance_type in child["instance_types"]: children_with_instances.append(child["record_uri"]) elif not instance_type: children_with_instances.append(child["record_uri"]) if child["has_children"]: find_children_with_instances( child["children"], children_with_instances=children_with_instances, instance_type=instance_type) return children_with_instances
from flask import Flask, request from flask_restful import Resource, Api, reqparse from flask_jwt import JWT, jwt_required from security import authenticate, identity #När vi använder flask_restful behöver vi inte använda jsonify. Det fixat flask_restful åt oss. app = Flask(__name__) app.secret_key = 'rasmus' api = Api(app) #JWT skapar en ny endpoint /auth #När vi kallar på /auth skickar vi username och password som vidarebefodrar de till authenticate-funktionen som returnerar en JWT-Token. #Vid nästa request så använder vi vår JTW-Token och skickar med till identity-funktionen som kan returnera om usern finns och returnerar "user_id" och JWT-token är valid jwt = JWT(app, authenticate, identity) items_list = [] #för varje ny "endpoint" skapar man upp en resurs som ärver från "Resource" class Item(Resource): #Gör så att reqparse tillhör Item-klassen istället för metoden så kallar du på 'Item.parser' i metoden. #json-payloaden kommer köras igenom reqparse och att tolka innehållet parser = reqparse.RequestParser() #lägger till argument som skall hjälpa parsern att tolka payloaden parser.add_argument('price', #kommer tolkas som en float type=float, #kräver att det finns ett pris required=True, help="This field cannot be left blank!" #Finns fler användabara argument att utforska ) #@jwt_required lägg som decorator som tar in authenticate och identity. Dessa måste returerna förväntade värden för att get/post skall kunna köras. #Använd denna decorator för varje metod för så klienten måste identifiera sig inför varje request #POSTMAN info: POST/auth, Body{"username": "användare","password": "lösen"}, kopiera acces_token #POSTMAN info: typ av request, Header: Authentication, "JTW 'acces_token'" @jwt_required() def get(self, name): #next tar det första item som matchar x['name']. Next får att använda flera gånger för att ta nästa och nästa osv. #Next kan generera ett error om den in finner något x['name'] som matchar. Lägg då till ', None' i slutet för att returnera None. item = next(filter(lambda x : x['name'] == name, items_list), None) #Om requesten är OK returnera 200 annars 404 not found. return {'item': item}, 200 if item else 404 #@jwt_required() def post(self, name): if next(filter(lambda x: x['name'] == name, items_list), None): #Om item redan existerar, returnera 400 = bad request. return {['item:' "Item with name '{}' already exists".format(name)]}, 400 #force=True även om content-type Header inte är satt till t.ex application.json så formateras den ändå. #silence=True returnerar ingen Error, endast None. #Här parsar/tolkar parse_args innehåller i parser och placerar de godkända argumenten i data data = Item.parser.parse_args() item = {'name': name, 'price': data['price']} items_list.append(item) #Fanns ditt item, returnera item och status, 201 = Created return item, 201 #@jwt_required() def delete(self, name): #itererar igenom items_list och filtrera ut "name" och ersätta resterande värden med en ny lista som läggs i "items_list" #OBS! viktigt att använda sig av globala items_list annars tror har du endast använt en lokal variable av items_list. #Saknar en if-sats ifall 'name' inte finns... global items_list items_list = list(filter(lambda x: x ['name'] != name, items_list)) return {'message': 'Item deleted'} #@jwt_required() def put(self, name): data = Item.parser.parse_args() item = next(filter(lambda x: x ['name'] == name, items_list), None) if item is None: item = {'name': name, 'price': data['price']} items_list.append(item) else: item.update(data) return item class ItemList(Resource): #@jwt_required() def get(self): return items_list #Förklarar vilken endpoint och klass som hör ihop. api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') #debug=True ger dig en html-sida där du kan fel söka när något är fel i koden. #flask använder port 5000 app.run(port=5000, debug=True)
import conexao_banco as sql def todos(): stmt = 'select "id_clientes","CPF_CNPJ", "email", "telefone","nome_razaosocial" from "Usuarios" inner join "Clientes" on "Usuarios"."id_usuario" = "Clientes"."id_usuario" order by "id_clientes"' result = sql.query(stmt) return(result) def busca(idcliente): stmt = f'select "id_clientes","nome_razaosocial","CPF_CNPJ", "telefone", "email" ,"endereco","senha","login","responsavel", "dia_pagamento" from "Usuarios" inner join "Clientes" on "Usuarios"."id_usuario" = "Clientes"."id_usuario" where "Clientes"."id_clientes" = {idcliente}' result = sql.query(stmt) return(result) def inclusao(cpf_cnpj, senha, login, nome, telefone, email, endereco, responsavel,diaPagamento): stmt = f''' select "id_usuario" from "Usuarios" where "CPF_CNPJ" = '{cpf_cnpj}' ''' result = sql.query(stmt) print(result) if result == []: stmt = f'''INSERT INTO public."Usuarios"("CPF_CNPJ", senha, login) VALUES ('{cpf_cnpj}', '{senha}', '{login}') ''' result = sql.update(stmt) print(result) if result == 'Feito': stmt = f'''select "id_usuario" from "Usuarios" where login = '{login}' and "CPF_CNPJ" = '{cpf_cnpj}' ''' result = sql.query(stmt) for x in result: stmt = f''' INSERT INTO public."Clientes"(id_usuario, nome_razaosocial, telefone, email, endereco, responsavel, dia_pagamento) VALUES ('{x['id_usuario']}', '{nome}', '{telefone}', '{email}','{endereco}', '{responsavel}',{diaPagamento});''' result = sql.update(stmt) else: stmt = f'''select "Id_Usuario" from Usuarios where "CPF_CNPJ" = '{cpf_cnpj}' ''' result = sql.query(stmt) for x in result: stmt = f''' INSERT INTO public.clientes("Id_Usuario", "Responsavel", "Codigo_Forma_Pagamento", "Dia_Pagamento") VALUES ('{x['Id_Usuario']}', '{responsavel}' );''' result = sql.update(stmt) return(result) def edicao(cpf_cnpj, nome, endereco, telefone, email, senha, idusuario, responsavel, diaPagamento, login): stmt = f'''UPDATE "Clientes" set "nome_razaosocial" = '{nome}', "endereco" = '{endereco}', "telefone" = '{telefone}', "email" = '{email}' , "responsavel" = '{responsavel}', "dia_pagamento" = {diaPagamento} where "id_clientes" = {idusuario}''' result = sql.update(stmt) stmt = f'''select "id_usuario" from "Clientes" where "id_clientes" = {idusuario} ''' result = sql.query(stmt) for x in result: stmt = f''' UPDATE "Usuarios" set "CPF_CNPJ" = '{cpf_cnpj}' , "senha" = '{senha}',"login" = '{login}' where "id_usuario" = {x['id_usuario']}''' result = sql.update(stmt) return result def exclusao(id): for x in id: stmt = f''' delete from "Clientes" where "id_clientes" = {x}''' print(stmt) result = sql.update(stmt)
a=int(input("Enter the number")) l=["one","two","three","four","five","six","seven","eight","nine","ten"] if 0<a<=10: print(l[a-1]) else: print("enter between 1 to 10")
#! /usr/bin/env python # title : EKF_filter.py # description : This module reads /vo, /odom, /imu and uses the extended kalman # filtering for the fusion. # author : Salah Eddine Ghamri # date : 17-03-2018 # version : 0.5 # usage : in Roslaunch file add: # <node name="EKF_filter" pkg="package_name" type="EKF_filter.py" output="screen"> # notes : Rate affects response # python_version : 2.6.7 # ================================================================================== import rospy import KALMAN_lib # initialisation------------------------------------ # node initialisation rospy.init_node('EKF_filter') frequency = 200.00 # it depends Rate = rospy.Rate(frequency) # very dangerous pay attention # x is of the form [x, y, theta, v, omega]'--------- x = [[0.0], [0.0], [0.0], [0.0], [0.0]] # P is covariance size(x) x size(x) P = [0.0, 0.0, 0.0, 0.0, 0.0] # variance of process noise sigma_v = 0.1 sigma_omega = 0.1 # variance of measurement noise must be declared in # "R" in KALMAN_lib.estimate() if needed. # -------------------------------------------------- kalman = KALMAN_lib.kalman_class(x, P) caller = KALMAN_lib.caller() if __name__ == "__main__": try: old_time = rospy.Time().now().to_sec() # loop continues while ros is not shutdown while not rospy.is_shutdown(): # time step for prediction new_time = rospy.Time().now().to_sec() T = new_time - old_time # read sensors now caller.read_sensors() # Estimation, estimates and return estimation error. # but we don't estimate the first time error = kalman.estimate(caller) # predict the next robot position kalman.predict(T, sigma_v, sigma_omega) # Publish on /odom_combined kalman.publish_message(caller) old_time = new_time # rospy.sleep(10) Rate.sleep() except rospy.ROSInterruptException: pass
def largestDivisibleSubset(nums): """ :type nums: List[int] :rtype: List[int] """ nums = sorted(nums) dp = [0]*len(nums) for i in range(len(nums)): for j in range(i, -1, -1): if (nums[i]%nums[j]==0): dp[i] = max(dp[i], dp[j]+1) maxIndex = 0 for i in range(len(nums)): maxIndex = i if dp[i] > dp[maxIndex] else maxIndex res = [] temp = nums[maxIndex] current = dp[maxIndex] for i in range(len(nums)-1,-1,-1): if (temp%nums[i] == 0 and dp[i] == current): res.append(nums[i]) temp = nums[i] current -= 1 return res print(largestDivisibleSubset([3,4,16,8]))