text
stringlengths
38
1.54M
# Contains read time suggestion algorithms from util.pewma import Pewma import math import numpy as np class ReadTimeSuggestionAlgorithm: """ Read time suggestion dummy class. """ def next(self, t, v): raise NotImplementedError("next(...) not implemented.") class Periodic(ReadTimeSuggestionAlgorithm): """ Suggest read time using a fixed distance between consecutive read times. """ def reset(self): pass def __init__(self, dt): self.name = str(list(zip(locals().keys(), locals().values()))) self.dt = dt def next(self, t, v): return round(t + self.dt) class AdaM(ReadTimeSuggestionAlgorithm): """ AdaM read time suggestion algorithm. """ def reset(self): self.pewma = Pewma(self.p_d_init, self.p_alpha, self.p_beta) self.v_last = float('nan') self.conf = float('nan') self.logMean = np.empty([self.logSize]) self.logVar = np.empty([self.logSize]) self.logConf = np.empty([self.logSize]) self.logTD = np.empty([self.logSize]) self.iterationNumber = 0 def __init__(self, p_d_init, p_alpha, p_beta, p_gamma, p_lambda, p_t_min, log_size=0): self.name = str(list(zip(locals().keys(), locals().values()))) self.p_d_init = p_d_init self.p_alpha = p_alpha self.p_beta = p_beta self.p_gamma = p_gamma self.p_lambda = p_lambda self.p_T_min = p_t_min self.logSize = log_size assert (self.p_gamma < 1) assert (self.p_gamma > 0) self.reset() def __has_sample(self): return not np.isnan(self.v_last).all() def next(self, t, v): if self.__has_sample(): delta_i = np.sum(np.abs(self.v_last - v)) prev_variance = self.pewma.est_var self.pewma.next(delta_i) curr_variance = self.pewma.est_var self.conf = 1. - (0 if prev_variance == 0 else math.fabs(curr_variance - prev_variance) / prev_variance) self.conf = max(self.conf, 0) # XXX: neither in paper, nor in java implementation, but makes sense. if self.conf >= 1 - self.p_gamma: self.td_next = round(self.td_next + self.p_lambda * ( 1. + math.fabs(self.conf - self.p_gamma) / self.conf)) # XXX: fabs due to AdaM:53 else: self.td_next = self.p_T_min else: self.td_next = self.p_T_min assert (self.td_next >= self.p_T_min) t_d = round(t + self.td_next) if self.iterationNumber < self.logMean.shape[0]: self.logMean[self.iterationNumber] = self.pewma.est_mean self.logVar[self.iterationNumber] = self.pewma.est_var self.logConf[self.iterationNumber] = self.conf self.logTD[self.iterationNumber] = t_d self.iterationNumber += 1 self.v_last = v return t_d def get_log_mean(self): return self.logMean[:self.iterationNumber - 1] def get_log_var(self): return self.logVar[:self.iterationNumber - 1] def get_log_confidence(self): return self.logConf[:self.iterationNumber - 1] def get_log_td(self): return self.logTD[:self.iterationNumber - 1]
# remove particular elements from list list1=[1,4,6,5,9,7,4] num=int(input("which itom idex do you want to remove")) list1.pop(num) print(list1)
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> #Q.1- Print anything you want on screen. >>> print("hii my name is ashish and m learning well") hii my name is ashish and m learning well >>> x="hy my name is ashish and m learning well" >>> x 'hy my name is ashish and m learning well' >>> x ="hy my name is ashish" >>> print(x) hy my name is ashish >>> print("%s"%("hy y name is ashish")) hy y name is ashish >>> #END >>> SyntaxError: invalid syntax >>> >>> #Q.2- Join two strings using '+'. >>> x="\"Acad\"" >>> y="\"View\"" >>> print(x+y) "Acad""View" >>> #without "" >>> x="Acad" >>> y="View" >>> print(x+y) AcadView >>> #END SyntaxError: invalid syntax >>> >>> #Q.3- Take the input of 3 variables x, y and z . Print their values on screen >>> x="rajat" >>> y="ashish" >>> z="yash" >>> print(x,y,z) rajat ashish yash >>> #another >>> >>> x="1" >>> y="2" >>> z="3" >>> print(x,y,z) 1 2 3 SyntaxError: invalid syntax >>> >>> #Q.4- Print “Let’s get started” on screen. >>> print(" \" Let’s get started \" ") " Let’s get started " >>> #another >>> x=" \" Let’s get started \" " >>> x ' " Let’s get started " ' >>> #another >>> >>> x=" \" Let’s get started \" " >>> print(x) " Let’s get started " >>> >>> #end SyntaxError: invalid syntax >>> >>> #Q.5- Print the following values using placeholders. #s=”Acadview” #course=”Python” #fees=5000 >>> >>> print(" s = \"%s\", \n course = \"%s\" , \n fees = \"%d\"" % ("python","acadview", 5000)) s = "python", course = "acadview" , fees = "5000" >>> #End SyntaxError: invalid syntax >>> >>> #Q.6- Let’s do some interesting exercise: #name=”Tony Stark” #salary=1000000 #print(‘%s’’%d’)%(____ ,____) >>> name= "\"tony stark\"" >>> saliry= "\"100000\"" >>> print("%s,%s" % (name,saliry)) "tony stark","100000" >>> #END
from django.shortcuts import render from django.http import HttpRequest from .models import Game # Create your views here. def index(request: HttpRequest): return render(request, "regency_app/index.html", context={}) def join_game(request: HttpRequest): games = Game.objects.order_by("-start_date")[:5] return render(request, "regency_app/join_game.html", context={"games_list": games})
import math def stdDevOfLengths(L=None): """Return the standard deviation on the length of strings. Expects L to be a list. Returns standard deviation Returns 'NaN' if the list is empty """ if not L or len(L) < 1: return float('NaN') # Get the mean of the length of the words count = 0 for word in L: count += len(word) mean = count / len(L) # Compute the standard deviation using the mean numerator = 0 for word in L: std_dev = (len(word) - mean) ** 2 numerator += std_dev std_dev = math.sqrt((numerator / len(L))) return std_dev if __name__ == '__main__': # Basic tests L1 = ['a', 'z', 'p'] L2 = ['apples', 'oranges', 'kiwis', 'pineapples'] print(stdDevOfLengths(L1)) print(stdDevOfLengths(L2))
# Misc. Helper Functions from functools import wraps #for login_required from flask import session """If user isn't logged in, they will be redirected away from certain pages back to home""" def login_required(f): @wraps(f) def is_logged_in(*args, **kwargs): if 'logged_in' not in session: return redirect(url_for('home')) return f(*args, **kwargs) return is_logged_in """ Returns the desired http method. Looks for a _method=DELETE property in the form""" def get_http_method(request): if request.method == 'POST' and '_method' in request.form and request.form['_method']=='DELETE': return 'DELETE' else: return request.method
# -*- coding: utf-8 -*- # __author__ = 'Gz' from basics_function.golable_function import MD5 import time import copy import requests import json import threading class FiveNut: def __init__(self, fail_list): self.salt = "3*y4f569#tunt$le!i5o" self.fail_list = fail_list self.time_stamp = int(round(time.time() * 1000)) self.token = None self.sign = None self._value_lock = threading.Lock() self.duid = None def get_sign(self, data): header_data = data["headers"] try: duid = header_data["duid"] except: assert False, "header 中没有duid" try: language = header_data["lang"] except: assert False, "header 中没有lang" try: version = header_data["version"] except: assert False, "header 中没有version" data = duid + "_" + language + "_" + str(self.time_stamp) + "_" + str(version) + "_" + self.salt result = MD5(data) return result def set_header(self, data): header_data = data["headers"] try: duid = header_data["duid"] except: assert False, "header 中没有duid" try: language = header_data["lang"] except: assert False, "header 中没有lang" try: version = header_data["version"] except: assert False, "header 中没有version" new_header_data = copy.deepcopy(header_data) new_header_data.pop("duid") new_header_data.pop("lang") new_header_data.pop("version") new_header_data.update( {"User-Agent": duid + "#&#" + language + "#&#" + str(self.time_stamp) + "#&#" + str(version)}) return new_header_data def get_token(self, data, headers, source): if self.sign is None or self.duid != data["headers"]["duid"]: sign = self.get_sign(data) else: sign = self.sign if source == "test": token_url = "http://api.dev.wuren.com:8080/v1/identity/login" else: token_url = "https://api.5nuthost.com/v1/identity/login" try: response = requests.post(token_url, json={"sign": sign}, headers=headers) token = json.loads(response.text)["info"]["token"] except: print(response.text) assert False, "获取token错误" return token
# coding: utf8 from urbvan_framework.schemas import (BaseResponseSchema, BaseBodySchema) from urbvan import permissions def render_response_error(errors={}): list_errors = [] for key, value in errors.items(): if type(value) is list: value = {"message": value[0]} value.update({"field": key}) list_errors.append(value) response = {"errors": list_errors} response = BaseResponseSchema().dump(response).data return response def render_to_response(body={}): response = {} response = BaseBodySchema().dump({ "result": body }).data response = BaseResponseSchema().dump({ "body": response }).data return response def get_urbvan_permissions(action): if action == 'destroy': permission_classes = [permissions.AdminUserPermission] elif action == 'create': permission_classes = [permissions.StaffUserPermission] elif action == 'partial_update': permission_classes = [permissions.StaffUserPermission] else: permission_classes = [permissions.UserPermission] return [permission() for permission in permission_classes]
from Grid import * from Inputs import * from NeuronKohonen import * if __name__ == '__main__': #ustawienia i parametry sieci neuronowej learningRate = 0.1 epoch = 100 noOfInputs = 4 width = 20 height = 20 inputs = Inputs() #utworzenie danych wejściowych """Przypisanie danych róznych kwiatow to zmiennych""" species = {} for i in range(3): species[inputs.getInputData(i)[0]] = inputs.getInputData(i)[1] #zainicjalizowanie siatki neuronów Kohonena WTA grid = Grid(noOfInputs, learningRate, width, height) #tablica zwycięzców Kohonena winner = {} #wśród wszystkich neuronów w siatce odnajdywany jest zwycięzca for i in range(epoch): for j in range(len(species["Iris-setosa"])): for key in species.keys(): winner[key] = grid.train(species[key][j]) for key, value in winner.items(): print(key) for val in value.getWeightsAsString().replace('[','').replace(']','').split(', '): print(val) testData = {} for i in range(3): testData[inputs.getTestData(i)[0]] = inputs.getTestData(i)[1] #sprawdzanie jak wiele z danych testowych zostanie poprawnie odgadnięte matched = 0 winnerTest = {} for key, value in testData.items(): for j in range(len(testData["Iris-setosa"])): winnerTest[key] = grid.guess(value[j]) if winnerTest[key] == winner[key]: matched += 1 print(matched) """średnie z danych wejściowych""" #averages: #Iris-setosa [5.01, 3.42, 1.47, 0.25] #Iris-versicolor [5.94, 2.78, 4.26, 1.33] #Iris-virginica [6.59, 2.98, 5.56, 2.03] """średnie z danych znormalizowanych""" #averages: #[0.81, 0.55, 0.24, 0.04] #[0.75, 0.35, 0.54, 0.17] #[0.71, 0.32, 0.6, 0.22]
from django.contrib import admin from modeltranslation.admin import TranslationAdmin from dictionaries import models from dictionaries.forms import DefaultElementAdminForm from grappelli_orderable.admin import GrappelliOrderableAdmin class SizeAdmin(GrappelliOrderableAdmin): list_display = ('size',) class DefaultElementAdmin(admin.ModelAdmin): form = DefaultElementAdminForm class OrderableTranslationAdmin(GrappelliOrderableAdmin, TranslationAdmin): pass # regular models admin.site.register(models.DefaultElement, DefaultElementAdmin) admin.site.register([ models.Font, models.FabricCategory ]) admin.site.register(models.Size, SizeAdmin) admin.site.register([ models.Color, models.StitchColor, models.CollarType ], GrappelliOrderableAdmin) # translated models admin.site.register([ models.TuckType, models.CuffRounding, models.PocketType, models.DickeyType, models.HemType, models.PlacketType, models.CustomButtonsType, models.SleeveType, models.BackType, ], TranslationAdmin) admin.site.register([ models.SizeOptions, models.YokeType, models.CollarButtons, models.FabricDesign, models.FabricColor, models.CuffType, models.FabricType, models.Thickness ], OrderableTranslationAdmin)
from django.db import models class contect(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone = models.CharField(max_length=13) text = models.TextField(max_length=500) timestamp = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return 'Message from '+ self.name+'-'+ self.email class post(models.Model): title = models.CharField(max_length=500) content = models.TextField(max_length=100000000) slug = models.SlugField(max_length=50) author = models.CharField(max_length=20) image = models.ImageField(upload_to='image/') timestamp = models.DateTimeField( blank=True) def __str__(self): return 'Blog title:'+ self.title +' by '+ self.author
#!/usr/bin/env python3 import argparse import json # This is the location of the IaaS swagger old_filename = "swagger/vra-iaas.json" new_filename = "swagger/vra-iaas-fixed.json" def replace_value(d, k, v, new): if k in d and d[k] == v: print(d[k]) print("found one") d[k] = new for child in d.values(): if isinstance(child, dict): replace_value(child, k, v, new) def rename_iaas_deployment(swagger): v = swagger['definitions']['Deployment'] del swagger['definitions']['Deployment'] swagger['definitions']['IaaSDeployment'] = v old_value = "#/definitions/Deployment" new_value = "#/definitions/IaaSDeployment" replace_value(swagger, "$ref", old_value, new_value) # Delete all the definitions not referred by any endpoints in IaaS API swagger def delete_unreferenced_definitions(swagger): del swagger['definitions']['AuthorizationContext'] del swagger['definitions']['Connection'] del swagger['definitions']['DatabaseMetaData'] del swagger['definitions']['DeferredResultObject'] del swagger['definitions']['DataSource'] del swagger['definitions']['PostgresSchemaManager'] del swagger['definitions']['ResultSet'] del swagger['definitions']['ResultSetMetaData'] del swagger['definitions']['ScheduledExecutorService'] del swagger['definitions']['Service'] del swagger['definitions']['ServiceDocument'] del swagger['definitions']['ServiceHost'] del swagger['definitions']['ServiceHostState'] del swagger['definitions']['ServiceStat'] del swagger['definitions']['Statement'] del swagger['definitions']['TableDescription'] del swagger['definitions']['Thread'] del swagger['definitions']['TimeSeriesStats'] del swagger['definitions']['Tracer'] if __name__ == "__main__": parser = argparse.ArgumentParser() args = parser.parse_args() # read in the swagger spec swagger = json.loads(open(old_filename).read()) rename_iaas_deployment(swagger) delete_unreferenced_definitions(swagger) # Overwrite the swagger spec f = open(new_filename, "w") f.write(json.dumps(swagger, sort_keys=False, indent=2)) f.write('\n')
#!/usr/bin/python from django.core.management import setup_environ import settings setup_environ(settings) import time import logging import statgrab from status.models import * kb = 1024 mb = kb * kb while True: ### Host data ### cpu = statgrab.sg_get_cpu_percents() load = statgrab.sg_get_load_stats() host = statgrab.sg_get_host_info() mem = statgrab.sg_get_mem_stats() hs = HostStats(hostname = host['hostname'], uptime = host['uptime'], arch = host['platform'], min1 = str(load['min1']), min5 = str(load['min5']), min15 = str(load['min15']), mem_total = mem['total'] / mb, mem_free = (mem['cache'] + mem['free']) / mb, mem_used = mem['used'] / mb) hs.save() ### FS data ### filesystems = statgrab.sg_get_fs_stats() for fs in filesystems: fs_stat = FilesystemStats(device = fs['device_name'], used_perc = str(float(fs['used']) / float(fs['size']) * 100.0), size = fs['size'] / mb, used = fs['used'] / mb, avail = fs['avail'] / mb, fs_type = fs['fs_type']) fs_stat.save() ### Network data ### statgrab.sg_get_network_io_stats() time.sleep(1) # Collect data over 1 second diff = statgrab.sg_get_network_io_stats_diff() netstats = statgrab.sg_get_network_iface_stats() for iface in diff: for netstat in netstats: if iface['interface_name'] == netstat['interface_name']: ns = NetworkStats(interface = iface['interface_name'], up = netstat['up'], tx = iface['tx'] / kb, rx = iface['rx'] / kb) ns.save() time.sleep(1)
# -*- coding: utf-8 -*- import multiprocessing import glob from eod import rewrite_data import ipdb import os import xarray as xr import numpy as np import pandas as pd from utils import constants as cnst, u_met from scipy.interpolate import griddata def saveDaily(): files = glob.glob('/prj/AMMA2050/CP4/historical/25km/precip/*.nc') for svar in files: out = svar.replace('A1hr_mean', 'Aday_mean') out = out.replace('precip', 'precip_day') ds = xr.open_dataset(svar) ds = ds.groupby('time.day').sum('time') ds.to_netcdf(out)
from django.shortcuts import render,redirect from .models import Log from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect import datetime from .forms import LogForm from logbook import models from logbook import forms from django.utils import six from django.contrib import messages @login_required def index(request): # Render the HTML template index.html with the data in the context variable # return render( # request, # 'index.html', # context={}, # ) log_list = Log.objects.all() return render(request, "logbook/log_list.html", {'log_list':log_list}) @login_required def logs(request): log_list = Log.objects.all() log = request.GET.get('page', 1) paginator = Paginator(log_list, 2) try: logs = paginator.page(log) except PageNotAnInteger: logs = paginator.page(1) except EmptyPage: logs = paginator.page(paginator.num_pages) return render(request, "logbook/log_list.html", {'log_list':log_list, 'Log':Log}) @login_required def delete(request, id): log = Log.objects.get(pk = id) log.delete() return redirect('index') @login_required def edit(request, id): log = get_object_or_404(Log, id=id) if request.method == "POST": form = AddNewLog(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = AddNewLog() return render(request, 'logbook/add_new_log.html', {'form': form, 'Log':Log}) def log_new(request): if request.method == "POST": form = LogForm(request.POST) if form.is_valid(): log = form.save(commit=False) log.email = request.user.username log.save() return redirect('logs') else: form = LogForm() return render(request, 'logbook/log_edit.html', {'form': form}) def log_edit(request, id): log = get_object_or_404(Log, id=id) if request.method == "POST": form = LogForm(request.POST, instance=log) if form.is_valid(): log = form.save(commit=False) log.email = request.user.username log.save() form.save_m2m() return redirect('logs') else: form = LogForm() return render(request, 'logbook/log_edit.html', {'form': form}) def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('index') else: form = UserCreationForm() return render(request, 'logbook/signup.html', {'form': form})
from typing import Union from numpy import asarray from itertools import zip_longest def nonelen(l): return 0 if l is None else len(l) def noneratio(x,y): return None if x is None or y is None else x/y def nonecast(x,fill_value=0.0): if x is not None: return [xj if xj is not None else fill_value for xj in x] def notallnone(x): return not all([ xj is None for xj in x]) def nearlysame(x,y,tol=1e-6): return all( ( abs(xj-yj)<tol for xj,yj in zip_longest(x,y,fillvalue=.777))) def nonennearlysame(x,y,tol=1e-6): x_cast = nonecast(x, fill_value=333.0) y_cast = nonecast(x, fill_value=333.0) return nearlysame(x_cast,y_cast) def nonecenter(m,x): """ :param m: List of masses :param x: List of points, can be None or vector :returns: point that is center of mass """ assert notallnone(m) assert notallnone(x) m_when_x_not_none = [ m for m,x in zip(m,x) if x is not None] x_when_x_not_none = [ x for m,x in zip(m,x) if x is not None] m_cast = nonecast(m_when_x_not_none,fill_value=0.0) x_cast = [ nonecast(pj,fill_value=0.0) for pj in x_when_x_not_none] if sum(m_cast)<1e-9: m_cast = [1./len(m_cast) for _ in m_cast ] return center(m_cast, x_cast) def center(m:[float], x:[[float]])->[Union[None, float]]: """ Center of mass m masses x set of points """ if len(m)!=len(x): import warnings warnings.warn('length mismatch') P = asarray([ asarray(xj) for xj in x]) M = asarray(m) PM = (P.T * M).T try: PM_sum = PM.sum(axis=0) except: k = 1 pass c = PM_sum / M.sum() return c.tolist()
''' programa 0 un programa que nos pida el nombre y que te responda encantado de conocerte''' nombre = input('¿Cómo te llamas?') print('encantado de conocerte,',nombre) cont = 0 while cont <= 9: print('hola', nombre, cont) cont = cont + 1
#!/usr/bin/python3 ''' @author: Edgar D. Arenas-Díaz ''' from optparse import OptionParser import subprocess import os def main(): parser = OptionParser() parser.add_option("-s", "--source-path", dest="srcpath", metavar="SRCPATH", help="Path to source files") parser.add_option("-f", "--results-filename", dest="resultpath", metavar="RESULTPATH", help="Name of the output results file") (options,args) = parser.parse_args() if (options.srcpath == None or options.resultpath == None): print("Both paths (source and results filename) are needed") print() parser.print_help() exit() outFile = open(options.resultpath, 'w') print('alignment-file-rated, GLOCSA, meanColumnValue, gapConcentration, columnIncrementRatio, meanGapBlockSize, totalGapPositions, numberGapBlocks, columnsNotAligned, columnsAligned, estimatedEvents, substitutionEvents, inDelEvents', file=outFile) print('alignment-file-rated, GLOCSA, meanColumnValue, gapConcentration, columnIncrementRatio, meanGapBlockSize, totalGapPositions, numberGapBlocks, columnsNotAligned, columnsAligned, estimatedEvents, substitutionEvents, inDelEvents') action(options.srcpath, outFile) outFile.close() def action(srcPath, outFile): contentlist = os.listdir(srcPath) dirslist = [] for element in contentlist: srcElemFPath = srcPath+"/"+element if os.path.isdir(srcElemFPath): dirslist.append(srcElemFPath) elif srcElemFPath.endswith("rating"): ratingFile = open(srcElemFPath, 'r') line = ratingFile.readline() while line != '': line = line[:-1] name,sep,value = line.partition(':') if sep == ':': value = value.strip() print(value, end=', ', file=outFile) print(value, end=', ',) line = ratingFile.readline() print('', file=outFile) print('') ratingFile.close() if(len(dirslist) > 0): for dirspath in dirslist: action(dirspath, outFile) if __name__ == '__main__': main()
# import basic packages import cv2, torch, types import numpy as np from numpy import random # import pytorch packages from torchvision import transforms import torchvision.transforms.functional as FT # for normalize / resize / to_tensor class ToTensor(object) : def __call__(self, image, boxes=None, labels=None, difficulties=None): # Convert nd_array to Torch tensor new_image = FT.to_tensor(image) return new_image, boxes, labels, difficulties # normalize class Normalize(object) : def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, image, boxes=None, labels=None, difficulties=None): new_image = FT.normalize(image, mean = self.mean, std = self.std) return new_image, boxes, labels, difficulties # resize class Resize(object): def __init__(self, size=300): self.size = size def __call__(self, image, boxes=None, labels=None, difficulties=None): # transfer from PIL to nd_array image = np.array(image) new_image = cv2.resize(image, (self.size, self.size)) height, width, _ = image.shape boxes[:,0] = boxes[:,0]/width boxes[:,1] = boxes[:,1]/height boxes[:,2] = boxes[:,2]/width boxes[:,3] = boxes[:,3]/height boxes = boxes.type(torch.float32) return new_image, boxes, labels, difficulties # =============================== # Photometri cDistort class PhotometricDistort(object): def __init__(self, photometricdistort_arg) : self.pd = [ RandomContrast(photometricdistort_arg["contrast_range"][0],photometricdistort_arg["contrast_range"][1]), RandomSaturation(photometricdistort_arg["saturation_range"][0],photometricdistort_arg["saturation_range"][1]), RandomBrightness(photometricdistort_arg["brightness_range"][0],photometricdistort_arg["brightness_range"][1]), RandomHue(photometricdistort_arg["hue_delta"]), ] def __call__(self, image, box=None, labels=None, difficulties=None): new_image = image random.shuffle(self.pd) for d in self.pd : new_image = d(new_image) return new_image, box, labels, difficulties class RandomSaturation(object): def __init__(self, lower, upper): self.lower = lower self.upper = upper assert self.upper >= self.lower, "contrast upper must be >= lower." assert self.lower >= 0, "contrast lower must be non-negative." def __call__(self, image): if random.random() < 0.5: adjust_factor = random.uniform(self.lower, self.upper) # Transformation image = FT.adjust_saturation(image, adjust_factor) return image class RandomHue(object): def __init__(self, delta): assert delta >= 0.0 and delta <= 360.0 self.delta = delta def __call__(self, image): if random.random() < 0.5: adjust_factor = random.uniform( -self.delta/255. , self.delta/255. ) # Transformation image = FT.adjust_hue(image, adjust_factor) return image class RandomContrast(object): def __init__(self, lower, upper): self.lower = lower self.upper = upper assert self.upper >= self.lower, "contrast upper must be >= lower." assert self.lower >= 0, "contrast lower must be non-negative." # expects float image def __call__(self, image): if random.random() < 0.5: adjuct_factor = random.uniform(self.lower, self.upper) image = FT.adjust_contrast(image, adjuct_factor) return image class RandomBrightness(object): def __init__(self, lower, upper): self.lower = lower self.upper = upper assert self.upper >= self.lower, "contrast upper must be >= lower." assert self.lower >= 0, "contrast lower must be non-negative." def __call__(self, image): if random.random() < 0.5: adjust_factor = random.uniform(self.lower, self.upper) image = FT.adjust_brightness(image, adjust_factor) return image #================================= # Expand class Expand(object): def __init__(self, mean): self.mean = mean def __call__(self, image, boxes=None, labels=None, difficulties=None): # convert PIL to numpy array image = np.array(image) boxes = np.array(boxes) if random.random() < 0.5: return image, boxes, labels, difficulties else : height, width, depth = image.shape ratio = random.uniform(1, 4) left = random.uniform(0, width*ratio - width) top = random.uniform(0, height*ratio - height) expand_image = np.zeros( (int(height*ratio), int(width*ratio), depth), dtype=image.dtype) expand_image[:, :, :] = self.mean expand_image[int(top):int(top + height), int(left):int(left + width)] = image image = expand_image boxes = boxes.copy() boxes[:, :2] += (int(left), int(top)) boxes[:, 2:] += (int(left), int(top)) return image, boxes, labels, difficulties # Flip / (also called random mirror) class RandomMirror(object): def __call__(self, image, boxes=None, classes=None, difficulties=None): # retrieve width image = np.array(image) _, width, _ = image.shape new_image = transforms.ToPILImage()(image) new_boxes = boxes if random.randint(2): # Flip images new_image = FT.hflip(new_image) # Flip boxes new_boxes = boxes new_boxes[:, 0] = width - boxes[:, 0] - 1 new_boxes[:, 2] = width - boxes[:, 2] - 1 new_boxes = new_boxes[:, [2, 1, 0, 3]] return new_image, new_boxes, classes, difficulties # random crop class RandomSampleCrop(object): """Crop Arguments: img (Image): the image being input during training boxes (Tensor): the original bounding boxes in pt form labels (Tensor): the class labels for each bbox mode (float tuple): the min and max jaccard overlaps Return: (img, boxes, classes) img (Image): the cropped image boxes (Tensor): the adjusted bounding boxes in pt form labels (Tensor): the class labels for each bbox """ def __init__(self, randomsamplecrop_arg): self.sample_options = [] self.min_iou = randomsamplecrop_arg["min_iou"] for each in (self.min_iou) : if each == 1 : self.sample_options.append(None) else : self.sample_options.append((each,None)) self.sample_options = tuple(self.sample_options) self.min_crop_size = randomsamplecrop_arg["min_crop_size"] self.aspect_ratio_constraint = randomsamplecrop_arg["aspect_ratio_constraint"] if len(self.aspect_ratio_constraint) !=2 : raise TypeError("Aspect Ratio Constraint Should be only two number : max and min") def __call__(self, image, boxes=None, labels=None, difficulties=None): height, width, _ = image.shape while True: # randomly choose a mode mode = random.choice(self.sample_options) if mode is None: return image, boxes, labels, difficulties min_iou, max_iou = mode if min_iou is None: min_iou = float('-inf') if max_iou is None: max_iou = float('inf') # max trails (50) for _ in range(50): current_image = image w = random.uniform(self.min_crop_size * width, width) h = random.uniform(self.min_crop_size * height, height) # aspect ratio constraint b/t .5 & 2 if h / w < self.aspect_ratio_constraint[0] or h / w > self.aspect_ratio_constraint[1]: continue left = random.uniform(width - w) top = random.uniform(height - h) # convert to integer rect x1,y1,x2,y2 rect = np.array([int(left), int(top), int(left+w), int(top+h)]) # cut the crop from the image current_image = current_image[rect[1]:rect[3], rect[0]:rect[2], :] # calculate IoU (jaccard overlap) b/t the cropped and gt boxes overlap = jaccard_numpy(boxes, rect) # is min and max overlap constraint satisfied? if not try again if overlap.min() < min_iou and max_iou < overlap.max(): continue # keep overlap with gt box IF center in sampled patch centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0 # mask in all gt boxes that above and to the left of centers m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1]) # mask in all gt boxes that under and to the right of centers m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1]) # mask in that both m1 and m2 are true mask = m1 * m2 # have any valid boxes? try again if not if not mask.any(): continue # take only matching gt boxes current_boxes = boxes[mask, :].copy() # take only matching gt labels current_labels = labels[mask] # take difficult current_difficulties = difficulties[mask] # should we use the box left and top corner or the crop's current_boxes[:, :2] = np.maximum(current_boxes[:, :2], rect[:2]) # adjust to crop (by substracting crop's left,top) current_boxes[:, :2] -= rect[:2] current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:], rect[2:]) # adjust to crop (by substracting crop's left,top) current_boxes[:, 2:] -= rect[:2] return current_image, current_boxes, current_labels, current_difficulties # ============================= # main of augmentation class Augmentation(object): def __init__(self, augmentation_config, spilt) : self.mean = augmentation_config["mean"] self.std = augmentation_config["std"] self.normalize_mean = augmentation_config["normalize"]["mean"] self.normalize_std = augmentation_config["normalize"]["std"] self.image_resize = augmentation_config["image_resize"] self.photometricdistort_arg = augmentation_config["extra_augment"]["PhotometricDistort"] self.randomsamplecrop_arg = augmentation_config["extra_augment"]["RandomSampleCrop"] self.spilt = spilt assert self.spilt in {'TRAIN', 'TEST'} if self.spilt == "TRAIN" : self.augment = [ # 如果增加 expand / random_sample_crop 的話要注意 data type (Image / Tensor / Numpy) # 那兩個沒事別亂做啊! PhotometricDistort(self.photometricdistort_arg), # Expand(self.mean), # RandomSampleCrop(self.randomsamplecrop_arg), RandomMirror(), Resize(self.image_resize), # include transfer to relative cooridinate ToTensor(), Normalize(self.normalize_mean,self.normalize_std) ] else : self.augment = [ Resize(self.image_resize), ToTensor(), Normalize(self.normalize_mean,self.normalize_std) ] def __call__(self, img, boxes=None, labels=None, difficulties=None): new_image = img new_boxes = boxes new_labels = labels new_difficulties = difficulties # if self.spilt == "TEST" : # new_boxes = new_boxes.numpy() for each_aug in self.augment : new_image, new_boxes, new_labels, new_difficulties = each_aug(new_image, new_boxes, new_labels, new_difficulties) return new_image, new_boxes, new_labels, new_difficulties
#coding=utf-8 def produce_entity_index(entity2idPath,DB_id_index_Path,allDBIdexPath): idMap=dict() with open(entity2idPath,encoding='utf-8') as f: line=f.readline().strip('\n') while line: id=line.split(' ')[0][3:] index=int(line.split(' ')[1]) # print(id) # print(index+1) idMap[id]=index+1 line=f.readline().strip('\n') dbf=open(allDBIdexPath,'w',encoding='utf-8') with open(DB_id_index_Path,encoding='utf-8') as f: line=f.readline().strip('\n').strip(' ') lineCount=0 totalCount=0 nolinkCount=0 while line: lineCount=lineCount+1 Ids=line.split(' ') tempStr=Ids[0] if(len(Ids)==1): tempStr=tempStr+' '+str(idMap[Ids[0]]) dbf.write(tempStr+'\n') dbf.write(tempStr+'\n') nolinkCount=nolinkCount+1 else: for i in range(len(Ids)): if(Ids[i]!='E0006472' and Ids[i]!='E0186505' and Ids[i]!='E0532473'): totalCount = totalCount + 1 tempStr=tempStr+' '+str(idMap[Ids[i]]) dbf.write(tempStr.strip(' ') + '\n') dbf.write(Ids[0]+' '+str(idMap[Ids[0]])+'\n') print(tempStr) line=f.readline().strip('\n').strip(' ') print('average link='+str(int(totalCount/lineCount))) print(nolinkCount) pass if __name__=='__main__': # entity2idPath='E:\mypython_Linking\CNN\entityId.txt' # DB_id_index_Path='E:\mypython_Linking\CNN\min_DB_id_index.txt' # allDBIdexPath = 'E:\mypython_Linking\CNN\min_DBIndex.txt' # produce_entity_index(entity2idPath,DB_id_index_Path,allDBIdexPath) ###############bu no link entity############## entity2idPath = 'E:\mypython_Linking\CNN\entityId_bu.txt' DB_id_index_Path = 'E:\mypython_Linking\CNN\min_DB_id_index_bu.txt' allDBIdexPath = 'E:\mypython_Linking\CNN\min_DBIndex_bu.txt'####生成新文件 produce_entity_index(entity2idPath, DB_id_index_Path, allDBIdexPath) pass
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import psycopg2 class Pipeline1(object): def __init__(self): # db_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # self.db = sqlite3.connect(db_path + "/db.sqlite3") self.conn = psycopg2.connect("dbname = test user = postgres") def process_item(self, item, spider): # print "*****************process items****************" # print item['title'] # print item['link'] # print item['time'] # print item['source'] # print item['desc'] cu = self.conn.cursor() cu.execute("insert into interviews_items values(" "'" + item['title'] + "', '" + item['link'] + "', '" + item['time'] + "', '" + item['source'] + "', '" + item['desc'] + "', '" + item['tag'] + "')") self.conn.commit() cu.close() return item
from jenkspy import jenks_breaks from Tools.Encoders.Encoder import Encoder from numpy.random import RandomState from typing import List import numpy as np class NaturalSplineEncoding(Encoder): """ Natural Spline Encoding encodes every feature individually as piecewise cubic spline with the following requirements: - The first and last splines are linear splines. - The cubic splines are continuous, differentiable and smooth everywhere. See https://en.wikipedia.org/wiki/Spline_(mathematics) and Section 2.4.5 of the book 'Regression Modeling Strategies' for more information. """ def __init__(self, num_curves: List[int]): """ Constructor of the Natural Spline Encoding. Arguments: num_curves (List[int]): How many polynomials per feature should be used to encode the natural spline. """ self.num_curves = num_curves def fit(self, X: np.array): self.__determine_knots(X) def transform(self, X: np.array) -> np.array: rows = [] for row in X: features = [] for x, knot in zip(row, self.knots.T): features.extend(self.__single_natural_spline_encoding(x, knot)) rows.append(features) return np.array(rows) def __determine_knots(self, X: np.array): """ Determine the locations of the knots for every feature using Jenks Natural Breaks. Arguments: X (np.array): The train input used to determine the location of the knots. """ self.knots = [] for column, num_curves in zip(X.T, self.num_curves): breaks = jenks_breaks(column, nb_class = num_curves) self.knots.append(breaks) self.knots = np.array(self.knots).T @classmethod def __single_natural_spline_encoding(self, x: float, knots: List[float]) -> List[float]: """ Compute the spline encoding for a single value. Arguments: x (float): The value on which a spline encoding is applied. knots (List[float]): The locations where the knots are placed. Returns: The spline encoding of this value. """ return [x] + [self.__feature_encoding(x, i, knots) for i in range(len(knots) - 2)] @classmethod def __feature_encoding(self, x: float, i: int, knots: List[float]) -> float: """ Compute the value of X_{i + 1} as defined in Section 2.4.5 of the book 'Regression Modeling Strategies'. Arguments: x (float): The value on which a spline encoding is applied. i (int): The index i which corresponds to the X_{i + 1} we want to compute. knots (List[float]): The locations where the knots are placed. Returns: The value of X_{i + 1}. """ return self.__ramp(x - knots[i]) ** 3 - self.__ramp(x - knots[-2]) ** 3 * (knots[-1] - knots[i]) / \ (knots[-1] - knots[-2]) + self.__ramp(x - knots[-1]) ** 3 * (knots[-2] - knots[i]) / (knots[-1] - knots[-2]) @staticmethod def __ramp(x: float): """ The ramp function (also known as the ReLu function). Arguments: x (float): The value of on which the ramp function is applied. Returns: The outcome of the ramp function. """ return max(x, 0)
import numpy as np import json import os from keyvalue import STORE from util import quickhash from run import run_deeprole def proposal_to_bitstring(proposal): result = 0 for p in proposal: result |= (1 << p) assert result < 32 return result def bitstring_to_proposal(bitstring): result = () i = 0 for i in range(5): if ((1 << i) & bitstring) != 0: result = result + (i, ) assert len(result) in [2, 3] return result def get_start_node(session_info): return { "type": "TERMINAL_PROPOSE_NN", "succeeds": 0, "fails": 0, "propose_count": 0, "proposer": session_info['starting_proposer'], "new_belief": list(np.ones(60)/60.0) } def terminal_propose_to_node_key(terminal_propose_node): assert terminal_propose_node['type'] == 'TERMINAL_PROPOSE_NN' return "node:" + quickhash({ 'succeeds': terminal_propose_node['succeeds'], 'fails': terminal_propose_node['fails'], 'propose_count': terminal_propose_node['propose_count'], 'proposer': terminal_propose_node['proposer'], 'belief': terminal_propose_node['new_belief'] }) def node_is_caught_up(node, game_info): phase = game_info['phase'] if node['type'] == 'TERMINAL_PROPOSE_NN': return False if node['type'].startswith('TERMINAL_'): return True if node['succeeds'] + node['fails'] + 1 < game_info['missionNum']: return False if node['type'] == 'PROPOSE': if phase != 'pickingTeam': return False return node['proposer'] == game_info['teamLeaderReversed'] elif node['type'] == 'VOTE': if phase != 'votingTeam': return False return node['proposer'] == game_info['teamLeaderReversed'] elif node['type'] == 'MISSION': return phase == 'votingMission' def replay_game_and_run_deeprole(session_info, game_info): current_node = get_start_node(session_info) updated_session = False while not node_is_caught_up(current_node, game_info): round_ = current_node['succeeds'] + current_node['fails'] if current_node['type'] == 'TERMINAL_PROPOSE_NN': next_node_key = terminal_propose_to_node_key(current_node) if not STORE.exists(next_node_key): current_node = run_deeprole(current_node) STORE.set(next_node_key, current_node) else: current_node = STORE.get(next_node_key) if next_node_key not in session_info['nodes_in_use']: session_info['nodes_in_use'].append(next_node_key) STORE.refcount_incr(next_node_key) updated_session = True elif current_node['type'] == 'PROPOSE': propose_count = current_node['propose_count'] leader = None proposal = [] for index, name in enumerate(session_info['players']): info = game_info['voteHistory'][name][round_][propose_count] if 'VHpicked' in info: proposal.append(index) if 'VHleader' in info: assert leader is None leader = index assert leader == current_node['proposer'] child_index = current_node['propose_options'].index(proposal_to_bitstring(proposal)) current_node = current_node['children'][child_index] elif current_node['type'] == 'VOTE': propose_count = current_node['propose_count'] proposal = bitstring_to_proposal(current_node['proposal']) for player in proposal: name = session_info['players'][player] assert 'VHpicked' in game_info['voteHistory'][name][round_][propose_count] leader_name = session_info['players'][current_node['proposer']] assert 'VHleader' in game_info['voteHistory'][leader_name][round_][propose_count] up_voters = [] for index, name in enumerate(session_info['players']): info = game_info['voteHistory'][name][round_][propose_count] if 'VHapprove' in info: up_voters.append(index) child_index = proposal_to_bitstring(up_voters) assert 0 <= child_index < 32 current_node = current_node['children'][child_index] elif current_node['type'] == 'MISSION': fails = game_info['numFailsHistory'][round_] current_node = current_node['children'][fails] if updated_session: STORE.set(session_info['session_id'], session_info) return current_node print(json.dumps(game_info, indent=2, sort_keys=2)) def get_move(phase, session_info, node): player = session_info['player'] perspective = session_info['perspective'] if phase == 'pickingTeam': assert node['type'] == 'PROPOSE' propose_strategy = node['propose_strat'][perspective] propose_options = node['propose_options'] index = np.random.choice(len(propose_strategy), p=propose_strategy) players = bitstring_to_proposal(propose_options[index]) return { 'buttonPressed': 'yes', 'selectedPlayers': [session_info['players'][p] for p in players] } elif phase == 'votingTeam': assert node['type'] == 'VOTE' vote_strategy = node['vote_strat'][player][perspective] vote_up = bool(np.random.choice(len(vote_strategy), p=vote_strategy)) return { 'buttonPressed': 'yes' if vote_up else 'no' } elif phase == 'votingMission': assert node['type'] == 'MISSION' if perspective < 7: return { 'buttonPressed': 'yes' } mission_strategy = node['mission_strat'][player][perspective] fail_mission = bool(np.random.choice(len(mission_strategy), p=mission_strategy)) return { 'buttonPressed': 'no' if fail_mission else 'yes' } elif phase == 'assassination': assert node['type'] == 'TERMINAL_MERLIN' merlin_strat = node['merlin_strat'][player][perspective] p = np.random.choice(len(merlin_strat), p=merlin_strat) return { 'buttonPressed': 'yes', 'selectedPlayers': [ session_info['players'][p] ] } else: assert False, "Can't handle this case"
from bigml.api import BigML api = BigML() source1 = api.create_source("iris.csv") api.ok(source1) dataset1 = api.create_dataset(source1, \ {'name': u'iris'}) api.ok(dataset1) cluster1 = api.create_cluster(dataset1, \ {'name': u'iris'}) api.ok(cluster1) centroid1 = api.create_centroid(cluster1, \ {u'petal length': 0.5, u'petal width': 0.5, u'sepal length': 1, u'sepal width': 1, u'species': u'Iris-setosa'}, \ {'name': u'my_centroid_name'}) api.ok(centroid1)
first = 'Ben' last = 'Wollen' message = first + ' [' + last + '] is a coder' print(message) msg = f'{first} [{last}] is a coder' print(msg)
""" cnet.py (see network) Check to see if you are connected to the internet and make sure your ip address is in the set ip_whitelist. (Originally designed for Linux Mint MATE v19.1.) """ import socket import subprocess import time import logging ip_whitelist = set() #ip_whitelist.add('') def internet(host = '8.8.8.8', port = 53, timeout = 3) -> bool: """ Check if I have an internet connection. Host: 8.8.8.8 (google-public-dns-a.google.com) OpenPort: 53/tcp Service: domain (DNS/TCP) """ try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) return True except socket.error as ex: logger.error(ex) return False def my_public_ip(): """ Get my public IP using ifconfig. If unable, then return 0.0.0.0. When you call subprocess.check_output, it prints stuff to term. If you use shell=True it will disable these logs, but for some reason it doesn't recognize the curl command. """ try: pipe_out = subprocess.check_output('curl ifconfig.me'.split(), timeout=5) return pipe_out.decode('utf8') except Exception as e: logger.error("Failed to determine public IP address.") logger.error(e) return "0.0.0.0" def restart_connection(): """ Restart network manager. Sleep for 5 seconds to give time for restart. """ cmd = 'sudo service network-manager restart' logger.info("Restarting network manager..."); logger.info(cmd) subprocess.call(cmd.split()) time.sleep(5) """ Set up logger """ log_format = '%(levelname)s %(asctime)s - %(message)s' logging.basicConfig(filename = '/home/ryan/Downloads/cnet.log', level = logging.DEBUG, format = log_format) logger = logging.getLogger() logger.info('~'*10 + ' cnet.py ' + '~'*10) """ Start checking connection """ status = 0 logger.info('Now ready to check the internet connection.') while True: if internet(): tries = 0 while tries < 3: my_ip = my_public_ip() tries += 1 if my_ip != "0.0.0.0": break if my_ip not in ip_whitelist: logger.warning("IP address not recognized. Attempting a restart.") restart_connection() else: status = 0 else: if status == 0: status = 1 logger.error("Unable to connect...") time.sleep(1) logger.error("Trying again...") elif status == 1: status = 2 logging.error("Failed to connect twice. Attempting a restart.") restart_connection() else: status = 0 logging.critical("Failed to connect three times.") logging.critical("Waiting 30 seconds and starting over...") time.sleep(30)
# # [794] Swim in Rising Water # # https://leetcode.com/problems/swim-in-rising-water/description/ # # algorithms # Hard (44.29%) # Total Accepted: 3.1K # Total Submissions: 6.9K # Testcase Example: '[[0,2],[1,3]]' # # On an N x N grid, each square grid[i][j] represents the elevation at that # point (i,j). # # Now rain starts to fall. At time t, the depth of the water everywhere is t. # You can swim from a square to another 4-directionally adjacent square if and # only if the elevation of both squares individually are at most t. You can # swim infinite distance in zero time. Of course, you must stay within the # boundaries of the grid during your swim. # # You start at the top left square (0, 0). What is the least time until you can # reach the bottom right square (N-1, N-1)? # # Example 1: # # # Input: [[0,2],[1,3]] # Output: 3 # Explanation: # At time 0, you are in grid location (0, 0). # You cannot go anywhere else because 4-directionally adjacent neighbors have a # higher elevation than t = 0. # # You cannot reach point (1, 1) until time 3. # When the depth of water is 3, we can swim anywhere inside the grid. # # # Example 2: # # # Input: # [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] # Output: 16 # Explanation: # ⁠0 1 2 3 4 # 24 23 22 21 5 # 12 13 14 15 16 # 11 17 18 19 20 # 10 9 8 7 6 # # The final route is marked in bold. # We need to wait until time 16 so that (0, 0) and (4, 4) are connected. # # # Note: # # # 2 <= N <= 50. # grid[i][j] is a permutation of [0, ..., N*N - 1]. # # from heapq import * class Solution(object): def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ # init pq = [] visited = set() N = len(grid) # start point pq.append([grid[0][0],0,0]) visited.add((0,0)) res = 0 while pq: point, row, col = heappop(pq) res = max(res, point) # check if row == col == N- 1: return res for i, j in ((row-1, col), (row+1, col), (row, col-1), (row, col+1)): # boundary if 0 <= i < N and 0 <= j < N and (i,j) not in visited: heappush(pq,(grid[i][j],i,j)) visited.add((i,j))
# coding:utf-8 import html_downloader, position_outputer, positionInfo_parser position = positionInfo_parser.PositionInfo_Parser().parse("http://campus.chinahr.com/job/120396.html", "company_test_uuid") # 职位所属公司uuid print "company_uuid:" + position.company_uuid # 职位url print "url:" + position.url # 职位名称 print "name:" + position.name # 职位类别(全职/实习) print "requirement:" + position.requirement # 职位部门 print "department:" + position.department # 工作地区(确定到市级) print "city:" + position.city # 工作详细地点 print "detailPosition:" + position.detailPosition # 招聘人数 print "personNum:" + position.personNum # 职位发布时间 print "publish_time:" + position.publish_time # 职位有效日期(起始日期) print "validStartDate:" + position.validStartDate # 职位有效日期(截止日期) print "validEndDate:" + position.validEndDate # 职位薪资 print "salary:" + position.salary # 职位学历要求 print "degree:" + position.degree # 职位英语等级要求 print "english_require:" + position.english_require # 职位性别要求 print "sex:" + position.sex # 职位最小年纪要求 print "startAge:" + position.startAge # 职位最大年纪要求 print "endAge:" + position.endAge # 职位描述 print "desc:" + position.desc outer = position_outputer.PositionOutputer() outer.collect_data(position) outer.output_txt()
from abc import abstractmethod class CoinHandlerBase: def __init__(self): _successor = CoinHandlerBase() self._successor = _successor @abstractmethod def handle_coin(self, coin): pass def set_successor(self, successor): self._successor = successor
import random deck_of_cards = [i for i in range(2,11) for num in range(4)] loser_deck = [] #random.seed(42) random.shuffle(deck_of_cards) player1_cards = [card for index, card in enumerate(deck_of_cards) if index % 2 == 0] player2_cards = [card for index, card in enumerate(deck_of_cards) if index % 2 == 1] print(player1_cards, 'P1 cards') print(player2_cards, 'P2 cards') print('') while len(player1_cards) > 0 and len(player2_cards) > 0: print('Player 1 drew -> {}'.format(player1_cards[0])) print('Player 2 drew -> {}'.format(player2_cards[0])) if player1_cards[0] > player2_cards[0]: loser_deck.append(player1_cards[0]) loser_deck.append(player2_cards[0]) for i in loser_deck: player2_cards.append(i) del player1_cards[0] del player2_cards[0] #print(loser_deck, 'loser deck') loser_deck = [] print('Player 1 won the round!') elif player2_cards[0] > player1_cards[0]: loser_deck.append(player2_cards[0]) loser_deck.append(player1_cards[0]) for i in loser_deck: player1_cards.append(i) del player2_cards[0] del player1_cards[0] #print(loser_deck, 'loser deck') loser_deck = [] print('Player 2 won the round!') elif player1_cards[0] == player2_cards[0]: loser_deck.append(player1_cards[0]) loser_deck.append(player2_cards[0]) del player1_cards[0] del player2_cards[0] #print(loser_deck, 'loser deck') if len(player1_cards) == 0: print('') print("Player 1 won the game!") elif len(player2_cards) == 0: print('') print("Player 2 won the game!")
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Fixed Value Comparator.""" import warnings import numpy as np from qiskit.circuit.library import IntegerComparator from qiskit.aqua.utils.circuit_factory import CircuitFactory class FixedValueComparator(CircuitFactory): r"""*DEPRECATED.* Fixed Value Comparator .. deprecated:: 0.7.0 Use Terra's qiskit.circuit.library.IntegerComparator instead. Operator compares basis states \|i>_n against a classically given fixed value L and flips a target qubit if i >= L (or < depending on parameters): \|i>_n\|0> --> \|i>_n\|1> if i >= L else \|i>\|0> Operator is based on two's complement implementation of binary subtraction but only uses carry bits and no actual result bits. If the most significant carry bit (= results bit) is 1, the ">=" condition is True otherwise it is False. """ def __init__(self, num_state_qubits, value, geq=True, i_state=None, i_target=None): """ Args: num_state_qubits (int): number of state qubits, the target qubit comes on top of this value (int): fixed value to compare with geq (Optional(bool)): evaluate ">=" condition of "<" condition i_state (Optional(Union(list, numpy.ndarray))): indices of state qubits in given list of qubits / register, if None, i_state = list(range(num_state_qubits)) is used i_target (Optional(int)): index of target qubit in given list of qubits / register, if None, i_target = num_state_qubits is used """ warnings.warn('The qiskit.aqua.circuits.FixedValueComparator object is deprecated and will ' 'be removed no earlier than 3 months after the 0.7.0 release of Qiskit Aqua. ' 'You should use qiskit.circuit.library.IntegerComparator instead.', DeprecationWarning, stacklevel=2) super().__init__(num_state_qubits + 1) self._comparator_circuit = IntegerComparator(value=value, num_state_qubits=num_state_qubits, geq=geq) self.i_state = None if i_state is not None: self.i_state = i_state else: self.i_state = range(num_state_qubits) self.i_target = None if i_target is not None: self.i_target = i_target else: self.i_target = num_state_qubits @property def num_state_qubits(self): """ returns num state qubits """ return self._comparator_circuit._num_state_qubits @property def value(self): """ returns value """ return self._comparator_circuit._value def required_ancillas(self): return self.num_state_qubits - 1 def required_ancillas_controlled(self): return self.num_state_qubits - 1 def _get_twos_complement(self): """Returns the 2's complement of value as array Returns: list: two's complement """ twos_complement = pow(2, self.num_state_qubits) - int(np.ceil(self.value)) twos_complement = '{0:b}'.format(twos_complement).rjust(self.num_state_qubits, '0') twos_complement = \ [1 if twos_complement[i] == '1' else 0 for i in reversed(range(len(twos_complement)))] return twos_complement def build(self, qc, q, q_ancillas=None, params=None): instr = self._comparator_circuit.to_instruction() qr = [q[i] for i in self.i_state] + [q[self.i_target]] if q_ancillas: # pylint:disable=unnecessary-comprehension qr += [qi for qi in q_ancillas[:self.required_ancillas()]] qc.append(instr, qr)
# Import libraries import numpy as np from flask import Flask, request, jsonify from deeppavlov import build_model, configs app = Flask(__name__) # Load the model model = build_model(configs.squad.squad, download=False) @app.route('/ques',methods=['POST']) def predict(): # Get the data from the POST request. data = request.get_json(force=True) # Make prediction using model loaded from disk as per the data. print(data['passage']) print(data['question']) prediction = model([data['passage']],[data['question']]) answer={} answer['result']=prediction[0] answer['starting'] = prediction[1] answer['logitvalue'] = prediction[2] # Take the first value of prediction return jsonify(answer) if __name__ == '__main__': app.run(port=5000, debug=True)
# This file is a part of pyctr. # # Copyright (c) 2017-2021 Ian Burgwin # This file is licensed under The MIT License (MIT). # You can find the full license text in LICENSE in the root of this project. from functools import wraps from typing import TYPE_CHECKING, NamedTuple from ....common import PyCTRError from ....util import readle, roundup if TYPE_CHECKING: from typing import BinaryIO class PartitionDescriptorError(PyCTRError): """Generic error for operations related to DIFI, IVFC, or DPFS.""" class InvalidHeaderError(PartitionDescriptorError): """The header is invalid.""" class InvalidHeaderLengthError(InvalidHeaderError): """Length of the header is invalid.""" class LevelData(NamedTuple): """Level data used by IVFC and DPFS.""" offset: int """Offset of the level.""" size: int """Size of the final level.""" block_size_log2: int """Block size in log2.""" block_size: int """Actual block size.""" def get_block_range(offset: int, size: int, block_size: int): starting_block = (roundup(offset - block_size + 1, block_size)) // block_size ending_block = max(((roundup(offset + size, block_size)) // block_size) - 1, starting_block) return starting_block, ending_block def read_le_u32_array(data: bytes): """Yields each little-endian u32 in a block of data.""" for o in range(0, len(data), 4): yield readle(data[o:o+4]) def _raise_if_level_closed(method): @wraps(method) def decorator(self: 'BinaryIO', *args, **kwargs): if self.closed: raise ValueError('I/O operation on closed file') return method(self, *args, **kwargs) return decorator
import requests import sys import shutil, os from django.shortcuts import render from subprocess import run,PIPE from django.core.files.storage import FileSystemStorage from cv2 import cv2 def button(request): return render(request,'index.html') def external(request): image = request.FILES['image'] print(image) fs=FileSystemStorage() filename=fs.save(image.name,image) fileurl=fs.open(filename) templateurl=fs.url(filename) print("rawurl",filename) print("fullurl",fileurl) print("tempurl",templateurl) image = run([sys.executable,'//project//project//scr.py',str(fileurl),str(filename)],shell=False,stdout=PIPE) print(image.stdout) stri=str(image.stdout, 'utf-8') shutil.copy('//project//project//media//temp.png', 'C://Users//saipr//Desktop//project//project//static//media') return render(request,'index.html',{'raw_url':templateurl,'edit_url':stri}) def take_picture(request): if request.method == 'POST': image = run([sys.executable,'//project//project//take.py'],shell=False,stdout=PIPE) print(image.stdout) stri=str(image.stdout, 'utf-8') print(stri) shutil.copy('//project//project//media//temp.png', '//project//project//static//media') return render(request,'index.html',{'edit_url':stri})
from django.contrib import admin from cars.models import Car, SoldCar class CarAdmin(admin.ModelAdmin): date_hierarchy='end_time' search_fields=['plate','brand'] list_display = ['id', 'plate', 'brand','end_time' ] admin.site.register(Car, CarAdmin) admin.site.register(SoldCar ,CarAdmin)
class foo(): '''填写描述''' def set(self): pass print(foo().__doc__) a = iter([1,2,3,4,5,6,7]) for i in range(5): print(next(a))
import hashlib import json import scrapy from kingfisher_scrapy.base_spider import ZipSpider class Portugal(ZipSpider): name = 'portugal' download_warnsize = 0 download_timeout = 9999 def start_requests(self): url = 'https://dados.gov.pt/api/1/datasets/?q=ocds&organization={}&page_size={}' id = '5ae97fa2c8d8c915d5faa3bf' page_size = 20 yield scrapy.Request( url.format(id, page_size), callback=self.parse_list ) def parse_list(self, response): if response.status == 200: datas = json.loads(response.text) for data in datas['data']: for resource in data['resources']: description = resource['description'] url = resource['url'] if description.count("OCDS") or description.count("ocds"): yield scrapy.Request( url, meta={'kf_filename': hashlib.md5(url.encode('utf-8')).hexdigest() + '.json'} ) if self.sample: break else: yield self.build_file_error_from_response(response, filename='list.json') def parse(self, response): yield from self.parse_zipfile(response, data_type='record_package', file_format='json_lines', encoding='iso-8859-1')
#Implement integer exponentiation. That is, implement the pow(x, y) function, #where x and y are integers and returns x^y. #Do this faster than the naive method of repeated multiplication. #For example, pow(2, 10) should return 1024. import sys sys.setrecursionlimit(1500) def power(base, exp): if exp == 0: return 1 if exp == 1: return base if exp == -1: return 1/base if exp % 2 == 0: return pow(base,exp/2) * pow(base,exp/2) else: return base * pow(base,(exp-1)/2) * pow(base,(exp-1)/2) res = power(2,2) print(res)
#!/usr/bin/python2 '''Run all the tests''' import sys import os if len(sys.argv) > 1: sys.path.insert(0, sys.argv[1]) else: BASE = os.path.abspath(__file__) DIR = os.path.dirname(BASE) TARGET = os.path.join(DIR, '..', 'src') CLEAN = os.path.abspath(TARGET) assert(os.path.isdir(CLEAN)) sys.path.insert(0, CLEAN) import unittest from test_pathwatch import * unittest.main()
lista = ['a','b','c','d','e','f'] lista_n = [1,2,3,4,5,6] lista_cap = [1,2,3,2,1] lista_lista = [[1,2,3],[4,5],[6,7,8,9]] #e1 def comprimento(lst): if lst == []: return 0 return 1 + comprimento(lst[1:]) print(f"O comprimento da lista é {comprimento(lista)}") #e2 def soma(lst): if lst == []: return 0 return lst[0] + soma(lst[1:]) print(f"A soma é {soma(lista_n)}") #e3 def check(lst,elem): if lst == []: return False return lst[0] == elem or check(lst[1:],elem) print(f"4 está na lista : {check(lista_n,4)}") #4 def concatenar(l1,l2): if l1 == []: return l2[:] rec = concatenar(l1[1:],l2) rec[:0] = l1[:1] return rec print(concatenar(lista,lista_n)) #5 def reverse(lst): if lst == []: return lst return lst[-1:] + reverse(lst[:-1]) print(reverse(lista)) #6 def capicua(lst): if lst[0] != lst[-1]: return False if len(lst) < 2: return True return capicua(lst[1:-1]) print(capicua(lista)) print(capicua(lista_cap)) #7 def list_list(lst)
from utils import * import os import tensorflow as tf import tensorflow_addons as tfa os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices' BUFFER_SIZE = 1000 BATCH_SIZE = 100 VOCAB_SIZE = 10000 def run(df, epochs, N_CLASS, metric, fold): # separate train and test train_dataset = df[df["kfold"] != fold].reset_index(drop=True) test_dataset = df[df["kfold"] == fold].reset_index(drop=True) x_train = train_dataset.drop(["kfold", "category"], axis=1).values x_test = test_dataset.drop(["kfold", "category"], axis=1).values # one hot the target variable y_train = tf.one_hot(train_dataset.category.values, N_CLASS) y_test = tf.one_hot(test_dataset.category.values, N_CLASS) # make tf compatible dataset train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)) test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)) train_dataset = train_dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE) test_dataset = test_dataset.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE) # Start model encoder = tf.keras.layers.experimental.preprocessing.TextVectorization( max_tokens=VOCAB_SIZE) encoder.adapt(train_dataset.map(lambda text, label: text)) # embedding + 1 * bidirectional LSTM(64) + Dense(64) + Dense output model = tf.keras.Sequential([ encoder, tf.keras.layers.Embedding( input_dim=len(encoder.get_vocabulary()), output_dim=2000, mask_zero=True), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(512)), # return_sequences=True)), # tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256)), # tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.1), tf.keras.layers.Dense(N_CLASS) ]) model.compile(loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(1e-4), metrics=[metric]) history = model.fit(train_dataset, epochs=epochs, validation_data=test_dataset) # , validation_steps=30) def main(): # import data df = pd.read_csv(f"/content/drive/MyDrive/MIDAS/data/text.csv") df.drop(["image"], axis=1, inplace=True) # Lable Encoding the target variable enc = preprocessing.LabelEncoder() df["category"] = enc.fit_transform(df["category"]) # defining the metric N_CLASS = len(df["category"].unique()) metric = tfa.metrics.F1Score(num_classes=N_CLASS, average="micro") print("N_CLASS:", N_CLASS) for fold in range(5): run(df=df, epochs=10, N_CLASS=N_CLASS, metric=metric, fold=fold) if __name__ == "__main__": main()
''' Header Name: mm_sh_toolset.py Created by: Matt Malley E-mail: contact@radiant-entertainment.com How to Run in Maya: Copy/Paste this into Maya (or create as a button): import maya.cmds as cmds cmds.unloadPlugin("mm_sh_toolset.py") cmds.loadPlugin("mm_sh_toolset.py") cmds.mm_sh_toolset() Project Description: This script is to assist in asset creation. Final Toolset: There are multiple tabs: Modeling, Organization, UV Tools, Rigging, and SH Unique functions. Each has a variety of useful buttons which fit their tab's description. ''' __authors__ = "Matt Malley" ###################################### ############# IMPORTS ################ ###################################### #------------------------------------------------------------------------------- #Imports Maya command information import maya.cmds as cmds import maya.mel as mel import maya.OpenMaya as om import os import sys import maya.OpenMayaMPx as OpenMayaMPx #------------------------------------------------------------------------------- #Import all individual scripts import mmAddAttr as mmAA import mmConvert3DSMaxRigToMayaRig as mmCM2M import mmCreateLocAndParent as mmCLAP import mmExportAnimationAsJson as mmEAAJ import mmExportSkeletonAsJson as mmESAJ import mmGetWorldTrans as mmGWT import mmScaleDownFrom3DSMax as mmSDF3M import mmModelingFunctions as mmMF import mmOrganizationFunctions as mmOF import mmOverrideVisual as mmOV import mmReplaceMeshWithObj as mmRMWO import mmReturnFilepathOrFilename as mmRFOF import mmRiggingFunctions as mmRF import mmSelectAnimatingParts as mmSAP import mmTransferAnimToDifferentRig as mmTATDR import mmTransferAnimToReferencedRig as mmTATRR import mmUVFunctions as mmUVF import mmBubbleSoft as mmBS import mmMassConversionFunctions as mmMCF import mmSpaceMatcher as mmSM import mmValueSwapper as mmVS reload( mmAA ) reload( mmCM2M ) reload( mmCLAP ) reload( mmEAAJ ) reload( mmESAJ ) reload( mmGWT ) reload( mmSDF3M ) reload( mmMF ) reload( mmOF ) reload( mmOV ) reload( mmRMWO ) reload( mmRFOF ) reload( mmRF ) reload( mmSAP ) reload( mmTATDR ) reload( mmTATRR ) reload( mmUVF ) reload( mmBS ) reload( mmMCF ) reload( mmSM ) reload( mmVS ) ###################################### ############# CLASSES ################ ###################################### mmPluginCmdName = "mm_sh_toolset" # Command class mmScriptedCommand(OpenMayaMPx.MPxCommand): def __init__(self): OpenMayaMPx.MPxCommand.__init__(self) # Invoked when the command is run. def doIt(self,argList): gui() ###################################### ############# DEFINES ################ ###################################### # Creator def mmCreator(): return OpenMayaMPx.asMPxPtr( mmScriptedCommand() ) # Initialize the script plug-in def initializePlugin(mobject): mplugin = OpenMayaMPx.MFnPlugin(mobject) try: mplugin.registerCommand( mmPluginCmdName, mmCreator ) except: sys.stderr.write( "Failed to register command: %s\n" % mmPluginCmdName ) raise # Uninitialize the script plug-in def uninitializePlugin(mobject): mplugin = OpenMayaMPx.MFnPlugin(mobject) try: mplugin.deregisterCommand( mmPluginCmdName ) except: sys.stderr.write( "Failed to unregister command: %s\n" % mmPluginCmdName ) #------------------------------------------------------------------------------- #Function which creates and displays GUI def gui(): mmCompareList = 0 #Check to see if a window currently exists, and delete it if it does if (cmds.window("sh_toolset_window", exists=1)): cmds.deleteUI("sh_toolset_window") cmds.windowPref("sh_toolset_window", r=True) #Create window, and set top left corner cmds.window("sh_toolset_window", title = "Stonehearth Toolset", w = 400, h = 300, resizeToFitChildren = True) cmds.windowPref("sh_toolset_window", te = 0, le = 0) #Adds a Tab Functionality to the Main Window mmForm = cmds.formLayout("basicFormLayout") mmTabs = cmds.tabLayout("mmTabs", innerMarginWidth=5, innerMarginHeight=5, scr = 1, w = 500, h = 300, cc = setWinHeight) cmds.formLayout( mmForm, edit=True, attachForm=((mmTabs, 'top', 0), (mmTabs, 'left', 0), (mmTabs, 'bottom', 0), (mmTabs, 'right', 0)) ) #------------------------------------------------------------------------------- #Stonehearth Buttons #------------------------------------------------------------------------------- ''' #Creates a new rowColumn Layout for design purposes #This is a larger set up than needed, and inside it should be multiple smaller UI menus cmds.rowColumnLayout("orgLayout2", numberOfColumns = 3, cw= [[1,150],[2,150],[3,150]], cal = [1,"center"]) curWinHeight += cmds.rowColumnLayout("orgLayout2", q = 1, h = 1) ''' #Creates a base window height value to determine the Tab's required Height #Subsequent additions to this value are adding up to the total height required curWinHeight = 0 curWinHeightColumn1 = 0 curWinHeightColumn2a = 0 curWinHeightColumn2b = 0 #Creates a Collapsable Shelf to Hide/Show the items inside SH_FrLayout = cmds.columnLayout("SH_BasicFrame") curWinHeightColumn1 += cmds.columnLayout("SH_BasicFrame", q = 1, h = 1) curWinHeightColumn1 += 30 #Creates a new frame and rowColumn set for the Normal buttons and fields SH_RoCoLayout = cmds.frameLayout("SH_Buttons", label = "SH Buttons", cll = 1) curWinHeightColumn1 += cmds.frameLayout("SH_Buttons", q = 1, h = 1) curWinHeightColumn1 += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_Overall", numberOfColumns = 2, cw= [[1, 150], [2, 300]]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout_Overall", q = 1, h = 1) #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnOne", numberOfColumns = 1, cw= [1, 150]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnOne", q = 1, h = 1) #Creates a new frame and rowColumn set for the Normal buttons and fields SH_RoCoLayout = cmds.frameLayout("Animation_Scripts", label = "Anim Scripts", cll = 1) curWinHeightColumn1 += cmds.frameLayout("Animation_Scripts", q = 1, h = 1) curWinHeightColumn1 += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout", q = 1, h = 1) #Button: Calls function to set up the UI as I want cmds.button ( label = "Viewport Fix", command = mmCM2M.mmFixUI, w = 75, h = 25) #Button: Calls function to set any selected object to world location cmds.button ( label = "Set to World", command = mmGWT.main, w = 75, h = 25) curWinHeightColumn1 += 10 #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayoutB", numberOfColumns = 1, cw= [1,150]) #Button: Calls function to add visibility toggling to a rig specifically created in the way described in this file. cmds.button ( label = "Toggle Vis of Self", command = mmCM2M.mmToggleVisOptionOnSelf, w = 75, h = 25) #Button: Calls function to add visibility toggling to a rig specifically created in the way described in this file. cmds.button ( label = "Toggle Vis of Children", command = mmCM2M.mmToggleVisOptionOnChildren, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") cmds.separator( height=10, style='in' ) curWinHeightColumn1 += 10 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout2Title", numberOfColumns = 1, cw= [1,150]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout2Title", q = 1, h = 1) cmds.text("Animation Scripts") curWinHeightColumn1 += 50 #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout2", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout2", q = 1, h = 1) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Export Anim", command = mmEAAJ.mainCall, w = 75, h = 25) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Export Skele", command = mmESAJ.mainCall, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout2B", numberOfColumns = 1, cw= [1,150]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout2B", q = 1, h = 1) #Button: Calls function to Transfer Animation from a 3DSMax Rig onto a Referenced Rig cmds.button ( label = "XFER Anim to Referenced Rig", command = mmTATRR.main, w = 150, h = 25) #Button: Calls function to Transfer Animation from a 3DSMax Rig onto a Different Rig cmds.button ( label = "XFER Anim to Different Rig", command = mmTATDR.main, w = 150, h = 25) #Button: Calls function to load any references which are currently not loaded - can do the same thing in the Reference Editor, # This just saves some clicks. cmds.button ( label = "Load any non-loaded Refs", command = mmCM2M.mmLoadAllReferences, w = 150, h = 25) #Button: Calls function to load any references which are currently not loaded - can do the same thing in the Reference Editor, # This just saves some clicks. cmds.button ( label = "SpaceMatcher Copy", command = mmSM.mmCopySpace, w = 150, h = 25) #Button: Calls function to load any references which are currently not loaded - can do the same thing in the Reference Editor, # This just saves some clicks. cmds.button ( label = "SpaceMatcher Paste", command = mmSM.mmPasteSpace, w = 150, h = 25) ############## cmds.separator( height=10, style='in' ) curWinHeightColumn1 += 10 cmds.text("Select two items then\nclick button to swap\ntheir values.") curWinHeightColumn1 += 50 #Creates a new rowColumn Layout for a value swapper purposes cmds.rowColumnLayout("mm_SH_RoCoLayout2C", numberOfColumns = 6, cw= [[1,25],[2,25],[3,25],[4,25],[5,25],[6,25]]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout2C", q = 1, h = 1) #Buttons for translation swapping # This just saves some clicks. cmds.button ( label = "TX", command = mmVS.mmSwapTransX, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "TY", command = mmVS.mmSwapTransY, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "TZ", command = mmVS.mmSwapTransZ, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-TX", command = mmVS.mmNegativeTransX, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-TY", command = mmVS.mmNegativeTransY, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-TZ", command = mmVS.mmNegativeTransZ, w = 20, h = 25) #Buttons for rotation swapping # This just saves some clicks. cmds.button ( label = "RX", command = mmVS.mmSwapRotX, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "RY", command = mmVS.mmSwapRotY, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "RZ", command = mmVS.mmSwapRotZ, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-RX", command = mmVS.mmNegativeRotX, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-RY", command = mmVS.mmNegativeRotY, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-RZ", command = mmVS.mmNegativeRotZ, w = 20, h = 25) #Buttons for scale swapping # This just saves some clicks. cmds.button ( label = "SX", command = mmVS.mmSwapScaleX, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "SY", command = mmVS.mmSwapScaleY, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "SZ", command = mmVS.mmSwapScaleZ, w = 20, h = 25) cmds.button ( label = "-SX", command = mmVS.mmNegativeScaleX, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-SY", command = mmVS.mmNegativeScaleY, w = 20, h = 25) # This just saves some clicks. cmds.button ( label = "-SZ", command = mmVS.mmNegativeScaleZ, w = 20, h = 25) #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") cmds.separator( height=10, style='in' ) curWinHeightColumn1 += 10 #------------------------------------------------------------------------------- #Creates a new frame and rowColumn set for the Normal buttons and fields SH_RoCoLayout = cmds.frameLayout("Rigging_Scripts", label = "Rig Adjust Scripts", cll = 1) # Add "cl = 1" to have the collapsable windows start collapsed curWinHeightColumn1 += cmds.frameLayout("Rigging_Scripts", q = 1, h = 1) curWinHeightColumn1 += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout3", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout3", q = 1, h = 1) #Button: Calls function to Set the Visual Override of a piece of Geo to display properly. #-------This button is only needed in rare cicrumstances - this function will be called automatically # during the Rig Converter script. cmds.button ( label = "Vis Override", command = mmOV.run, w = 75, h = 25) #Button: Calls function to toggle geo for manipulation or to lock it as a reference. For most animations, should not be needed. cmds.button ( label = "Geo Lock Tog", command = mmCM2M.mmToggleGeoManipulation, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout3A", numberOfColumns = 1, cw= [1,150]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout3A", q = 1, h = 1) #Button: Calls function to create a Locator at the selected object's pivot and then parent the object to the loc cmds.button ( label = "Add Selected Mesh to Rig", command = mmCLAP.main, w = 150, h = 25) #Button: Calls function to create a Locator at the selected object's pivot and then parent the object to the loc cmds.button ( label = "Group Selection in Place", command = mmOF.mmCallGroupInPlace, w = 150, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn1 += 10 cmds.text("To add a View-Only item\nto main or offhand bone,\nfirst reference in meshes,\nselect bone, ref meshes,\nthen click add button.") curWinHeightColumn1 += 50 #Button: Calls function to load in a mesh as a referenced file. cmds.button ( label = "Select an Item to Reference", command = mmCM2M.mmCallBringInReference, w = 75, h = 25) #Button: Calls function take selection of bone and referenced meshes, and adds referenced meshes to the rig as view-only meshes, # with controls to only view one at a time. cmds.button ( label = "Add View-Only Helper to Rig", command = mmCM2M.mmAddItemToRig, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout3B", numberOfColumns = 1, cw= [1,150]) curWinHeightColumn1 += cmds.rowColumnLayout("mm_SH_RoCoLayout3B", q = 1, h = 1) cmds.separator( height=10, style='in' ) curWinHeightColumn1 += 10 cmds.text("Geo Modification") curWinHeightColumn1 += 50 #Button: Calls function to replace the mesh objects of a rig file with an obj pulled in from some location. cmds.button ( label = "Select OBJ to replace Meshes", command = mmRMWO.main, w = 75, h = 25) #Button: Calls function to create a Locator at the selected object's pivot and then parent the object to the loc cmds.button ( label = "Select OBJ to Load into Scene", command = mmCM2M.mmBringInObj, w = 75, h = 25) #Button: Calls function to create a Locator at the selected object's pivot and then parent the object to the loc cmds.button ( label = "Clean Selected Meshes", command = mmCM2M.mmCleanMesh, w = 75, h = 25) #Bubble soft will make all selected meshes look poofy cmds.button ( label = "BubbleSoft", command = mmBS.main, w = 75, h = 25) curWinHeightColumn1 += 10 #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") #------------------------------------------------------------------------------- #Creates a new frame and rowColumn set for the Normal buttons and fields SH_RoCoLayout = cmds.frameLayout("Rig_Creation_Scripts", label = "Rig Creation Scripts", cll = 1) curWinHeightColumn2a += cmds.frameLayout("Rig_Creation_Scripts", q = 1, h = 1) curWinHeightColumn2a += 30 #Button: Calls function to create a Locator at the selected object's pivot and then parent the object to the loc cmds.button ( label = "Select OBJ to Load into Scene", command = mmCM2M.mmBringInObj, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 #Column for setting up a file to be ready for the rig creators #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnTwoPreface", numberOfColumns = 2, cw= [[1, 150],[2, 150]]) cmds.text("When creating a new rig:\nrun Set Up Function (to right),\nthen move your pivots, and\narrange your hierarchy.") curWinHeightColumn2a += 50 #Button: Calls all Rig Creation Functions without extra input cmds.button ( label = "Set Up Scene for Rigging", command = mmCM2M.mmRigPrep, w = 75, h = 25) #Check Box Group to decide what should be included in Hand System cmds.checkBoxGrp("centerPivotsChkBox", numberOfCheckBoxes=1, label='Center Pivots?', label1='Center', v1 = 1, adj = 1, cw2 = [75,75], w = 150, cl2 = ["center","center"], vr =1) curWinHeight += 25 #Button: Calls all Rig Creation Functions without extra input cmds.button ( label = "Clean Mesh Names if Needed", command = mmCM2M.mmMeshNameFixer, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 cmds.text("At this point, be sure to add a COG icon if you want one.") curWinHeightColumn2a += 50 cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 cmds.text("When converting from Max to Maya, skip Set Up Function.") curWinHeightColumn2a += 50 cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 #Column for creating "Human" Rigs - so Male, Female, Goblin #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnTwoHolder", numberOfColumns = 2, cw= [[1, 150],[2, 150]]) curWinHeightColumn2a += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnTwoHolder", q = 1, h = 1) #Column for creating "Human" Rigs - so Male, Female, Goblin #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnTwo", numberOfColumns = 1, cw= [1, 150]) curWinHeightColumn2a += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnTwo", q = 1, h = 1) cmds.text("Human Rig Creator:") curWinHeightColumn2a += 50 cmds.text("Convert Rig from Max to Maya\nor Create a new Human Rig\nfrom an OBJ") curWinHeightColumn2a += 50 #Button: Calls all Rig Creation Functions without extra input cmds.button ( label = "Run All", command = mmCM2M.mmHumanRigRunAll, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 #### #Separating out the various steps #### #Can't figure out how to input various entries.. and doesn't matter atm, so skipping the step by step for now. cmds.text("Separating Out Steps:") curWinHeightColumn2a += 50 #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Step 1 - Prep", command = mmCM2M.mmHumanRigRunStep1, w = 75, h = 25) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.text("Select Left Foot,\nthen Left Toe,\nthen Click:") curWinHeightColumn2a += 50 cmds.button ( label = "Step 2 - Foot/Clav", command = mmCM2M.mmHumanRigRunStep2, w = 75, h = 25) #Button: Calls function to Transfer Animation from a 3DSMax Rig onto a Referenced Rig cmds.button ( label = "Step 3 - Place Rig", command = mmCM2M.mmHumanRigRunStep3, w = 75, h = 25) #Button: Calls function to Transfer Animation from a 3DSMax Rig onto a Referenced Rig cmds.button ( label = "Step 4 - Completion", command = mmCM2M.mmHumanRigRunStep4, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 #Button: Calls function to Attach standard view-only models to human rigs. # This is separated because you cannot undo the referencing in of models - which is important just from a rig creation standpoint (sanity). cmds.button ( label = "Load in Standard View Onlys", command = mmCM2M.mmLoadAllViewOnlyHelpersHumanRig, w = 75, h = 25) #Button: Calls function to add scale to a rig specifically created in the way described in this file. cmds.button ( label = "Add Scale to Rig", command = mmCM2M.mmAddScaleToRig, w = 75, h = 25) cmds.text("Remove VisLock\nso it can Toggle") curWinHeightColumn2a += 50 #Button: Calls function to add scale to a rig specifically created in the way described in this file. cmds.button ( label = "Remove Vis Lock", command = mmCM2M.mmRemoveVisLock, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2a += 10 #Button: Calls function to add scale to a rig specifically created in the way described in this file. cmds.button ( label = "Dissassemble Rig", command = mmCM2M.mmDissassembleRig, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") #------------------------------------------------------------------------------- #Column for creating all other rigs #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThree", numberOfColumns = 1, cw= [1, 150]) curWinHeightColumn2b += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThree", q = 1, h = 1) cmds.text("Generic Rig Creator:") #curWinHeight += 50 cmds.text("Convert Rig from Max to Maya\nor Create a new Generic Rig\nfrom an OBJ") #curWinHeight += 50 #Button: Calls all Rig Creation Functions without extra input cmds.button ( label = "Run All", command = mmCM2M.mmGenericRunAll, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2b += 10 #### #Separating out the various steps #### #Can't figure out how to input various entries.. and doesn't matter atm, so skipping the step by step for now. cmds.text("Separating Out Steps:") curWinHeightColumn2b += 50 #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Step 1 - Prep", command = mmCM2M.mmGenericRigRunStep1, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2b += 10 cmds.text("Optional Limb/Foot Creation") #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Create Trash Limb Locator", command = mmCM2M.mmCreateTrashLimbLoc, w = 75, h = 25) #Little Column for the chest and pelvis #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeA", numberOfColumns = 2, cw= [[1, 75],[2, 75]]) curWinHeightColumn2b += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeA", q = 1, h = 1) cmds.text("Mirror Limb?") #Pin UVs option of Unfold Button cmds.radioButtonGrp( "mmLimb_MirrorCheckBox", nrb = 2, vr = 0, labelArray2 = ["Yes", "No"], sl = 1, ct2 = ["center","center"], cl2 = ["center","center"], adj = 1, co2 = [-3, 0] ) curWinHeightColumn2b += cmds.radioButtonGrp("mmLimb_MirrorCheckBox", q = 1, h = 1) cmds.text("Include Foot?") #Pin UVs option of Unfold Button cmds.radioButtonGrp( "mmLimb_FootCheckBox", nrb = 2, vr = 0, labelArray2 = ["Yes", "No"], sl = 1, ct2 = ["center","center"], cl2 = ["center","center"], adj = 1, co2 = [-3, 0] ) curWinHeightColumn2b += cmds.radioButtonGrp("mmLimb_FootCheckBox", q = 1, h = 1) cmds.text("Include Toe?") #Pin UVs option of Unfold Button cmds.radioButtonGrp( "mmLimb_ToeCheckBox", nrb = 2, vr = 0, labelArray2 = ["Yes", "No"], sl = 2, ct2 = ["center","center"], cl2 = ["center","center"], adj = 1, co2 = [-3, 0] ) curWinHeightColumn2b += cmds.radioButtonGrp("mmLimb_ToeCheckBox", q = 1, h = 1) #End the previous rowColumn cmds.setParent("..") cmds.text("Select only LEFT limb pieces\nfrom furthest extremity to\npart closest to body.") #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Single Limb Primer", command = mmCM2M.mmGenericRigAddFeet, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2b += 10 #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Step 2 - Partial Rig", command = mmCM2M.mmGenericRigRunStep2, w = 75, h = 25) cmds.separator( height=10, style='in' ) curWinHeightColumn2b += 10 #Little Column for the chest and pelvis #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeB", numberOfColumns = 2, cw= [[1, 75],[2, 75]]) curWinHeightColumn2b += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeB", q = 1, h = 1) cmds.text("Define Group") #TextField to set which spine control we are working with cmds.intField("mmCreateSpineGroupValue", w = 75, h = 25, v = 1) curWinHeightColumn2b += 5 #End the previous rowColumn cmds.setParent("..") #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Optional Spine Controls", command = mmCM2M.mmGenericRigAddSpine, w = 75, h = 25) #Little Column for the chest and pelvis #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeC", numberOfColumns = 2, cw= [[1, 75],[2, 75]]) curWinHeightColumn2b += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeC", q = 1, h = 1) #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Matcher", command = mmOF.mmCallMoveObject, w = 50, h = 25) curWinHeightColumn2b += 5 cmds.text("Matcher will\nmatch the first\nselection to\nthe second's\nposition") #End the previous rowColumn cmds.setParent("..") cmds.text("Start should be +Z from End") #Little Column for the chest and pelvis #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeD", numberOfColumns = 3, cw= [[1, 50],[2, 50],[3, 50]]) curWinHeightColumn2b += cmds.rowColumnLayout("mm_SH_RoCoLayout_ColumnThreeD", q = 1, h = 1) #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Tag Start", command = mmCM2M.mmTagStartObject, w = 50, h = 25) curWinHeightColumn2b += 5 #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Tag Mid", command = mmCM2M.mmTagMidObject, w = 50, h = 25) curWinHeightColumn2b += 5 #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Tag End", command = mmCM2M.mmTagEndObject, w = 50, h = 25) curWinHeightColumn2b += 5 #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Tag S-Ctrl", command = mmCM2M.mmTagStartControl, w = 50, h = 25) curWinHeightColumn2b += 5 #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Tag M-Ctrl", command = mmCM2M.mmTagMidControl, w = 50, h = 25) curWinHeightColumn2b += 5 #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Tag E-Ctrl", command = mmCM2M.mmTagEndControl, w = 50, h = 25) curWinHeightColumn2b += 5 #End the previous rowColumn cmds.setParent("..") cmds.text("Fix any parenting needed.") cmds.text("Don't NEED to tag head start.") cmds.separator( height=10, style='in' ) curWinHeightColumn2b += 10 #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Step 3 - Completion", command = mmCM2M.mmGenericRigRunStep3, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") cmds.separator( height=10, style='in' ) curWinHeightColumn2b += 10 #Creates a new frame and rowColumn set for the Normal buttons and fields SH_RoCoLayout = cmds.frameLayout("Mass Conversion Scripts", label = "Mass Conversion Scripts", cll = 1) curWinHeightColumn1 += cmds.frameLayout("Mass_Conversion_Scripts", q = 1, h = 1) curWinHeightColumn1 += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mm_SH_RoCoLayout_Overall2", numberOfColumns = 2, cw= [[1, 150], [2, 300]]) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "QuickSaveFileAs", command = mmMCF.mmQuickSaveFileAs ) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- #cmds.button ( label = "Export All Anims from this Folder Structure", command = mmMCF.mmExportAllAnims ) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Convert and Export All Anims from this Folder Structure", command = mmMCF.mmConvAndExportAllAnimsSequential_1 ) curWinHeightColumn1 += 30 #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Fix Broken Viewport", command = mmMCF.mmFixBrokenViewport ) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Only Export All Anims from this Folder Structure", command = mmMCF.mmExportAllAnimsSequential_1 ) curWinHeightColumn1 += 30 #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "mmFreezeTransOnGeo", command = mmCM2M.mmFreezeTransOnGeo, w = 75, h = 25) #Button: Calls function to Export an animation from Maya to .JSON #--------------Currently is exporting to correct location with bad information--------------- cmds.button ( label = "Transfer and Export All Anims from this Folder Structure", command = mmMCF.mmTransferAndExportAllAnims ) curWinHeightColumn1 += 30 #Button: Calls function to Export an animation from Maya to .JSON cmds.button ( label = "Select Anim Parts", command = mmSAP.main, w = 75, h = 25) #------------------------------------------------------------------------------- #End the previous rowColumn cmds.setParent(mmTabs) mmCompareList = [curWinHeightColumn1, curWinHeightColumn2a, curWinHeightColumn2b] curWinHeight = max(mmCompareList) #Store window Height to memory setSHWinHeight(curWinHeight) #------------------------------------------------------------------------------- #Basic Modeling Buttons #------------------------------------------------------------------------------- #Creates a base window height value to determine the Tab's required Height #Subsequent additions to this value are adding up to the total height required curWinHeight = 0 #Creates a Collapsable Shelf to Hide/Show the items inside basicFrLayout = cmds.columnLayout("basicFrame") curWinHeight += cmds.columnLayout("basicFrame", q = 1, h = 1) curWinHeight += 30 #Creates a new frame and rowColumn set for the Normal buttons and fields normalRoCoLayout = cmds.frameLayout("normButtons", label = "Normal Buttons", cll = 1) curWinHeight += cmds.frameLayout("normButtons", q = 1, h = 1) curWinHeight += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mmNormalRoCoLayout", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeight += cmds.rowColumnLayout("mmNormalRoCoLayout", q = 1, h = 1) #Button: Shows and/or hides the normals of an object cmds.button ( label = "Toggle Vis", command = mmMF.toggleNormals, w = 75, h = 25) #Button: Allows user to reverse an object's normals cmds.button ( label = "Rev Norm", command = mmMF.toggleRevNormals, w = 75, h = 25) #Button: Allows user to change the size of an object's normals cmds.floatField("normalSizeVal", value=.4, min=.001, step=.1, precision=3, w = 50) cmds.button ( label = "Norm Size", command = mmMF.dispNormalSize, w = 75, h = 25) #End the previous rowColumn cmds.setParent(basicFrLayout) #Creates a new frame and rowColumn set for the Edge buttons and fields edgeRoCoLayout = cmds.frameLayout("edgeButtons", label = "Edge Buttons", cll = 1) curWinHeight += cmds.frameLayout("edgeButtons", q = 1, h = 1) curWinHeight += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mmEdgeRoCoLayout", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeight += cmds.rowColumnLayout("mmEdgeRoCoLayout", q = 1, h = 1) #Button: Softens the selected edges cmds.button ( label = "Soften Edges", command = mmMF.softenEdge, w = 75, h = 25) #Button: Hardens the selected edges cmds.button ( label = "Harden Edges", command = mmMF.hardenEdge, w = 75, h = 25) #Button: Show / hide border edges cmds.button ( label = "Toggle Vis", command = mmMF.toggleBorderEdges, w = 75, h = 25) #End the previous rowColumn cmds.setParent(edgeRoCoLayout) #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("mmBasicColumnLayout2", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeight += cmds.rowColumnLayout("mmBasicColumnLayout2", q = 1, h = 1) #Button: Change border edge thickness with a field cmds.floatField("borderEdgeThickVal", value=2, min=.001, step=.1, precision=3, w = 50) cmds.button ( label = "Set Width", command = mmMF.setBordEdgeThickness, w = 75, h = 25) #Button: Sets the selected edges softness to the value which the user provides cmds.floatField("edgeSoftVal", value=30, min=0, max = 180, step=1, precision=3, w = 50) cmds.button ( label = "Edge Size", command = mmMF.setEdgeSoftness, w = 75, h = 25) #End the previous rowColumn cmds.setParent(mmTabs) #Store window Height to memory setModWinHeight(curWinHeight) #------------------------------------------------------------------------------- #UV Buttons #------------------------------------------------------------------------------- #Creates a base window height value to determine the Tab's required Height #Subsequent additions to this value are adding up to the total height required curWinHeight = 0 #Creates a new frame and rowColumn set for the UV buttons and fields uvFrLayout = cmds.frameLayout("uvLayout1", label = "UV Buttons", cll = 0) curWinHeight += cmds.frameLayout("uvLayout1", q = 1, h = 1) curWinHeight += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout2", numberOfColumns = 1, cw= [1,150]) curWinHeight += cmds.rowColumnLayout("uvLayout2", q = 1, h = 1) #Button to open the UV editor cmds.button ( label = "UV Editor", command = mmUVF.uvWindow, w = 75, h = 25) #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout3", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeight += cmds.rowColumnLayout("uvLayout3", q = 1, h = 1) #Radio Buttons for positive or negative U coords cmds.radioButtonGrp( "uCheckBox", nrb = 2, vr = 1, labelArray2 = ["+U", "-U"], cw = [[1, 35],[2, 35]]) curWinHeight += cmds.radioButtonGrp("uCheckBox", q = 1, h = 1) #Radio Buttons for positive or negative V coords cmds.radioButtonGrp( "vCheckBox", nrb = 2, vr = 1, labelArray2 = ["+V", "-V"], cw = [[1, 35],[2, 35]]) curWinHeight += cmds.radioButtonGrp("vCheckBox", q = 1, h = 1) #End the previous rowColumn cmds.setParent("..") #Button moves UV's to a negative U or V coordinate area cmds.button("button1", label = "Move UV", command = mmUVF.moveUVCords, w = 75, h = 25) curWinHeight += cmds.button("button1", q = 1, h = 1) #Creates a new frame and rowColumn set for the Unfold UV buttons and fields cmds.frameLayout("uvLayout4", label = "Unfold UVs", cll = 1) curWinHeight += cmds.frameLayout("uvLayout4", q = 1, h = 1) curWinHeight += 10 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout5", numberOfColumns = 1, cw= [1,150]) curWinHeight += cmds.rowColumnLayout("uvLayout5", q = 1, h = 1) #Unfold UV fields, radio selectors, and buttons #Weight Solver option of Unfold Button cmds.text("Weight Solver") cmds.floatSliderGrp("weightSolver", field=True, value=0.0, min=0, max = 1, step=.01, precision=3, cw = [[1,75], [2,75]]) curWinHeight += cmds.floatSliderGrp("weightSolver", q = 1, h = 1) #Optimization option of Unfold Button cmds.text("Optimize to Original") cmds.floatSliderGrp("optimizeToOriginal", field=True, value=0.5, min=0, max = 1, step=.01, precision=3, cw = [[1,75], [2,75]]) curWinHeight += cmds.floatSliderGrp("optimizeToOriginal", q = 1, h = 1) #Number of Maximum Iterations option of Unfold Button cmds.text("Max Iterations") cmds.intSliderGrp("unfoldMaxIterations", field=True, value=5000, min=0, max = 10000, cw = [[1,75], [2,75]]) curWinHeight += cmds.intSliderGrp("unfoldMaxIterations", q = 1, h = 1) #Stopping Threshold option of Unfold Button cmds.text("Stopping Threshold") cmds.floatSliderGrp("stopThresh", field=True, value=.0010, min=0, max = 1, step=.01, precision=3, cw = [[1,75], [2,75]]) curWinHeight += cmds.floatSliderGrp("stopThresh", q = 1, h = 1) #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout6", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeight += cmds.rowColumnLayout("uvLayout6", q = 1, h = 1) #Pin UVs option of Unfold Button cmds.text("Pin UVs") cmds.radioButtonGrp( "unfoldCheckBox", nrb = 3, vr = 1, labelArray3 = ["Border", "Selected", "None"], sl = 3) curWinHeight += cmds.radioButtonGrp("unfoldCheckBox", q = 1, h = 1) #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout7", numberOfColumns = 1, cw= [1,150]) curWinHeight += cmds.rowColumnLayout("uvLayout7", q = 1, h = 1) #Button which calls Unfold function cmds.button("button2", label = "Unfold", command = mmUVF.uvUnfold, w = 75, h = 25) curWinHeight += cmds.button("button2", q = 1, h = 1) #Creates a new frame and rowColumn set for the Relax UV buttons and fields cmds.frameLayout("uvLayout10", label = "Relax UVs", cll = 1) curWinHeight += cmds.frameLayout("uvLayout10", q = 1, h = 1) #curWinHeight += 10 cmds.text("Max Iterations") cmds.intSliderGrp("relaxMaxIterations", field=True, value=90, min=0, max = 200, cw = [[1,75], [2,75]]) #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout11", numberOfColumns = 1, cw= [1,150]) curWinHeight += cmds.rowColumnLayout("uvLayout11", q = 1, h = 1) cmds.text("Pin UVs") #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("uvLayout8", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeight += cmds.rowColumnLayout("uvLayout8", q = 1, h = 1) #Relax Options cmds.radioButtonGrp( "relaxCheckBox", nrb = 3, vr = 1, labelArray3 = ["Border", "Selected", "None"], sl = 1) curWinHeight += cmds.radioButtonGrp("relaxCheckBox", q = 1, h = 1) #Button which calls Relax Function cmds.button("button3", label = "Relax", command = mmUVF.uvRelax, w = 75, h = 25) curWinHeight += cmds.button("button3", q = 1, h = 1) #curWinHeight += 10 #Button to select UV Shell Border out of almost any selection cmds.button ( label = "Grab Border", command = mmUVF.selectUVBorder, w = 75, h = 25) #curWinHeight += 10 #Button to select UV Shell out of almost any selection cmds.button ( label = "Grab Shell", command = mmUVF.selectUV, w = 75, h = 25) #curWinHeight += 10 #End the previous rowColumn cmds.setParent("..") cmds.rowColumnLayout("uvLayout9", numberOfColumns = 2, cw= [1,75]) curWinHeight += cmds.rowColumnLayout("uvLayout9", q = 1, h = 1) #Button: Sets the selected edges softness to the value which the user provides cmds.intField("uvAdjustVal", value=1, min=0, max = 10, step=1, w = 50) #curWinHeight += 10 #Button to select UV Shell out of almost any selection cmds.button ( label = "UV Adj", command = mmUVF.adjUV, w = 75, h = 25) #curWinHeight += 10 #End the previous rowColumn cmds.setParent(mmTabs) #Store window Height to memory setUVWinHeight(curWinHeight) #------------------------------------------------------------------------------- #Organization Buttons #------------------------------------------------------------------------------- #Creates a base window height value to determine the Tab's required Height #Subsequent additions to this value are adding up to the total height required curWinHeight = 0 curWinHeightColumn1 = 0 curWinHeightColumn2 = 0 curWinHeightColumn3 = 0 #Creates a Collapsable Shelf to Hide/Show the items inside orgFrLayout = cmds.frameLayout("orgLayout1", label = "Organization Options", cll = 1) curWinHeightColumn1 += cmds.frameLayout("orgLayout1", q = 1, h = 1) #Creates a new rowColumn Layout for design purposes #This is a larger set up than needed, and inside it should be multiple smaller UI menus orgMainLayout = cmds.rowColumnLayout("orgLayout2", numberOfColumns = 3, cw= [[1,150],[2,150],[3,150]], cal = [1,"center"]) curWinHeightColumn1 += cmds.rowColumnLayout("orgLayout2", q = 1, h = 1) #Creates a new rowColumn Layout for design purposes #This is a new rowColumn specifically for the Trans/Rot/Scale toggle options cmds.rowColumnLayout("orgLayout2sub1", numberOfColumns = 1, cw= [1,140], cal = [1,"center"]) curWinHeightColumn1 += cmds.rowColumnLayout("orgLayout2sub1", q = 1, h = 1) #Creates a new rowColumn Layout for design purposes #This is a larger set up than needed, and inside it should be multiple smaller UI menus cmds.rowColumnLayout("orgLayout2sub2", numberOfColumns = 2, cw= [[1,150],[2,150],[3,150]], cal = [1,"center"]) curWinHeightColumn1 += cmds.rowColumnLayout("orgLayout2sub2", q = 1, h = 1) #Creates a new rowColumn Layout for design purposes #This is a new rowColumn specifically for the Trans/Rot/Scale toggle options cmds.rowColumnLayout("orgLayout2sub3", numberOfColumns = 2, cw= [[1,50],[2,90]], cal = [1,"center"]) curWinHeightColumn1 += cmds.rowColumnLayout("orgLayout2sub3", q = 1, h = 1) #Button which Selects or Deselects all Trans check boxes cmds.button ( label = "Trans", command = mmOF.selectAllTransToggle, w = 50, h = 25) #Check Boxes for Translate X, Y, and Z selection cmds.checkBoxGrp ( "chkBoxTrans", ncb = 3, labelArray3 = ["X", "Y", "Z"], cw = [[1, 30],[2, 30],[3, 30]], cal = [1,"center"]) curWinHeightColumn1 += cmds.checkBoxGrp("chkBoxTrans", q = 1, h = 1) #Button which Selects or Deselects all Trans check boxes cmds.button( label = "Rotate", command = mmOF.selectAllRotToggle, w = 50, h = 25) #Check Boxes for Rotate X, Y, and Z selection cmds.checkBoxGrp( "chkBoxRot", ncb = 3, labelArray3 = ["X", "Y", "Z"], cw = [[1, 30],[2, 30],[3, 30]], cal = [1,"center"]) curWinHeightColumn1 += cmds.checkBoxGrp("chkBoxRot", q = 1, h = 1) #Button which Selects or Deselects all Trans check boxes cmds.button( label = "Scale", command = mmOF.selectAllScaleToggle, w = 50, h = 25) #Check Boxes for Scale X, Y, and Z selection cmds.checkBoxGrp( "chkBoxScale", ncb = 3, labelArray3 = ["X", "Y", "Z"], cw = [[1, 30],[2, 30],[3, 30]], cal = [1,"center"]) curWinHeightColumn1 += cmds.checkBoxGrp("chkBoxScale", q = 1, h = 1) #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("orgLayout3", numberOfColumns = 2, cw= [[1,50],[2,75]], cal = [1,"center"]) curWinHeightColumn1 += cmds.rowColumnLayout("orgLayout3", q = 1, h = 1) #Button which Selects or Deselects all check boxes cmds.button( label = "Tog All", command = mmOF.selectAllToggle, w = 50, h = 25) #End the previous rowColumn cmds.setParent("..") #Check Boxes for Visibility selection cmds.checkBoxGrp( "chkBoxVis", label = "Vis", ncb = 1, l = "Vis", cw = [[1, 40],[2, 30]], cal = [1,"center"]) curWinHeightColumn1 += cmds.checkBoxGrp("chkBoxVis", q = 1, h = 1) #End the previous rowColumn cmds.setParent("..") #End the previous rowColumn cmds.setParent("..") #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("orgLayout4", numberOfColumns = 2, cw= [[1,75],[2,75]]) curWinHeightColumn1 += cmds.rowColumnLayout("orgLayout4", q = 1, h = 1) #Lock and Hide Attributes Button cmds.button( label = "Lock/Hide", command = mmOF.lockNHide, w = 50, h = 25) #Unlock and Unhide Attributes Button cmds.button( label = "UnLock/Hide", command = mmOF.unlockUnhide, w = 50, h = 25) #Button changes display type to Reference for all selected objects cmds.button( label = "Ref Display", command = mmOF.refDisplayType, w = 50, h = 25) #Button changes display type to Normal for all selected objects cmds.button( label = "Norm Display", command = mmOF.normDisplayType, w = 50, h = 25) #End the previous rowColumn cmds.setParent(orgMainLayout) #------------------------------------------------------------------------------- #Adding a separator to see what happens #cmds.separator( height=1, style='single' ) #Creates a new column set cmds.rowColumnLayout("orgLayout5", numberOfColumns = 1, cw= [1,150]) curWinHeightColumn2 += cmds.rowColumnLayout("orgLayout5", q = 1, h = 1) #Creates a Color Index Slider Group to change colors of selected objects cmds.colorIndexSliderGrp("colorField", min=0, max=20, value=0, w = 100 ) cmds.button( label = "Color Changer", command = mmOF.changeColor, w = 50, h = 25) curWinHeightColumn2 += 50 #Button to Mass Rename different selections cmds.text("Mass Rename Add Prefix") cmds.textFieldButtonGrp("massRenameField_Prefix", text='addedText_', buttonLabel='Add Pre', bc = mmOF.mmNameAddPrefix, cw = [[1,100],[2,50]] ) curWinHeightColumn2 += 10 #Button to Mass Rename different selections cmds.text("Mass Rename Add Suffix") cmds.textFieldButtonGrp("massRenameField_Suffix", text='_addedText', buttonLabel='Add Suf', bc = mmOF.mmNameAddSuffix, cw = [[1,100],[2,50]] ) curWinHeightColumn2 += 10 #Button causes the first selected object to move to the second & freeze transforms cmds.button( label = "Matcher", command = mmOF.mmCallMoveObject, w = 50, h = 25) curWinHeightColumn2 += 10 cmds.text("Matcher will match\nthe first selection to\nthe second's position") #End the previous rowColumn cmds.setParent(orgMainLayout) #------------------------------------------------------------------------------- #Creates a Collapsable Shelf to Hide/Show the items inside cmds.frameLayout("orgLayout6", label = "Icon Creation", cll = 1) curWinHeightColumn3 += cmds.frameLayout("orgLayout6", q = 1, h = 1) curWinHeightColumn3 += 30 #Creates a new rowColumn Layout for design purposes cmds.rowColumnLayout("orgLayout7", numberOfColumns = 2, cw= [[1,75],[2,75]], cal = [1,"center"]) curWinHeightColumn3 += cmds.rowColumnLayout("orgLayout7", q = 1, h = 1) curWinHeightColumn3 += 30 #Button creates a Box shaped Icon NURB cmds.button( label = "Box", command = mmOF.createCube, w = 50, h = 25) curWinHeightColumn3 += 5 #Button creates a Belt shaped Icon NURB cmds.button( label = "Belt", command = mmOF.createBelt, w = 50, h = 25) #Button creates a Hand shaped Icon NURB cmds.button( label = "Hand", command = mmOF.createHand, w = 50, h = 25) #Button creates a Foot shaped Icon NURB cmds.button( label = "Foot", command = mmOF.createFoot, w = 50, h = 25) curWinHeightColumn3 += 5 #Button creates an Arrow shaped Icon NURB cmds.button( label = "Move All", command = mmOF.createMoveAll, w = 50, h = 25) #Button creates a Cog shaped Icon NURB cmds.button( label = "COG", command = mmOF.createCog, w = 50, h = 25) curWinHeightColumn3 += 5 #Button creates a Cog shaped Icon NURB cmds.button( label = "L", command = mmOF.createL, w = 50, h = 25) #Button creates a Cog shaped Icon NURB cmds.button( label = "R", command = mmOF.createR, w = 50, h = 25) curWinHeightColumn3 += 5 #Button creates a Pin shaped Icon NURB cmds.button( label = "Pin", command = mmOF.createPin, w = 50, h = 25) #Button creates a Pin shaped Icon NURB cmds.button( label = "Orb", command = mmOF.createOrb, w = 50, h = 25) curWinHeightColumn3 += 5 #Button creates a Pin shaped Icon NURB cmds.button( label = "FitAll", command = mmOF.createFitAll, w = 50, h = 25) #End the previous rowColumn cmds.setParent("..") #Button to Mass Rename different selections cmds.textFieldButtonGrp("createTextBox_TextField", text='text', buttonLabel='Text', bc = mmOF.createTextBox, cw = [[1,100],[2,50]] ) curWinHeightColumn3 += 10 #End the previous rowColumn cmds.setParent(mmTabs) mmCompareList = [curWinHeightColumn1, curWinHeightColumn2, curWinHeightColumn3] curWinHeight = max(mmCompareList) #Store window Height to memory setOrgWinHeight(curWinHeight) #------------------------------------------------------------------------------- #Rigging Buttons #------------------------------------------------------------------------------- #Creates a base window height value to determine the Tab's required Height #Subsequent additions to this value are adding up to the total height required curWinHeight = 0 #Creates a new frame and rowColumn set for the UV buttons and fields rigFrLayout = cmds.frameLayout("rigLayout1", label = "Rig Buttons", cll = 0) curWinHeight += cmds.frameLayout("rigLayout1", q = 1, h = 1) curWinHeight += 30 cmds.rowColumnLayout("rigLayout2", numberOfColumns = 1, cw= [1,150]) curWinHeight += cmds.rowColumnLayout("rigLayout2", q = 1, h = 1) #Text area to describe how to run the function cmds.text("Select an icon, then\na 3 joint chain to effect.") #Check Box Group to decide what should be included in Hand System cmds.checkBoxGrp("ikfkSwitchChkBoxes", numberOfCheckBoxes=1, label='Include:', label1 = 'Stretchy', v1 = 1, adj = 1, cw2 = [75,75], w = 150, cal = [1,"center"], vr =1) curWinHeight += 50 """ #Old when I had bendy working #Check Box Group to decide what should be included in Hand System cmds.checkBoxGrp("ikfkSwitchChkBoxes", numberOfCheckBoxes=2, label='Include:', la2 = ['Bendy', 'Stretchy'], v1 = 0, v2 = 1, adj = 1, cw2 = [75,75], w = 150, cl2 = ["center","center"], vr =1) curWinHeight += 50 """ #create a new row column layout cmds.rowColumnLayout("rigLayout3", numberOfColumns = 2, cw= [(1,75),(2,75)]) curWinHeight += cmds.rowColumnLayout("rigLayout3", q = 1, h = 1) """ #Old when I had bendy working #Text area to describe how to run the function cmds.text("Bendy \n Divisions:") curWinHeight += 25 #IntField to get the number of divisions for the arm cmds.intField("createIKSplineArmDivVal", w = 75, h = 25, v = 30) """ #Text area to describe how to run the function cmds.text("Number of\nBones In IK:") curWinHeight += 25 #IntField to get the number of divisions for the arm cmds.intField("createIKSplineArmNumBonesVal", w = 75, h = 25, v = 3) #set parent back to previous cmds.setParent("..") #Button to create an IK/FK switch and additional limbs to control it cmds.textFieldButtonGrp("ikfkSwitchLabel", buttonLabel = "IK/FK Auto", bc = mmRF.autoIKFK, w = 75, cw = [[1,75],[2,75]], text = "Switch Label") #Text area to describe how to run the function cmds.text("Ensure joints are oriented\nwith 'Y' down the chain,\na preferred angle is set for\nmid joint, and that names\nare unique. All conn-\nections to limb should\nbe made to last cluster.") curWinHeight += 130 cmds.separator( height=10, style='in' ) curWinHeight += 10 #Text area to describe how to run the function cmds.text("Select icon you want, \n then the joint to set-up.") curWinHeight += 25 #Check Box Group to decide what should be included in Hand System cmds.radioButtonGrp("mmPadAndAlignRadioBoxes", nrb=4, label='Constraint Type:', labelArray4=['Point', 'Aim', 'Orient', 'Parent'], cl2 = ["center","center"], cw2 = [90,60], adj = 1, w = 100, vr =1, sl = 3) curWinHeight += 50 #Button to pad an icon, align it, and orient constrain a joint to it cmds.button(label = "Pad, Align, and Orient", c = mmRF.padAndAlign) curWinHeight += 25 cmds.separator( height=10, style='in' ) curWinHeight += 10 #Text area to describe how to run the function cmds.text("Select curves you want, \n and type in new name.") curWinHeight += 25 #Button to combine multiple Nurbs curves into one object cmds.textFieldButtonGrp("combineNurbsLabel", buttonLabel = "Combine", bc = mmOF.combineNurbCurves, w = 75, cw = [[1,75],[2,75]], text = "New_icon") curWinHeight += 50 cmds.separator( height=10, style='in' ) curWinHeight += 10 #Text area to describe how to run the function cmds.text("Select icon you want, then \n select each finger chain.") curWinHeight += 25 #Check Box Group to decide what should be included in Hand System cmds.checkBoxGrp("handSystemChkBoxes", numberOfCheckBoxes=3, label='Include:', labelArray3=['Curl', 'Spread', 'Twist'], v1 = 1, v2 = 1, v3 = 1, adj = 1, cw2 = [75,75], w = 150, cl2 = ["center","center"], vr =1) curWinHeight += 25 cmds.text("*does not connect 'fist' attr") curWinHeight += 25 cmds.button(label = "Create Hand System", c = mmRF.handCreator) curWinHeight += 50 cmds.separator( height=10, style='in' ) curWinHeight += 10 cmds.text("Select Controller, \n Multiplier, then base\nthrough end pads of\none tentacle") curWinHeight += 50 cmds.button(label = "Connect Tentacle Icon", c = mmRF.tentacleConnector) curWinHeight += 35 cmds.separator( height=10, style='in' ) curWinHeight += 10 #create a new row column layout cmds.rowColumnLayout("rigLayout4", numberOfColumns = 2, cw= [(1,75),(2,75)]) curWinHeight += cmds.rowColumnLayout("rigLayout4", q = 1, h = 1) #End the previous rowColumn cmds.setParent(mmTabs) #Store window Height to memory setRigWinHeight(curWinHeight) #------------------------------------------------------------------------------- #Rigging Buttons 2 #------------------------------------------------------------------------------- #Creates a base window height value to determine the Tab's required Height #Subsequent additions to this value are adding up to the total height required curWinHeight = 0 #Creates a new frame and rowColumn set for the UV buttons and fields rig2FrLayout = cmds.frameLayout("rig2Layout1", label = "Rig Buttons", cll = 0) curWinHeight += cmds.frameLayout("rig2Layout1", q = 1, h = 1) curWinHeight += 30 cmds.rowColumnLayout("rig2Layout2", numberOfColumns = 1, cw= [1,150]) curWinHeight += cmds.rowColumnLayout("rig2Layout2", q = 1, h = 1) cmds.text("Select a Curve, and press\nCLUSTERIZER") curWinHeight += 25 cmds.button(label = "The Clusterizer", c = mmRF.clusterMaker) #curWinHeight += 25 cmds.text("*must be Cubic") cmds.separator( height=10, style='in' ) curWinHeight += 10 cmds.text("Select ikSpline Curve,\nroot joint of chain,\nand select the axis which\ntravels down the chain.") curWinHeight += 25 #Check Box Group to decide what should be included in Hand System cmds.radioButtonGrp("stretchySplineRadioBoxes", nrb=3, labelArray3=["X", "Y", "Z"], cl3 = ["center","center","center"], cw3 = [50, 50, 50], adj = 1, w = 100, vr =0, sl = 2) curWinHeight += 50 cmds.button(label = "Make Spline Stretchy", c = mmRF.makeSplineStretchy) curWinHeight += 25 cmds.separator( height=10, style='in' ) curWinHeight += 10 cmds.text("Select the icon which\nwill control the switch,\nthen the pad which the\nconstraints will be on,\nthen each item which will\nbe constraining.") curWinHeight += 100 #do i need multiple types? parent is the only one that seems to work cmds.radioButtonGrp("switcherSystemChkBoxes", nrb=4, label='Constraint Type:', labelArray4=['Point', 'Orient', 'Parent', 'Scale'], cl2 = ["center","center"], cw2 = [90,60], adj = 1, w = 100, vr =1, sl = 3) curWinHeight += cmds.radioButtonGrp("switcherSystemChkBoxes", q = 1, h = 1) curWinHeight += 25 cmds.button(label = "Create a Switcher System", c = mmRF.spaceSwitcherMulti) curWinHeight += 25 cmds.button(label = "(Simple Switcher System)", c = mmRF.spaceSwitcherMultiSimple) curWinHeight += 25 #Check Box Group to decide what should be included in Hand System cmds.checkBoxGrp("switcherSystemChkBoxes2", numberOfCheckBoxes=1, l='*Create Attributes?', v1 = 1, adj = 1, cw2 = [120, 30], w = 150, cal = (1,"right"), vr =1) curWinHeight += 25 cmds.text("If not, proper attr must\nalready exist on icon.") curWinHeight += 50 cmds.separator( height=10, style='in' ) curWinHeight += 10 cmds.text("Select curve and then\neach joint to effect\nfrom most to least influence") curWinHeight += 50 #Check Box Group to decide what should be included in Hand System cmds.radioButtonGrp("mmMultiChainFKHelperRadioButtons", nrb=2, labelArray2=["Whole\nChain", "Selected\nJoints"], cl2 = ["center","center"], cw2 = [75, 75], adj = 1, w = 100, vr =0, sl = 1) curWinHeight += 50 cmds.button(label = "Multi-Chain FK Helper", c = mmRF.multiChainFKHelper) curWinHeight += 25 #End the previous rowColumn cmds.setParent(mmTabs) #Store window Height to memory setRig2WinHeight(curWinHeight) #------------------------------------------------------------------------------- #Renames the Tabs to comprehensible Names cmds.tabLayout( mmTabs, edit=True, tabLabel=((SH_FrLayout, 'SH_Tools'), (basicFrLayout, 'Modeling'), (orgFrLayout, 'Organization'), (uvFrLayout, 'UVs'), (rigFrLayout, 'Rigging'), (rig2FrLayout, 'Rigging2')) ) #Resizes window to default tab size #This "sti" actually sets the default tab to load on open. cmds.tabLayout("mmTabs", e = 1, sti = 1) setWinHeight() #Display everything cmds.showWindow("sh_toolset_window") #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- #FUNCTIONS #------------------------------------------------------------------------------- #UI Window Functions #------------------------------------------------------------------------------- #Function: Resizes Main Window to fit Tabs as they are selected def setWinHeight(*args): curSelectedTab = cmds.tabLayout("mmTabs", q = 1, sti = 1) if (curSelectedTab == 1): cmds.window("sh_toolset_window", e = 1, h = SH_WinHeightNow) cmds.formLayout("basicFormLayout", e = 1, h = SH_WinHeightNow) elif (curSelectedTab == 2): cmds.window("sh_toolset_window", e = 1, h = modWinHeightNow) cmds.formLayout("basicFormLayout", e = 1, h = modWinHeightNow) elif (curSelectedTab == 3): cmds.window("sh_toolset_window", e = 1, h = uvWinHeightNow) cmds.formLayout("basicFormLayout", e = 1, h = uvWinHeightNow) elif (curSelectedTab == 4): cmds.window("sh_toolset_window", e = 1, h = orgWinHeightNow) cmds.formLayout("basicFormLayout", e = 1, h = orgWinHeightNow) elif (curSelectedTab == 5): cmds.window("sh_toolset_window", e = 1, h = rigWinHeightNow) cmds.formLayout("basicFormLayout", e = 1, h = rigWinHeightNow) elif (curSelectedTab == 6): cmds.window("sh_toolset_window", e = 1, h = rig2WinHeightNow) cmds.formLayout("basicFormLayout", e = 1, h = rig2WinHeightNow) else: print "invalid input"; #Stores Win Height of Particular Tab def setSHWinHeight(shHeightCurrentVal): global SH_WinHeightNow SH_WinHeightNow = shHeightCurrentVal; #Stores Win Height of Particular Tab def setModWinHeight(modHeightCurrentVal): global modWinHeightNow modWinHeightNow = modHeightCurrentVal; #Stores Win Height of Particular Tab def setOrgWinHeight(orgHeightCurrentVal): global orgWinHeightNow orgWinHeightNow = orgHeightCurrentVal; #Stores Win Height of Particular Tab def setUVWinHeight(uvHeightCurrentVal): global uvWinHeightNow uvWinHeightNow = uvHeightCurrentVal; #Stores Win Height of Particular Tab def setRigWinHeight(rigHeightCurrentVal): global rigWinHeightNow rigWinHeightNow = rigHeightCurrentVal; #Stores Win Height of Particular Tab def setRig2WinHeight(rig2HeightCurrentVal): global rig2WinHeightNow rig2WinHeightNow = rig2HeightCurrentVal; #End of Toolset
"""PyTorch implementation of ResNet ResNet modifications written by Bichen Wu and Alvin Wan, based off of ResNet implementation by Kuang Liu. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 """ import functools import torch.nn as nn from .block import BasicBlock, BottleNect class ResNet(nn.Module): def __init__(self, block, num_blocks, num_class=10): super(ResNet, self).__init__() self.num_class = num_class self.in_channels = num_filters = 16 self.conv1 = nn.Conv2d(3, self.in_channels, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(self.in_channels) self.relu = nn.ReLU(inplace=True) self.avgpool = nn.AdaptiveAvgPool2d(1) self.layer1 = self._make_layer(block, self.in_channels, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, int(num_filters*2), num_blocks[1], stride=2) self.layer3 = self._make_layer(block, int(num_filters*4), num_blocks[2], stride=2) self.linear = nn.Linear(int(num_filters*4*block(16,16,1).EXPANSION), num_class) def _make_layer(self, block, ou_channels, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_channels, ou_channels, stride)) self.in_channels = int(ou_channels * block(16,16,1).EXPANSION) return nn.Sequential(*layers) def forward(self, x): out = self.relu(self.bn1(self.conv1(x))) out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.avgpool(out) out = out.view(out.size(0), -1) out = self.linear(out) return out def ResNetWrapper(num_blocks, num_class=10, block=None, attention_module=None): b = lambda in_planes, planes, stride: \ block(in_planes, planes, stride, attention_module=attention_module) return ResNet(b, num_blocks, num_class=num_class) def ResNet20(num_class=10, block=None, attention_module=None): return ResNetWrapper( num_blocks = [3, 3, 3], num_class = num_class, block = block, attention_module = attention_module) def ResNet32(num_class=10, block=None, attention_module=None): return ResNetWrapper( num_blocks = [5, 5, 5], num_class = num_class, block = block, attention_module = attention_module) def ResNet56(num_class=10, block=None, attention_module=None): if block == BasicBlock: n_blocks = [9, 9, 9] elif block == BottleNect: n_blocks = [6, 6, 6] return ResNetWrapper( num_blocks = n_blocks, num_class = num_class, block = block, attention_module = attention_module) def ResNet110(num_class=10, block=None, attention_module=None): if block == BasicBlock: n_blocks = [18, 18, 18] elif block == BottleNect: n_blocks = [12, 12, 12] return ResNetWrapper( num_blocks = n_blocks, num_class = num_class, block = block, attention_module = attention_module) def ResNet164(num_class=10, block=None, attention_module=None): if block == BasicBlock: n_blocks = [27, 27, 27] elif block == BottleNect: n_blocks = [18, 18, 18] return ResNetWrapper( num_blocks = n_blocks, num_class = num_class, block = block, attention_module = attention_module)
def range_chars(char_1, char_2): range_start = ord(char_1) range_end = ord(char_2) for i in range(range_start+ 1, range_end): print(chr(i), end=" ") character_1 = input() character_2 = input() range_chars(character_1, character_2)
def perform(codes): cur = codes[0] idx = 1 res = 0 cnt = base_cnt = 1 def calc_res(base_cnt, cnt, res): if base_cnt >= cnt: if 0 >= cnt: res += base_cnt else: res += base_cnt - cnt return res while idx < len(codes): if cur == codes[idx]: cnt += 1 base_cnt = cnt else: cnt -= 1 if idx + 1 >= len(codes): res = calc_res(base_cnt, cnt, res) elif idx + 1 < len(codes) and cur == codes[idx + 1]: res = calc_res(base_cnt, cnt, res) cnt = 0 cur = codes[idx] idx -= 1 idx += 1 return res
import pygame BLACK = (0,0,0) class Brick(pygame.sprite.Sprite): #This class represents a brick. It derives from the "Sprite" class in Pygame. lives=0 def __init__(self, color, width, height, lives): # Call the parent class (Sprite) constructor super().__init__() self.lives=lives # Pass in the color of the brick, and its x and y position, width and height. # Set the background color and set it to be transparent self.image = pygame.Surface([width, height]) self.image.fill(BLACK) self.image.set_colorkey(BLACK) # Draw the brick (a rectangle!) pygame.draw.rect(self.image, color, [0, 0, width, height]) # Fetch the rectangle object that has the dimensions of the image. self.rect = self.image.get_rect() def hurt(self): self.lives -= 1 if self.lives == 0: self.kill() return 1 return 0
from typing import Any class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def printc(*args: Any, color: str = 'green') -> None: string = '' for arg in args: string += str(arg) print(_get_color_from_string(color) + string + bcolors.ENDC) def _get_color_from_string(string: str) -> str: return { 'green': bcolors.OKGREEN, 'blue': bcolors.OKBLUE, 'cyan': bcolors.OKCYAN, 'yellow': bcolors.WARNING, 'red': bcolors.FAIL }[string.lower()]
DBENGINE = 'mysql' # ENGINE OPTIONS: mysql, sqlite3, postgresql DBNAME = 'lianjia2' DBUSER = 'lianjia' DBPASSWORD = 'lianjia' DBHOST = '192.168.50.113' DBPORT = 3306 CITY = 'gz' # only one, shanghai=sh shenzhen=sh...... REGIONLIST = [u'huangpu'] # only pinyin support
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse @api_view(['GET']) def api_root(request, format=None): return Response({ 'apis': reverse('apis:checkbox-list', request=request, format=format), })
import sys i1 = 10 i2 = 10 print(hex(id(i1)),hex(id(i2))) i1 = 11 i2 = 10 + 1 print(hex(id(i1)),hex(id(i2))) # list는 mutable이므로 서로 다른 객체가 된다 l1 = [1,2] l2 = [1,2] print(hex(id(l1)),hex(id(l2))) s1 = 'hello' s2 = 'hello' print(hex(id(s1)),hex(id(s2))) # is 동일성 레퍼런스 비교 print(i1 is i2) print(l1 is l2) print(s1 is s2) # 리터럴 상수 지정 방식 t1 = (1,2,3) t2 = (1,2,3) print(sys.getrefcount(t1), sys.getrefcount(t2)) print(t1 is t2) # 생성자 방식 t3 = tuple(range(1,4)) print(sys.getrefcount(t3)) print(t1 is t3) # slicing 방식 t4 = (0,1,2,3)[1:] print(t3 is t4) # 직접 리터럴 상수를 지정하는 방식 / 생성자를 활용하는 방식 / slicing 방식의 동일성 결과는 서로 다름
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=missing-docstring import argparse import json import logging import os import subprocess import sys import time from distutils.spawn import find_executable import requests requests.packages.urllib3.disable_warnings() logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def here(path=''): return os.path.abspath(os.path.join(os.path.dirname(__file__), path)) if not here('./lib') in sys.path: sys.path.append(here('./lib')) from botscript import bot class Ngrok: # delay time in sec delay = 3 # Popen object popen = None # pubilic url public_url = None def __init__(self, port=5000): """constructor for Ngrok class Keyword Arguments: port {int} -- internal port number (default: {5000}) """ self.port = port webhook_url = os.environ.get('bot_webhook') if webhook_url is None or webhook_url.strip() == '': # check if ngrok is installed assert find_executable("ngrok"), "ngrok command must be installed, see https://ngrok.com/" self.ngrok_cmds = ["ngrok", "http", str(port), "-log=stdout"] self.pkill_cmds = ["pkill"] self.pkill_cmds.extend(self.ngrok_cmds) def pkill(self): """kill previous sessions of ngrok (if any)""" subprocess.Popen(self.pkill_cmds, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).wait() def run_background(self): """run ngrok in background, using subprocess.Popen()""" # kill same port process, if any self.pkill() logger.info("start ngrok") # spawn ngrok in background # subprocess.call("ngrok http 5000 -log=stdout > /dev/null &", shell=True) self.popen = subprocess.Popen(self.ngrok_cmds, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Leaving some time to ngrok to open time.sleep(self.delay) result_code = self.popen.poll() if result_code is None: logger.info("ngrok is running successfuly") return True logger.error("ngrok terminated abruptly with code: %s", str(result_code)) return False def get_info(self): """get info object from rest api""" # use ngrok management api api_path = 'http://127.0.0.1:4040/api/tunnels' get_result = None try: get_result = requests.get(api_path) except requests.exceptions.RequestException: return None if get_result and get_result.ok: return get_result.json() return None def get_public_url(self): """getter for public_url Returns: str -- public_url handled by ngrok """ if self.public_url: # already exist return self.public_url data = self.get_info() if data is None: return None self.public_url = data['tunnels'][0]['public_url'] return self.public_url if __name__ == '__main__': logging.basicConfig(level=logging.INFO) def main(): parser = argparse.ArgumentParser(description='operate ngrok and webhook for webex teams.') # webhook parser.add_argument('-r', '--regist', action='store_true', default=False, help='Regist webhook') parser.add_argument('-d', '--delete', action='store_true', default=False, help='Delete webhook') parser.add_argument('-u', '--update', action='store_true', default=False, help='Update disabled webhook') # ngrok parser.add_argument('-s', '--start', action='store_true', default=False, help='Start ngrok and regist webhook') parser.add_argument('-k', '--kill', action='store_true', default=False, help='Kill ngrok process and delete webhook') # list parser.add_argument('-l', '--list', action='store_true', default=False, help='List ngrok and webhook information') args = parser.parse_args() result_code = 0 if args.regist: result_code = regist_webhook() elif args.delete: result_code = delete_webhook() elif args.update: result_code = update_webhook() elif args.start: result_code = start() elif args.kill: result_code = kill() elif args.list: result_code = list_info() return result_code def regist_webhook(): webhook_url = os.environ.get('bot_webhook') if webhook_url is None or webhook_url.strip() == '': logger.error("failed to read environment variable 'bot_webhook', please set it before run this script") return -1 bot.regist_webhook(target_url=webhook_url) return 0 def delete_webhook(): bot.delete_webhooks() return 0 def update_webhook(): webhooks = bot.get_webhooks() if not webhooks: print("no webhook found.") return 0 for w in webhooks: status = w.get('status') if status != 'active': webhook_id = w.get('id') webhook_name = w.get('name') target_url = w.get('targetUrl') print("disabled webhook found: {}".format(webhook_id)) bot.update_webhook(webhook_id=webhook_id, webhook_name=webhook_name, target_url=target_url) return 0 def start(): ngrok = Ngrok() ngrok_result = ngrok.run_background() if ngrok_result is False: logger.error("failed to run ngrok") return -1 # get public_url opened by ngrok public_url = ngrok.get_public_url() # register webhook with the public url bot.regist_webhook(target_url=public_url) # show all webhooks logger.info("show all webhooks below") webhooks = bot.get_webhooks() for w in webhooks: print(json.dumps(w, ensure_ascii=False, indent=2)) return 0 def kill(): ngrok = Ngrok() ngrok.pkill() bot.delete_webhooks() return 0 def list_info(): ngrok = Ngrok() info = ngrok.get_info() if info: print('ngrok is running') print(json.dumps(info, ensure_ascii=False, indent=2)) print('') else: print('no ngrok found.') webhooks = bot.get_webhooks() if webhooks: print('webhook is registered') for w in webhooks: print(json.dumps(w, ensure_ascii=False, indent=2)) print('') else: print('no webhook found.') return 0 sys.exit(main())
from typing import Callable import cv2 import numpy as np from torch.utils.data import Dataset from torchvision import transforms as transforms class TransformDataset(Dataset): def __init__(self, dataset: Dataset, transform: Callable): self.dataset = dataset self.transform = transform def __getitem__(self, index: int): dataPoint = self.dataset[index] if isinstance(dataPoint, tuple): return (self.transform(dataPoint[0]),) + dataPoint[1:] else: return self.transform(dataPoint) def __len__(self): return len(self.dataset) class PairTransform(object): def __init__(self, transform): self.transform = transform def __call__(self, sample): xi = self.transform(sample) xj = self.transform(sample) return xi, xj def get_simclr_image_transform(color_scale, input_shape): # get a set of data augmentation transformations as described in the SimCLR paper. color_jitter = transforms.ColorJitter(0.8 * color_scale, 0.8 * color_scale, 0.8 * color_scale, 0.2 * color_scale) data_transforms = transforms.Compose([transforms.RandomResizedCrop(size=input_shape[0]), transforms.RandomHorizontalFlip(), transforms.RandomApply([color_jitter], p=0.8), transforms.RandomGrayscale(p=0.2), GaussianBlur(kernel_size=int(0.1 * input_shape[0])), transforms.ToTensor()]) return data_transforms class GaussianBlur(object): # Implements Gaussian blur as described in the SimCLR paper def __init__(self, kernel_size, min=0.1, max=2.0): self.min = min self.max = max # kernel size is set to be 10% of the image height/width self.kernel_size = kernel_size def __call__(self, sample): sample = np.array(sample) # blur the image with a 50% chance prob = np.random.random_sample() if prob < 0.5: sigma = (self.max - self.min) * np.random.random_sample() + self.min sample = cv2.GaussianBlur(sample, (self.kernel_size, self.kernel_size), sigma) return sample
def lightNeeded(x): if x==0: return 6 if x==1: return 2 if x==2: return 5 if x==3: return 5 if x==4: return 4 if x==5: return 5 if x==6: return 6 if x==7: return 4 if x==8: return 7 if x==9: return 6 ''' def changeConsumed(x,y): if y=="*": return lightNeeded(x) if x==y: return 0 if (x==0 or y==0): if (x==0 and y==1) or (x==1 and y==0): return 4 if (x==0 and y==2) or (x==2 and y==0): return 3 if (x==0 and y==3) or (x==3 and y==0): return 3 if (x==0 and y==4) or (x==4 and y==0): return 4 if (x==0 and y==5) or (x==5 and y==0): return 3 if (x==0 and y==6) or (x==6 and y==0): return 2 if (x==0 and y==7) or (x==7 and y==0): return 2 if (x==0 and y==8) or (x==8 and y==0): return 1 if (x==0 and y==9) or (x==9 and y==0): return 2 if (x==1 or y==1): if (x==1 and y==2) or (x==2 and y==1): return 5 if (x==1 and y==3) or (x==3 and y==1): return 3 if (x==1 and y==4) or (x==4 and y==1): return 2 if (x==1 and y==5) or (x==5 and y==1): return 5 if (x==1 and y==6) or (x==6 and y==1): return 6 if (x==1 and y==7) or (x==7 and y==1): return 2 if (x==1 and y==8) or (x==8 and y==1): return 5 if (x==1 and y==9) or (x==9 and y==1): return 4 if (x==2 or y==2): if (x==2 and y==3) or (x==3 and y==2): return 2 if (x==2 and y==4) or (x==4 and y==2): return 5 if (x==2 and y==5) or (x==5 and y==2): return 4 if (x==2 and y==6) or (x==6 and y==2): return 3 if (x==2 and y==7) or (x==7 and y==2): return 5 if (x==2 and y==8) or (x==8 and y==2): return 2 if (x==2 and y==9) or (x==9 and y==2): return 3 if (x==3 or y==3): if (x==3 and y==4) or (x==4 and y==3): return 3 if (x==3 and y==5) or (x==5 and y==3): return 2 if (x==3 and y==6) or (x==6 and y==3): return 3 if (x==3 and y==7) or (x==7 and y==3): return 3 if (x==3 and y==8) or (x==8 and y==3): return 2 if (x==3 and y==9) or (x==9 and y==3): return 1 if (x==4 or y==4): if (x==4 and y==5) or (x==5 and y==4): return 3 if (x==4 and y==6) or (x==6 and y==4): return 4 if (x==4 and y==7) or (x==7 and y==4): return 2 if (x==4 and y==8) or (x==8 and y==4): return 3 if (x==4 and y==9) or (x==9 and y==4): return 2 if (x==5 or y==5): if (x==5 and y==6) or (x==6 and y==5): return 1 if (x==5 and y==7) or (x==7 and y==5): return 3 if (x==5 and y==8) or (x==8 and y==5): return 2 if (x==5 and y==9) or (x==9 and y==5): return 1 if (x==6 or y==6): if (x==6 and y==7) or (x==7 and y==6): return 4 if (x==6 and y==8) or (x==8 and y==6): return 1 if (x==6 and y==9) or (x==9 and y==6): return 2 if (x==7 or y==7): if (x==7 and y==8) or (x==8 and y==7): return 3 if (x==7 and y==9) or (x==9 and y==7): return 2 if (x==8 or y==8): if (x==8 and y==9) or (x==9 and y==8): return 1''' def dig(x): total=0 while x>0: total+=x%10 x/=10 return total def Primes(a): sieve=[True]*(a+1) sieve[:2]=[False, False] sqrt=int(a**.5)+1 for x in range(2, sqrt): if sieve[x]: sieve[2*x::x]=[False]*(a/x-1) return sieve def countClock(x): s=str(x) total=0 for y in s: total+=lights(y).count("1") return total def changeClock(x,y): s1=str(x) s2=str(y) while len(s2)<len(s1): s2="*"+s2 total=0 for z in range(len(s1)): if s2[z]=="*": total+=changeConsumed(int(s1[z]),s2[z]) else: total+=changeConsumed(int(s1[z]),int(s2[z])) return total def lights(x): if x=="*": return '0000000' x=int(x) if x==0: return '1111110' if x==1: return '0110000' if x==2: return '1101101' if x==3: return '1111001' if x==4: return '0110011' if x==5: return '1011011' if x==6: return '1011111' if x==7: return '1110010' if x==8: return '1111111' if x==9: return '1111011' def changeClock2(x,y): s1=str(x) s2=str(y) total=0 while len(s2)<len(s1): s2="*"+s2 for z in range(len(s1)): a=int(lights(s1[z]),2) b=int(lights(s2[z]),2) #print x,y, a, b, bin(a^b), lights(s1[z]), lights(s2[z]) total+=bin(a^b).count("1") return total def main(a,b): p=Primes(b) primes=[] for x in range(len(p)): if p[x]: primes.append(x) x=0 while primes[x]<a: x+=1 count1=0 count2=0 print primes[-1] #primes=[137] #x=0 for y in range(x, len(primes)): p=primes[y] #print p count1+=countClock(p)*2 count2+=countClock(p) #print count1, count2 prev=p nex=dig(p) while prev>=10: count1+=countClock(nex)*2 #print nex, countClock(nex)*2 count2+=changeClock2(prev,nex) #print prev, nex, changeClock2(prev,nex) prev=nex nex=dig(nex) #print prev, nex #print nex count2+=lightNeeded(nex) print count1, count2, count1-count2 main(10000000,20000000)
import FWCore.ParameterSet.Config as cms highPurityGeneralTracks = cms.EDFilter( 'TrackSelector', src = cms.InputTag('generalTracks'), cut = cms.string('quality("highPurity")'), )
# -*- coding: utf-8 -*- """ Created on Fri Dec 25 20:21:56 2020 @author: AYUSHI GUPTA """ def progC(): import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from guizero import App, Combo,Text,CheckBox, ButtonGroup,PushButton,info,TextBox, Picture import os import time import sys from io import StringIO from sklearn.metrics import recall_score,precision_score #import math import seaborn as sn def sigmoid(z): return 1 / (1 + np.e**(-z)) def fit(xtrain,ytrain): epoch=20 b=0 lr=0.1 weights=np.zeros(4) N = len(xtrain) for _ in range(epoch): # Gradient Descent y_hat=np.zeros([67,1]) for i in range(N): y_hat[i][0]=np.sum(sigmoid(np.dot(xtrain[i], weights)+b)) t=np.dot(xtrain.T, y_hat - ytrain) t=t.reshape(4,) weights =weights- lr * t / N b=b-lr*np.sum(y_hat-ytrain)/N return weights,b def predict(X,weights,b): # Predicting with sigmoid function z = np.dot(X, weights)+b # Returning binary result return [1 if i > 0.5 else 0 for i in sigmoid(z)] def accuracy(ypred,y_test): count=0 for i in range(len(ypred)): if(ypred[i]==y_test[i]): count=count+1 return (count/len(ypred))*100 def plot_confusion(y_pred,y_test): data = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(data, columns=np.unique(y_test), index = np.unique(y_test)) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' plt.figure(figsize = (10,7)) sn.set(font_scale=1.4)#for label size sn.heatmap(df_cm, cmap="Reds", annot=True,annot_kws={"size": 16})# font size data=pd.read_csv("D:/Machine Learning/Assignments/iris.csv") df=data.iloc[0:100,:] x=df[['SL','SW','PL','PW']] y=df[['SPECIES']] y['SPECIES']=y['SPECIES'].map({'Iris-setosa':0,'Iris-versicolor':1}) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33) print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) X_train=X_train.to_numpy() X_test=X_test.to_numpy() y_train=y_train.to_numpy() y_test=y_test.to_numpy() weights,b=fit(X_train,y_train) ypred=predict(X_test,weights,b) print(ypred) acc=accuracy(ypred,y_test) recall = recall_score(y_test, ypred, average='weighted') precision = precision_score(y_test, ypred, average='weighted') plot_confusion(ypred,y_test) def counter_loop(): old_stdout = sys.stdout result = StringIO() sys.stdout = result print("\nHere we will use Iris dataset, its first 100 samples") print("\nEpoch=20 and learning rate=0.1") print("\nThe weight matrix we obtained is ",weights) print("\nThe bias value we obtained is ",b) print("\nThe accuracy of model we obtained is",acc) print("\nThe recall value obtained is ",recall) print("\nThe recall value obtained is ",precision) result_string = result.getvalue() counter.value = result_string # read output button.disable() app = App(title="Logistic Regression Algorithm", width=1000, height=500,) counter = Text(app, text="Logistic Regression Algorithm",size = 20, font = "Times New Roman", color="blue") button = PushButton(app, command=counter_loop, text ="Accuracy") app.display() '''def main(): data=pd.read_csv("D:/Machine Learning/Assignments/iris.csv") df=data.iloc[0:100,:] x=df[['SL','SW','PL','PW']] y=df[['SPECIES']] y['SPECIES']=y['SPECIES'].map({'Iris-setosa':0,'Iris-versicolor':1}) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33) print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) X_train=X_train.to_numpy() X_test=X_test.to_numpy() y_train=y_train.to_numpy() y_test=y_test.to_numpy() weights,b=fit(X_train,y_train) print("The weight matrix we obtained is") print(weights) print("The bias value we obtained is") print(b) ypred=predict(X_test,weights,b) print(ypred) print("The accuracy of model we obtained is") acc=accuracy(ypred,y_test) print(acc) plot_confusion(ypred,y_test) if __name__=='__main__': main()'''
#Assistive Tech Group 2019 # __init__(self, id, lat, lon) # updateLocation(self,latitude, longitude) class Guide: def __init__(self, GUIDEID, name, latitude, longitude):# Guide(GUIDEID, latitude, longitude) self.GUIDEID = GUIDEID self.latitude = latitude self.longitude = longitude self.name = name def updateLocation(self,latitude,longitude): self.latitude = latitude self.longitude = longitude
from django.contrib import admin from django.urls import path from django.conf.urls import url, include from QuoteeApp import views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.conf.urls.static import static app_name='QuoteeApp' urlpatterns = [ path('Quote', views.Quote, name='Quote'), path('register', views.register, name='register'), path('admin/', admin.site.urls,name='admin'), path('',views.index,name='index'), path('addquote',views.addquote,name='addquote'), path('registrations',views.registrations,name="registrations"), path('login',views.login,name='login'), path('logmein_p',views.logmein_p), path('feedback',views.feedback,name='feedback'), path('thanks',views.thanks,name='thanks'), path('success',views.success,name='success'), path('logmeout_p',views.logmeout_p,name='logmeout_p'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
class Tweet: def __init__(self, tweet, who, score): self.tweet = tweet self.who = who self.score = score def __str__(self): return self.tweet + " - " + self.who + " - " + str(self.score) def __iter__(self): return iter([self.tweet, self.who, str(self.score)])
class BallotTreeNode: def __init__(self, candidateString, candidateDictionary): self.votesThatPassHere = 0 self.candidateString=candidateString self.candidateDictionary=candidateDictionary self.children={} def addBallot(self, remainingBallot): self.votesThatPassHere+=1 #we've gone the ballot as deep as it can go if(len(remainingBallot)==0): return #we check whether we've already had a ballot like this if(remainingBallot[0] in self.children): #if so, we just recursively add a ballot without our current level self.children[remainingBallot[0]].addBallot(remainingBallot[1:]) else: #if not, we first have to add this possible child to our children self.children.update({remainingBallot[0] : BallotTreeNode(remainingBallot[0], self.candidateDictionary)}) #then continue adding self.children[remainingBallot[0]].addBallot(remainingBallot[1:]) def updateCandidates(self, remainder): #iterate over all the children for candidateStr in self.children: #this gets copied over every iteration tempRemainder=remainder #if the candidate that we're iterating over isn't lost if(not self.candidateDictionary[candidateStr].lost): #then we add to their votes self.candidateDictionary[candidateStr].votes+= tempRemainder * self.candidateDictionary[candidateStr].weight * self.children[candidateStr].votesThatPassHere #we have to update the remaining value of the ballot going this way tempRemainder*=1-self.candidateDictionary[candidateStr].weight #we check whether we're done with this ballot: either this child has no children and the remainder of the ballot is therefore exhausted or the remaining value of this ballot is 0 if(len(self.children[candidateStr].children)>0 and tempRemainder>0): #we continue deeper only if we're not done self.children[candidateStr].updateCandidates(tempRemainder) def getNumOkay(self): #recursibe depth first search on the number of ballots not exhausted (easier than the other way around) if(self.candidateDictionary[self.candidateString].lost): sum=0 for child in self.children: sum+=self.children[child].getNumOkay() return sum else: return self.votesThatPassHere
''' ############################### PYSKELWAYS ##################################### A software for hypergraph extraction from a binarised image TODOLIST : * Put small functions in miscfunc, or create two func files * Put CORRECTION IN A NEW MODULE * REPAIR SPLIT (Connexion unbreakable, wrong connection broken when clicked) * Reduce pickle size ? note : the structure for _ in range(1): is just to wrap the code with a proper IDE use M.dirP to see what is in an object ! ''' ######################### IMPORTATIONS ######################################### for _ in range(1): # Permet simplement de faire un repliement ### PYSKELFRAC ### import PySkelFrac.classes as c ### All Objects and their properties import PySkelFrac.Miscfunc as M ### Most functions I coded #import PySkelFrac.QGISsave as Q ### Save datas as QGIS SHAPE #import PySkelFrac.Addproperties as AdP ### LIBRAIRIES SCIENTIFIQUES UTILES DANS LE MAIN ### import numpy as np import cv2 ### LIBRAIRIES UTILITAIRES (MANIPULATION FICHIERS) ### import pickle # enregistrement de variables python, via "dump" et "load" import os # exploration de fichiers from pathlib import Path # Permet de gérer le fait d'être sous PC et LINUX from copy import deepcopy # permet d'éviter les problemes de "pointeurs", en recopiant les vlaeurs lcas ### PRINTS ### import matplotlib as mpl import matplotlib.pylab as pl import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle from matplotlib.lines import Line2D from matplotlib.collections import LineCollection from matplotlib.ticker import FormatStrFormatter import matplotlib.ticker as ticker SIZETICKS=20 SIZEFONT=25 LEGENDSIZE=20 LEGENDHANDLELENGTH=2 plt.rc('text', usetex=True) plt.rc('font', family='serif',size=SIZEFONT) plt.rc('xtick', labelsize=SIZETICKS) plt.rc('ytick', labelsize=SIZETICKS) plt.rc('figure',figsize = (10, 10)) plt.rcParams.update({'figure.autolayout': True}) plt.rcParams['text.latex.preamble']=[r"\usepackage{amsmath} \usepackage{libertine}"] ticksfontProperties = {'family':'sans-serif','sans-serif':['Helvetica'], 'weight' : 'medium', 'size' : SIZETICKS} params = {'legend.fontsize': LEGENDSIZE, 'legend.handlelength': LEGENDHANDLELENGTH} plt.rcParams.update(params) CMAP= mpl.cm.get_cmap('jet') CMAP.set_under('w',1.) import warnings #warnings.filterwarnings("ignore") #Uncomment to remove warning messages print('warning ignored !') for _ in range(1): # fonctions en plus from scipy.optimize import curve_fit def split(event,x,y,flags,param): ''' Action when there is a click on the split interface ''' global AllPlaces global AllArcs global img global voiesWidth if event == cv2.EVENT_LBUTTONDOWN: a,b,c = cv2.resize(np.rot90(imglink[xm:xM,ym:yM,:],k=flip),(winsize,winsize))[y,x,:] if a + b*255 + c* 255 *255 -1>=0: P=AllPlaces.list[a + b*255 + c* 255 *255 -1] if not P.ModifiedPlace: L =P.Links[0] ### AJOUTE DES EXTREMITES P.Extremities.append([L[0],L[2]]) P.Extremities.append([L[1],L[3]]) ### AJOUT DE l'INFO DANS LES ARCS A = AllArcs.list[L[0]] if L[2]=='first': A.FirstLink= ['Extremity'] else : A.LastLink = ['Extremity'] A = AllArcs.list[L[1]] if L[3]=='first': A.FirstLink= ['Extremity'] else : A.LastLink = ['Extremity'] ### SUPPRESSION DU LIEN if L[2] == 'first': pt1 = AllArcs.list[L[0]].XYNoPlace[0 ,:] else : pt1 = AllArcs.list[L[0]].XYNoPlace[-1,:] if L[3] == 'first': pt2 = AllArcs.list[L[1]].XYNoPlace[0 ,:] else : pt2 = AllArcs.list[L[1]].XYNoPlace[-1,:] pts = np.array([pt1,pt2]).astype(np.int32) img = cv2.polylines(img ,[pts],0,(255,255,255),4*voiesWidth) P.Links=[] P.ModifiedPlace=True def link(event,x,y,flags,param): ''' Action when click on link function ''' global listpts global P global Nimg global winsize if event == cv2.EVENT_LBUTTONDOWN: v = cv2.resize(imglink[ym:yM,xm:xM,:],(winsize,winsize) )[y,x,0] if v!=0: listpts.append(int(v-1)) E= P.Extremities[v-1] if E[1].lower()=='first': pt = AllArcs.list[E[0]].XYNoPlace[0,:] else : pt = AllArcs.list[E[0]].XYNoPlace[-1,:] Nimg = cv2.circle(Nimg ,(int(pt[0]),int(pt[1])),2*voiesWidth,(255 ,255,255),-1) def MKDIR(fold): try: os.mkdir(fold) except BaseException as E : print('no folder created :',E) ######################## INITIALISATION DES DONNEES ############################ ### NOM DE L'IMAGE ### imgname = "9recto3_proc-Exemple.jpg" # The name of the image we are analyzing Workfold = Path('/media/pa/Storage/Paul_VALCKE_THESE_FULL/0--IMAGES/QUALITYSQUEL/DONE') # The folder the image is stocked SavedBase ='Results/Gorgones/' # Where the result will be placed ### CREATION DU DICTIONNAIRE DE PARAMETRES "p" ### for _ in range(1): p={} ### PARAMETRES IMAGE p['resize']=1 # Réduit la dimension de l'image si nécessaire. ça va beaucoup plus vite ainsi, mais on perd en précision. >1 pour réduire p['typicallength']=10 # Taille typique (en pixel) des "artefacts", soit les erreurs de binarisation. 10 c'est raisonnable p['threshold']=15 #p['treshold']=127 # Threshold "réappliqué" (meme sur une image déja thresholdé). 127 (la moitiée) c'est bien p['Splitexterior']=True # Permet de prendre les branches qui composent l'enveloppe p['Splitall']=True # Permet aussi de récuperer les toutes branches dans les trous. ça ralenti pas mal p['Cdiff']=0.9 # Fait diffuser la courbure pour trouver les vrais extrenums dans le split. p['Ndiff']=100 # Pareil ### PARAMETRES ARCS p['Kmin']= 1.1 # Rapport de taille minimum pour les arcs-impasse. En dessous de 1 ils sont tous gardé, plus c'est grand moins y'en a ### PARAMETRE SCORE LINK p['refereepoint']=True # Si True, on considère un point à 'refereedist' fois la distance de la place comme référent, on s'écarte plus quoi p['refereedist'] =1.1 # Voir au dessus p['delta']=0 # Si !=0 (doit etre <1), déplace un peu le point pour le 'raytracing' dans les calculs de score ### CHOIX DU SCORE p['ScoreMode']="+" # NOT USED ANYMORE, SCORE ONLY WITH p['crit'] p['coeffs'] = {'D1' : 0, 'D2' : 0, 'DCenter' : 0, 'Rarc1' : 0, 'Rarc2' : 0, 'inLen' : 0, 'inMinD' : 0, 'inVarD' : 0, 'Ang12' : 0, 'Ang1' : 0, 'Ang2' : 0, 'inDintegrale' : 0, 'Outlen' : 1, 'OutDintegrale': 0,} p['crit']='Outlen' ### SPLIT VISUALISATION winsize=1150 p['voiesWidth']=0.25 p['rotate'] = False # Not sur if used anymore ? rotate=True;flip = -1 # Same for _ in range(1): Savefold = Path(SavedBase+imgname.split('.')[0]) p['image'] = imgname.split('.')[0] p['imageformat']= imgname.split('.')[-1] p['workfold'] = Workfold p['savefold'] = Savefold MKDIR(SavedBase) MKDIR( str(p['savefold'] )) MKDIR(str(Path(str(p['savefold'] /'PicklePRE')))) MKDIR(str(Path(str(p['savefold'] /'Pickle' )))) MKDIR(str(Path(str(p['savefold'] /'QGIS' )))) ### PREPARATION DES DONNEES INITIALES ### try : print('Try to reload old datas...') ''' Try to get the datas of previous runs''' IMG = pickle.load(open(str(p['savefold'] / 'PicklePRE/IMG.p' ),'rb')) AllContours = pickle.load(open(str(p['savefold'] / 'PicklePRE/AllContours.p'),'rb')) try: AllArcs = pickle.load(open(str(p['savefold'] / 'PicklePRE/AllArcs1.p' ),"rb")) AllPlaces = pickle.load(open(str(p['savefold'] / 'PicklePRE/AllPlaces1.p' ),"rb")) except BaseException: AllArcs = pickle.load(open(str(p['savefold'] / 'PicklePRE/AllArcs.p' ),"rb")) AllPlaces = pickle.load(open(str(p['savefold'] / 'PicklePRE/AllPlaces.p' ),"rb")) print('loaded !') except BaseException : '''Recreate base datas''' print('DATA NOT EXISTING YET !') IMG =c.Image(p) # FIRST IMAGE EXTRACTION AllContours =c.Contours(IMG,p) # CONTOURS EXTRACTION AllContours.SplitContours(p) # CONTOURS SPLIT AllArcs = c.Arcs(IMG,AllContours,p) # ARCS EXTRACTION AllPlaces= c.Places(IMG,AllArcs,p) # PLACES EXTRACTION AllPlaces=M.PrepareScore(IMG,AllArcs,AllPlaces,p) # POTENTIALLINK SCORE EXTRACTION pickle.dump(AllArcs, open(str(p['savefold'] / 'PicklePRE/AllArcs.p') ,"wb")) pickle.dump(IMG, open(str(p['savefold'] / 'PicklePRE/IMG.p') ,"wb")) pickle.dump(AllContours , open(str(p['savefold'] / 'PicklePRE/AllContours.p'),"wb")) pickle.dump(AllPlaces , open(str(p['savefold'] / 'PicklePRE/AllPlaces.p') ,"wb")) for P in AllPlaces.list : P.ThereisnoLink=False AllArcs,AllPlaces = M.LinkByScore(IMG,AllArcs,AllPlaces,p) ################################################################################ ################################################################################ ################################################################################ for _ in range(1):### SPLIT ### voiesWidth=int(np.median([A.Rmean for A in AllArcs.list if A.Usedinvoie])*p['voiesWidth']) repair = True while repair : # ACTUALISATION DES VOIES for A in AllArcs.list: A.Usedinvoie=False AllVoies = c.Voies(AllArcs,p) AllPlaces.AddExtremities(AllArcs,AllVoies,p) # CREATION DE LA CARTE for _ in range(1): # AJOUT DU FOND img = np.zeros((IMG.Y,IMG.X,3),np.uint8) img[:,:,0]=IMG.original[:,:,0].T img[:,:,1]=IMG.original[:,:,1].T img[:,:,2]=IMG.original[:,:,2].T imglink = np.zeros((IMG.Y,IMG.X,3),np.uint8) # Image des liens # AJOUT DES LIENS for i,P in enumerate(AllPlaces.list) : if len(P.Links): L = P.Links[0] if L[2] == 'first': pt1 = AllArcs.list[L[0]].XYNoPlace[ 0,:] else : pt1 = AllArcs.list[L[0]].XYNoPlace[-1,:] if L[3] == 'first': pt2 = AllArcs.list[L[1]].XYNoPlace[ 0,:] else : pt2 = AllArcs.list[L[1]].XYNoPlace[-1,:] pts = np.array([pt1,pt2]).astype(np.int32) img = cv2.polylines(img ,[pts],0,(0 , 0 , 0 ),voiesWidth*4) imglink = cv2.polylines(imglink,[pts],0,((i+1) % 255, (i+1) // 255%255 ,(i+1) // (255*255)),voiesWidth*4) # AJOUT DES VOIES colormax = pl.cm.jet( np.linspace(0,1,1+len(AllVoies.list) ) ) for i,V in enumerate(AllVoies.list) : pts=np.vstack(( V.XY[:,0], V.XY[:,1])).T.reshape(-1,2).astype(np.int32) G = int(colormax[i,1]*255) B = int(colormax[i,2]*255) R = int(colormax[i,0]*255) img = cv2.polylines(img, [pts],0,(R,G,B),voiesWidth) # INITIALISATION DE L'INTERFACE for _ in range(1): d = int(np.amin((IMG.X,IMG.Y))/2) xm=int(IMG.Y/2)-d+1 xM=int(IMG.Y/2)+d-1 ym=int(IMG.X/2)-d+1 yM=int(IMG.X/2)+d-1 exit = False cv2.namedWindow( 'image') cv2.setMouseCallback('image',split) while not exit: # SPLITTING # Retournement IMGSHOW= img[xm:xM,ym:yM,0:]*1 if rotate : IMGSHOW=np.rot90(IMGSHOW,k=flip) cv2.imshow('image',cv2.resize(IMGSHOW,(winsize,winsize))) k = cv2.waitKey(1) & 0xFF # Gestion des touches de direction for _ in range(1): plus = int((xM-xm)*0.1) if k == ord('p') : xm += plus; xM -= plus; ym += plus; yM -= plus; if k == ord('m') : xm -= plus xM += plus ym -= plus yM += plus up = ord('s') left = ord('d') right = ord('q') down = ord('z') deltaT= int((xM-xm)*0.1 ) if k == left : xm-=deltaT;xM-=deltaT # left if k == up : ym+=deltaT;yM+=deltaT # up if k == right : xm+=deltaT;xM+=deltaT # right if k == down : ym-=deltaT;yM-=deltaT # down if k == ord('h') : xm=int(IMG.Y/2)-d+1 Xm=int(IMG.Y/2)+d-1 ym=int(IMG.X/2)-d+1 Ym=int(IMG.X/2)+d-1 if k == 27 : exit = True;repair = False # exit if xm<= 0 : xm=1 if xM>=IMG.Y : xM=IMG.Y-1 if ym<= 0 : ym=1 if yM>=IMG.X : yM=IMG.X-1 cv2.destroyAllWindows() pickle.dump(AllArcs , open(str(p['savefold'] / 'PicklePRE/AllArcs1.p'),"wb")) pickle.dump(AllPlaces, open(str(p['savefold'] / 'PicklePRE/AllPlaces1.p') ,"wb")) for _ in range(1):### LINK ### # Refresh des voies for A in AllArcs.list: A.Usedinvoie=False AllVoies = c.Voies(AllArcs,p) AllPlaces.AddExtremities(AllArcs,AllVoies,p) # Creation de l'image for _ in range(1): # image orginale en fond img = np.zeros((IMG.Y,IMG.X,3),np.uint8)+255 img[:,:,0]=IMG.original[:,:,0].T img[:,:,1]=IMG.original[:,:,1].T img[:,:,2]=IMG.original[:,:,2].T ''' img[:,:,0]=REAL[:,:,0].T img[:,:,1]=REAL[:,:,1].T img[:,:,2]=REAL[:,:,2].T ''' colormax = pl.cm.jet( np.linspace(0,1,1+len(AllVoies.list) ) ) for i,V in enumerate(AllVoies.list) : pts=np.vstack(( V.XY[:,0], V.XY[:,1])).T.reshape(-1,2).astype(np.int32) G = int(colormax[i,1]*255) B = int(colormax[i,2]*255) R = int(colormax[i,0]*255) img = cv2.polylines(img, [pts],0,(R,G,B),voiesWidth) # CORRECTION PAR PLACE print('Number of place to correct :',len([P for P in AllPlaces.list if (not len(P.Links) and len(P.Extremities)>1 and not P.ThereisnoLink)])) for index,P in enumerate( [P for P in AllPlaces.list if (not len(P.Links) and len(P.Extremities)>1 and not P.ThereisnoLink)]) : Nimg = np.copy(img) imglink = np.zeros_like(img) for i,E in enumerate(P.Extremities): # Ajout des cercles if E[1].lower()=='first': pt = AllArcs.list[E[0]].XYNoPlace[0,:] else : pt = AllArcs.list[E[0]].XYNoPlace[-1,:] Nimg = cv2.circle(Nimg ,(int(pt[0]),int(pt[1])),2*voiesWidth,(127+30*i ,127-10*i,127+10*i),-1) imglink = cv2.circle(imglink,(int(pt[0]),int(pt[1])),2*voiesWidth,(i+1,0,0),-1) # Coordonnées xm = np.amax((int(P.XY[0,0]-IMG.X/10), 0 )) xM = np.amin((int(P.XY[0,0]+IMG.X/10),IMG.X )) ym = np.amax((int(P.XY[0,1]-IMG.Y/10), 0 )) yM = np.amin((int(P.XY[0,1]+IMG.Y/10),IMG.Y )) listpts = [] cv2.namedWindow('image') cv2.setMouseCallback('image',link) exit = False while not exit: IMGSHOW= Nimg[ym:yM,xm:xM,:]*1 cv2.imshow('image',cv2.resize(IMGSHOW,(winsize,winsize))) k = cv2.waitKey(1) & 0xFF # Gestion des touches de direction for _ in range(1): deltaT= int((xM-xm)*0.1 ) deltaZ= 0.05 if k == ord('p'): xm = xm + IMG.X*deltaZ xM = xM - IMG.X*deltaZ ym = ym + IMG.Y*deltaZ yM = yM - IMG.Y*deltaZ if k == ord('m'): xm = xm - IMG.X*deltaZ xM = xM + IMG.X*deltaZ ym = ym - IMG.Y*deltaZ yM = yM + IMG.Y*deltaZ if k == ord('z') : xm-=deltaT;xM-=deltaT # left if k == ord('d') : ym+=deltaT;yM+=deltaT # up if k == ord('s') : xm+=deltaT;xM+=deltaT # right if k == ord('q') : ym-=deltaT;yM-=deltaT # down if k == ord('h') : xm = 0;xM = IMG.X;ym = 0;yM = IMG.Y # home xm = int(np.amin((np.amax((0 ,xm)),IMG.X))) ym = int(np.amin((np.amax((0 ,ym)),IMG.Y))) xM = int(np.amax((np.amin((IMG.X,xM)),0 ))) yM = int(np.amax((np.amin((IMG.Y,yM)),0 ))) if k == ord('o'): P.ThereisnoLink=True exit=True if k == ord('r'): try: E= P.Extremities[listpts[0]] if E[1].lower()=='first': pt = AllArcs.list[E[0]].XYNoPlace[0,:] else : pt = AllArcs.list[E[0]].XYNoPlace[-1,:] Nimg = cv2.circle(Nimg ,(int(pt[0]),int(pt[1])),2*voiesWidth,(0 ,0,0),-1) listpts=[] except BaseException: print('No Reinitialisation possible !') if k == 27 : exit = True # Ajout du lien if len (listpts)==2: P.Links=[[P.Extremities[listpts[0]][0], P.Extremities[listpts[1]][0], P.Extremities[listpts[0]][1].lower(), P.Extremities[listpts[1]][1].lower()]] L=P.Links[0] if L[2] == 'first': pt1 = AllArcs.list[L[0]].XYNoPlace[0 ,:] else : pt1 = AllArcs.list[L[0]].XYNoPlace[-1,:] if L[3] == 'first': pt2 = AllArcs.list[L[1]].XYNoPlace[0 ,:] else : pt2 = AllArcs.list[L[1]].XYNoPlace[-1,:] pts = np.array([pt1,pt2]).astype(np.int32) img = cv2.polylines(img ,[pts],0,(0,0,0),voiesWidth) if L[2]=='first': AllArcs.list[ L[0] ].FirstLink=[L[1],L[3]] else : AllArcs.list[ L[0] ]. LastLink=[L[1],L[3]] if L[3]=='first': AllArcs.list[ L[1] ].FirstLink=[L[0],L[2]] else : AllArcs.list[ L[1] ]. LastLink=[L[0],L[2]] del P.Extremities[np.amax(listpts)] del P.Extremities[np.amin(listpts)] break cv2.destroyAllWindows() pickle.dump(AllArcs , open(str(p['savefold'] / 'PicklePRE/AllArcs1.p'),"wb")) pickle.dump(AllPlaces , open(str(p['savefold'] / 'PicklePRE/AllPlaces1.p') ,"wb")) ################################################################################ ################################################################################ ################################################################################ for A in AllArcs.list: A.Usedinvoie=False AllVoies = c.Voies(AllArcs,p) AllPlaces.AddExtremities(AllArcs,AllVoies,p) AllArcs, AllVoies = M.UpgradeArcsVoies(IMG,AllArcs,AllVoies) #### GENERATION OF A MAP OF THE RESULT ######################################### for _ in range(1):### CARTE COMPLETE voiesWidth=int(np.median([A.Rmean for A in AllArcs.list if A.Usedinvoie])*p['voiesWidth']) ### MAP WITH IMAGE img = np.zeros((IMG.X,IMG.Y,3),np.uint8)+255 img[:,:,0]=IMG.original[:,:,0] img[:,:,1]=IMG.original[:,:,1] img[:,:,2]=IMG.original[:,:,2] colormax = pl.cm.jet( np.linspace(0,1,1+len(AllVoies.list) ) ) for i,V in enumerate(AllVoies.list) : pts=np.vstack(( V.XY[:,1], V.XY[:,0])).T.reshape(-1,2).astype(np.int32) G = int(colormax[i,1]*255) B = int(colormax[i,2]*255) R = int(colormax[i,0]*255) img = cv2.polylines(img, [pts],0,(R,G,B),voiesWidth) cv2.imwrite(str(p['savefold'] / 'VoiesMAP.jpg'),img)
import os.path # create link in windows # run cmd as administrator # mklink broken_link C:\\not-exist FILENAMES = [ __file__, os.path.dirname(__file__), os.sep, 'broken_link', ] for file in FILENAMES: print(f'File : {file}') print(f'Absolute : {os.path.isabs(file)}') print(f'Is File? : {os.path.isfile(file)}') print(f'Is Dir? : {os.path.isdir(file)}') print(f'Is Link? : {os.path.islink(file)}') print(f'Mountpoint? : {os.path.ismount(file)}') print(f'Exists? : {os.path.exists(file)}') print(f'Link Exists? : {os.path.lexists(file)}') print()
# -*- coding:utf-8 -*- # __author__ = 'gupan' import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, BASE_DIR) from common.iniParser import IniParser import json conf_path = BASE_DIR + '\\conf\\testInfo.ini' # print(BASE_DIR, conf_path) # 获取测试链接主页 cf = IniParser(conf_path) base_url = cf.get_item('url', 'baseUrl') # 判断发送测试报告使用哪一种邮箱 email_type = cf.get_item('emails', 'email_type') email_server = json.loads(cf.get_item('emails', 'email_dic'))[email_type] # 获取邮箱发件人账号密码 email_sender = cf.get_item('emails', 'sender') email_sender_pwd = cf.get_item('emails', 'sender_pwd') # 获取邮件收件人账号 email_receivers = json.loads(cf.get_item('emails', 'receivers'))
import sys sys.path.append('./lib') sys.path.append('./utils') from productos import findByCodigo # Cantidad de stock de un producto def stock(): print('Introduzca el codigo del producto que desea ver el stock: ') producto = findByCodigo(input('~~>')) print() print(producto["nombre"]) print() print('STOCK ', producto['stock']) print() return ''
""" This module deals with processing the verb conjugation forms. """ from wiktionary_parser.sections import FTSection from wiktionary_parser.formating_type import RegexFT class NormalVerbConjugation(object): def __init__(self, plain, third, third_past, past_part, pres_part): self.plain = plain self.third = third self.third_past = third_past self.past_part = past_part self.pres_part = pres_part def summary(self): out = [] out.append('I %s (present)' % self.plain) out.append('He %s (present)' % self.third) out.append('He %s (past)' % self.third_past) out.append('He is %s (present participle)' % self.pres_part) out.append('He has %s (past participle)' % self.past_part) return '\n'.join(out) class ToBeVerbConjugation(object): """ I think this is only used for "to be". """ def __init__(self, plain, first, second, third, first_past, second_past, past_part, pres_part): self.plain = plain self.first = first self.second = second self.third = third self.first_past = first_past self.second_past = second_past self.past_part = past_part self.pres_part = pres_part def summary(self): out = [] out.append('to %s' % self.plain) out.append('I %s (present)' % self.first) out.append('You %s (present)' % self.second) out.append('He %s (present)' % self.third) out.append('I %s (past)' % self.first_past) out.append('You %s (past)' % self.second_past) out.append('He is %s (present participle)' % self.pres_part) out.append('He has %s (past participle)' % self.past_part) return '\n'.join(out) class ModalVerbConjugation(object): def __init__(self, plain, past, negative): self.plain = plain self.past = past self.negative = negative def summary(self): out = [] out.append('He %s eat (present)' % self.plain) out.append('He %s eat (past)' % self.past) out.append('He %s eat (negative present)' % self.negative) return '\n'.join(out) class AuxiliaryVerbConjugation(object): def __init__(self, plain, third, past): self.plain = plain self.third = third self.past = past def summary(self): out = [] out.append('I %s (present)' % self.plain) out.append('He %s (present)' % self.third) out.append('He %s (past)' % self.past) return '\n'.join(out) class simpleVerbConjugationSection(FTSection): name = 'Verb Conjugation Section' def process_data(self, data): word = self.get_property('word') plain = data.get('plain', None) third = data.get('third', None) past = data.get('past', None) past_part = data.get('past_part', None) pres_part = data.get('pres_part', None) stem = data.get('stem', None) ending = data.get('ending', None) modal = ('modal' in data) to_be = ('to_be' in data) auxiliary = ('auxiliary' in data) if to_be: data.pop('to_be') conj = ToBeVerbConjugation(**data) elif modal: data.pop('modal') conj = ModalVerbConjugation(**data) elif auxiliary: data.pop('auxiliary') conj = AuxiliaryVerbConjugation(**data) else: if stem is not None: if ending == 'e': plain = stem + 'e' past = stem + 'ed' pres_part = stem + 'ing' elif ending == 'y': plain = stem + 'y' third = stem + 'ies' past = stem + 'ied' elif ending == 'es': plain = stem third = stem + 'es' elif len(ending) == 1: # Make sure that the ending is the same as the last letter of the stem. if ending != stem[-1] and not (ending == 'k' and stem[-1] == 'c'): raise StandardError("stem is %s and ending is %s" % (stem, ending)) plain = stem past = stem + ending + 'ed' pres_part = stem + ending + 'ing' else: raise StandardError('Verb template does not match.') if plain is None: plain = word.title if third is None: third = plain + 's' if past is None: past = plain + 'ed' if past_part is None: past_part = past if pres_part is None: pres_part = plain + 'ing' conj = NormalVerbConjugation(plain, third, past, past_part, pres_part) if word.conjugations is None: word.conjugations = [] word.conjugations.append(conj) fts = [] fts.append(RegexFT( description="Regular", slug="regular", regex="^{{verb(?P<regular>)}}$", correct=True, )) fts.append(RegexFT( description="Regular (2)", slug="regular2", regex="^{{verb(?P<regular>)\|regular=true}}$", correct=True, )) fts.append(RegexFT( description="The pagename is not the base verb.", slug="pagename_not_base", regex="^{{verb\|(?P<plain>[\w\s-]+)}}$", correct=True, )) fts.append(RegexFT( description="Ending adjustment", slug="end adjust", regex="^{{verb\|(?P<stem>[\w\s-]+)\|(?P<ending>[\w]+)}}$", correct=True, )) fts.append(RegexFT( description="Past tense is the same as past participle", slug="past_is_past_part", regex="^{{verb\|(?P<plain>[\w\s-]+)\|(?P<third>[\w\s-]+)\|(?P<past>[\w\s-]+)\|(?P<pres_part>[\w\s-]+)}}$", correct=True, )) fts.append(RegexFT( description="Irregular", slug="irregular", regex="^{{verb2?\|(?P<plain>[\w\s-]+)\|(?P<third>[\w\s-]+)\|(?P<past>[\w\s-]+)\|(?P<past_part>[\w\s-]+)\|(?P<pres_part>[\w\s-]+)}}$", correct=True, )) fts.append(RegexFT( description="Irregular", slug="irregular", regex="^{{verb3(?P<to_be>)\|(?P<plain>[\w\s-]+)\|(?P<first>[\w\s-]+)\|(?P<second>[\w\s-]+)\|(?P<third>[\w\s-]+)\|(?P<first_past>[\w\s-]+)\|(?P<second_past>[\w\s-]+)\|(?P<past_part>[\w\s-]+)\|(?P<pres_part>[\w\s-]+)}}$", correct=True, )) fts.append(RegexFT( description="Modal", slug="modal", regex="^{{verb4(?P<modal>)\|(?P<plain>[\w\s-]+)\|(?P<past>[\w\s-]+)\|(?P<negative>[\w\s'-]+)}}$", correct=True, )) fts.append(RegexFT( description="Modal", slug="modal", regex="^{{verb5(?P<auxiliary>)\|(?P<plain>[\w\s-]+)\|(?P<third>[\w\s-]+)\|(?P<past>[\w\s'-]+)}}$", correct=True, ))
def get_min_coin_change(arr , target): min_coin = target if target in arr: return 1 else: for coin in [ _ for _ in arr if _ < target ]: res = 1 + get_min_coin_change( arr , target - coin) if res < min_coin: min_coin = res return res print get_min_coin_change( [1,2,3,4,10] , 5 ) print get_min_coin_change( [ 1,2,3,4,6,5,10] , 5 )
import pygame class Janela: def __init__(self, x, y, title): self.size = (x,y) self.title = title def main(): game = Janela(800,600,"Oi, sou o Pygame.") pygame.display.set_caption(game.title) pygame.display.set_mode(game.size) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = false if __name__ == "__main__": pygame.init() main()
""" Created on Sat Aug 29 11:13:10 2020 @author: sds """ # how to use e.g. in spyder # import modules import numpy as np import hiddensmmodel # load data: nparray without timestamp T = 10000 data = np.loadtxt('example-data.txt')[:T] # train model model = hiddensmmodel.Hsmm(data) # estimated state sequenece to evaluate model.states
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('dancers', '0014_tour_is_published'), ] operations = [ migrations.RemoveField( model_name='atl', name='dancer', ), migrations.AddField( model_name='atl', name='dancer1', field=models.TextField(default=1, max_length=300, verbose_name='\u041f\u0430\u0440\u0442\u043d\u0435\u0440 1'), preserve_default=False, ), migrations.AddField( model_name='atl', name='dancer2', field=models.TextField(default=1, max_length=300, verbose_name='\u041f\u0430\u0440\u0442\u043d\u0435\u0440 2'), preserve_default=False, ), ]
import screen screen.clear() def print_models(unprinted_designs, completed_models): # Simulate printing each design, until none are left. print("\nUnprinted Designs:") while unprinted_designs: current_design = unprinted_designs.pop() #Simulate creating 3D print from the design print("\tPrinting model: " + current_design.title()) completed_models.append(current_design) def show_completed_Models(completed_models): # Show all the models that are printed. print("\nThe following models have been printed:") for completed_model in completed_models: print("\t" + completed_model.title()) # Start some designs that need to be printed. unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs[:], completed_models) show_completed_Models(completed_models)
# -*- coding: utf-8 -*- import json import urllib import urllib2 import sys sys.path.insert(1, '../genuzot') import helperFunctions as Helper from sefaria.model import * apikey = Helper.apikey server = Helper.server structs = {} structs = { "nodes" : [] } def intro_basic_record(): return { "title": "Haamek Davar Intro", #"titleVariants": [""], "sectionNames": ["content"], "categories": ["Musar"], "schema" : { "titles" : [ { "lang" : "en", "text" : "Haamek Davar Intro", "primary" : True }, { "lang" : "he", "text" : u"הקדמת העמק דבר על התורה", "primary" : True } ], "nodeType" : "JaggedArrayNode", "depth" : 1, "addressTypes": ["Integer"], "sectionNames" :["content"], "key" : "Haamek Davar Intro" } } def createBookRecord(book_obj): url = 'http://' + server + '/api/v2/raw/index/' + book_obj["title"].replace(" ", "_") indexJSON = json.dumps(book_obj) values = { 'json': indexJSON, 'apikey': apikey } data = urllib.urlencode(values) print url, data req = urllib2.Request(url, data) try: response = urllib2.urlopen(req) print response.read() except HTTPError, e: print 'Error code: ', e.code def open_file(): with open("introduction.txt", 'r') as filep: file_text = filep.read() ucd_text = unicode(file_text, 'utf-8').strip() save_file(ucd_text) def save_file(intro): text_whole = { "title": "Haamek Davar Intro", "versionTitle": "", "versionSource": "", "language": "he", "text": intro, } Helper.mkdir_p("preprocess_json/") with open("preprocess_json/Haamek_Davar_intro.json", 'w') as out: json.dump(text_whole, out) with open("preprocess_json/Haamek_Davar_intro.json", 'r') as filep: file_text = filep.read() createBookRecord(intro_basic_record()) Helper.postText("Haamek Davar Intro", file_text, False) def index(): structs["nodes"].append({ "titles": [{ "lang": "en", "text": "Haamek Davar Intro", "primary": True }, { "lang": "he", "text": u"הקדמת העמק דבר על התורה", "primary": True }], "nodeType": "ArrayMapNode", "includeSections": True, "depth": 0, "wholeRef": "Haamek Davar Intro" }) pmap = { 'Genesis': "Bereshit", 'Exodus': "Shemot", 'Leviticus': "Vayikra", 'Numbers': "Bamidbar", 'Deuteronomy': "Devarim" } for chumash in ['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy']: structs["nodes"].append({ "sharedTitle": pmap[chumash], "nodeType": "ArrayMapNode", "includeSections": True, "depth": 0, "wholeRef": "Haamek Davar on " + chumash }) root = JaggedArrayNode() root.add_title("Haamek Davar Torah", "en", primary=True) root.add_title(u"העמק דבר על התורה", "he", primary=True) root.key = "Haamek Davar Torah" root.depth = 1 root.sectionNames = ["Chumash"] root.addressTypes = ["Integer"] root.validate() index = { "title": "Haamek Davar Torah", "categories": ["Musar"], "default_struct": "content", "alt_structs": {"content": structs}, "schema": root.serialize() } createBookRecord(index) if __name__ == '__main__': open_file() #opens file and posts it index()
def isLeap(year: int): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True return False year = int(input()) print('YES' if isLeap(year) else 'NO')
import socket import threading import SocketServer import time import random import sys import os list_ip = [] def init_list_ip(): list_ip = [] return None def remove_client_ip(ip_client): list_ip.remove(ip_client) if len(list_ip) == 0: return 1 else: return None def add_client_ip(ip_client): list_ip.append(ip_client) return None def remove_file(ddrr): print 'Deleted ' + ddrr os.remove(ddrr) return None def send_list(f, connection): #print len(f) for i in f: element_length(connection, i) connection.sendall(str(len(i))) connection.sendall(i) return None def element_length(connection, nm): if len(nm) > 9: connection.sendall('2') elif len(nm) > 99: connection.sendall('3') elif len(nm) > 999: connection.sendall('4') elif len(nm) > 9999: connection.sendall('5') else: connection.sendall('1') return None def list_all(connection): for f_1, f_2, f_3 in os.walk('C:\Users\Coordinator\Desktop\S\McNapster\Server_Database'): nm = print_name(f_1) element_length(connection, nm) connection.sendall(str(len(nm))) connection.sendall(nm) element_length(connection, f_2) connection.sendall(str(len(f_2))) if len(f_2) != 0: send_list(f_2, connection) element_length(connection, f_3) connection.sendall(str(len(f_3))) if len(f_3) != 0: send_list(f_3, connection) element_length(connection, 'DONE***DONE***DONE') connection.sendall('18') connection.sendall('DONE***DONE***DONE') return None def check_file_name_exist(arg_n): f_dir = [] drr = None actual_name = None for f_1, f_2, f_3 in os.walk('C:\Users\Coordinator\Desktop\S\McNapster\Server_Database'): if len(f_2) != 0: for d in f_2: f_dir.append(d) for dr in f_dir: f_dir = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\%s' % (dr) f = os.listdir(f_dir) for fl in f: if arg_n == fl: drr = dr actual_name = fl return 1, drr, actual_name return 0, drr, actual_name def print_name(f): f_dir = '' n = 1 for i in f: if n > (len('C:\Users\Coordinator\Desktop\S\McNapster')+ 1): f_dir = f_dir + i n = n + 1 n = n + 1 #print f_dir + ':' return f_dir def send_file(connection, arg_n, ddrr): # Send a file over a socket print 'Server openning file : %s' % (arg_n) name = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\%s' % (ddrr) + '\%s' % (arg_n) if ('wma' in arg_n) or('mp3' in arg_n) or ('mp4' in arg_n)or ('mov' in arg_n)or ('wmv' in arg_n): nn = 'rb' elif ('bmp' in arg_n)or ('jpg' in arg_n): nn = 'rb' else: nn = 'rb' try: f1 = open(name, nn) f1.seek(0, os.SEEK_END) size = f1.tell() print size connection.sendall(str(size)) f1.seek(0, 0) i = 1 sum_bytes = 0 lines = f1.readlines() for line in lines: print 'Sending Line', i, ' with ', len(line), ' bytes. sum_bytes = ', sum_bytes #connection.sendall('CONTINUESENDING') connection.sendall(line) i = i+1 sum_bytes = sum_bytes + len(line) print '------' print ' sum_bytes = ', sum_bytes #connection.sendall('PLZCEASESENDING') connection.sendall('^^DONE+DONE/DONE-DONE^^') f1.close() if(size == sum_bytes): #connection.sendall(('SERVER: Server sent file with ' + str(size) + ' bytes')) print 'Server sent file with ', sum_bytes/(1000*1000), ' Megabytes' return 1 else: print 'ERROR' return 0 except SystemError: print ' Except Error' #connection.sendall(" Error. Something went wrong somewhere. Try Again") return 0 return 0 def file_receive(sock, arg_n): iss = 0 mss = '' nn = '' for i in arg_n: if iss == 1: mss = mss + i if i == '.': iss = 1 if mss == 'mov' or mss == 'wmv': nn = 'wb' name = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\Vidoes\%s' % (arg_n) elif mss == 'wma' or mss == 'mp3' or mss == 'mp4': nn = 'wb' name = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\Music\%s' % (arg_n) elif mss == 'jpg' or mss == 'bmp': nn = 'wb' name = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\Pictures\%s' % (arg_n) elif mss == 'txt' or mss == 'py' or mss == 'c': nn = 'wb' name = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\Files\%s' % (arg_n) else: nn = 'wb' name = 'C:\Users\Coordinator\Desktop\S\McNapster\Server_Database\Files\%s' % (arg_n) try: size = sock.recv(64) print size f1 = open(name, nn) i = 1 quit_bit = 0 sum_bytes = 0 # Receive the data in small chunks and write it to a file # the file is is known in advance to be 16,958,907 bytes while True: data = sock.recv(4096) if '^^DONE+DONE/DONE-DONE^^' in data: new_data = '' n = 0 for iii in data: if n < (len(data) - 23): new_data = new_data + iii n = n + 1 data = new_data quit_bit = 1 #print '----------------' if data: # write the data to the file f1.write(data) i = i + 1 sum_bytes = sum_bytes + len(data) print 'received chunk ', i, 'with ', len(data), ' bytes, ', \ ' sum_bytes = ', sum_bytes, ' size', size if quit_bit: break else: print 'received line with no data ?? ' print ' sum_bytes = ', sum_bytes break print '------' print 'sum_bytes = ', sum_bytes f1.close if(quit_bit == 1): #data = sock.recv(128) #print data print 'Received file with', sum_bytes, ' bytes, Closing file ', arg_n return 1, name else: print '**ERROR**' return 0, name except SystemError: #data = sock.recv(64) #print data print " Error. Something went wrong somewhere. Try Again" return 0, name return None, name def get_command(connection, client_address): while True: try: data = connection.recv(64) #print 'Received data : "%s"' % data if data == 'LIST-ALL': connection.sendall('\nSERVER: Received LIST-ALL command from client') list_all(connection) elif data == 'READ': connection.sendall('\nSERVER: Received READ command from client') #receive the arguments arg_name = connection.recv(128) ixi, ddrr, actual_n = check_file_name_exist(arg_name) #print ixi if ixi == 0: connection.sendall('SERVER: $ERROR$ File ' + arg_name + ' does not exist') #return 0 else: connection.sendall('SERVER: Recieved File name ' + arg_name + ' to be transferred') xx = send_file(connection, arg_name, ddrr) print '^^----******+++++*******----^^' if xx == 1: connection.sendall('SERVER: File ' + arg_name + ' has been sent successfully') #print '1' else: connection.sendall('SERVER: **ERROR**: File transfer unsuccessful, Try Again') #print '0' print '^^----******+++++*******----^^' elif data == 'WRITE': connection.sendall('\nSERVER: Received WRITE command from client') #receive the arguments data = connection.recv(64) if 'ERROR$' in data: print data else: arg_name = data connection.sendall('\nSERVER: Recieved name ' + arg_name) sx, nname = file_receive(connection, arg_name) if sx == 1: connection.sendall('\nSERVER: File ' + arg_name + ' has been recieved succesfully') else: remove_file(nname) connection.sendall('SERVER: $ERROR$: File transfer unsuccessful, Try Again') elif data == 'BYE': print '\nSERVER: Client left the Server: ', client_address quit_check = remove_client_ip(client_address) #print list_ip #print quit_check #This method will remove this client ip address from a list containing all ip addresses of clients that are conneted to server #When there are no elements left in the list then server knows that no clients are connected to server and thus it QUITs n close server if quit_check == 1: return 1 else: connection.close() return None elif data == 'CONNECT': connection.sendall('\nClient is now connected to the server') add_client_ip(client_address) else: connection.sendall('\nSERVER: Invalid Command') except SystemError: connection.sendall(" Error. Something went wrong somewhere") break return 0 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): cur_thread = threading.current_thread() # identify current thread thread_name = cur_thread.name # get thread-number in python print '\nServer Thread %s receives request' % thread_name a = 0 while a == 0: try: print 'Server receives connection from ', self.client_address a = get_command(self.request, self.client_address) if a: break finally: # Clean up the connection # this section 'finally' is 'ALWAYS' executed print '******************************************************' print 'Server Thread %s terminating connection' % thread_name self.request.close() #print '\nServer Thread %s sleeping for 30 seconds' #time.sleep(30) #print '\nServer Thread %s terminating' % thread_name class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass if __name__ == "__main__": # Port 0 means to select an arbitrary unused port HOST, PORT = "localhost", 4000 print "\nStart Threaded-Server on PORT %s " % PORT server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=server.serve_forever) # Terminate the server when the main thread terminates # by setting daemon to True server_thread.daemon = True server_thread.start() print "Main Server using thread %s " % server_thread.name # sleeping the server thread will keep the server alive print 'Main Server thread sleeping' while True: answer = raw_input(">>") if answer.upper() == 'QUIT': print "Shutting Down Server for upgrade..\n%s clients need to be closed" % str(len(threading.enumerate())-2) #server_thread.close() break print 'Main server thread shutting down the server and terminating' server.shutdown()
import heapq import sys input = sys.stdin.readline heap = [] tot = int(input()) for i in range(tot): num = int(input()) if num == 0: if len(heap) == 0: print(0) else: print(heapq.heappop(heap)) else: heapq.heappush(heap, num)
#coding: UTF-8 import sys sys.path.append('../') import jieba jieba.load_userdict("slackbot/plugins/extra_dict/custom_dict.txt") jieba.load_userdict("slackbot/plugins/extra_dict/dict.txt") import jieba.analyse import re from slackbot.bot import respond_to from slackbot.bot import listen_to ANSWER_LIST = [] @respond_to(u'jieba') def jieba_message(message): seg_list = jieba.cut("我超級喜歡吃茄子", cut_all=False) message.reply(u"Default Mode: " + "/ ".join(seg_list)) @listen_to(u'jieba') def jieba_l_message(message): seg_list = jieba.cut("我超級喜歡吃茄子", cut_all=False) message.reply(u"Default Mode: " + "/ ".join(seg_list)) ## 取得 quizmaster 丟出的題目字串,解析出問題及選項 @respond_to(unicode("題目", 'utf-8') + ' (.*)', re.DOTALL) def receive_question(message, question): # if message._client.users[message._get_user_id()][u'name'] == "quizmaster": print isinstance(message.body['text'], unicode) m = re.match(u"(.*) \[(\d+)\] (.*) ### (.*) \[END\]", message.body['text']) quiz_no = m.group(2) question = m.group(3) options = {} for item in m.group(4).split(','): index, value = item.split(':') options[index] = value seg_list = jieba.cut(question, cut_all=False) message.reply(u"text seg: " + "/ ".join(seg_list)) # word2vec @listen_to(unicode("題目", 'utf-8') + ' (.*)', re.DOTALL) def receive_question(message, question): # if message._client.users[message._get_user_id()][u'name'] == "quizmaster": print isinstance(message.body['text'], unicode) m = re.match(u"(.*) \[(\d+)\] (.*) ### (.*) \[END\]", message.body['text']) quiz_no = m.group(2) question = m.group(3) options = {} for item in m.group(4).split(','): index, value = item.split(':') options[index] = value seg_list = jieba.cut(question, cut_all=False) message.reply(u"text seg: " + "/ ".join(seg_list)) # word2vec ## 當 quizmaster 丟出 "機器人小朋友請搶答",請儘速把答案丟到 channel @listen_to(unicode("機器人小朋友請搶答", 'utf-8') +'$') def hello_send(message): # if message._client.users[message._get_user_id()][u'name'] == "quizmaster": reply_ans = "" for idx, ans in enumerate(ANSWER_LIST): reply_ans += str(idx + 1) + " : " + ans + ", " message.send("<@%s>: %s %s" % (PIX_INSPECTOR, unicode("請給分 ", 'utf-8'), reply_ans[:-2])) ANSWER_LIST[:] = [] # 幫按讚 @listen_to(unicode("題號", 'utf-8') + ' (.*)') def hey(message, ans_string): message.react('+1') # 回覆訊息範例 @respond_to('hello$', re.IGNORECASE) def hello_reply(message): message.reply('hello sender!')
import matplotlib.pyplot as plt import numpy as np import cPickle as pickle from matplotlib.backends.backend_pdf import PdfPages import scipy.stats pdf = PdfPages('SamplingRate' + '.pdf') a = pickle.load(open("Age_matched_w_inner_and_outer.p","r")) regions = ['left_frontal','right_frontal','left_parietal','right_parietal','occipital'] conditions = ['eo','ec'] for condition in conditions: fig = plt.figure(figsize=(8, 11)) fig.text(.5, .95, condition, horizontalalignment='center') subplot_index = 1 for region in regions: plt.subplot(3, 2, subplot_index) subplot_index += 1 LOW = [ a[subject][condition][region]['mse'] for subject in a if condition in a[subject] and a[subject]['Dx'] == 'CONTROL' and int(subject) > 1037] print "250:",[sub for sub in a if int(sub)>1037 and a[sub]['Dx']=='CONTROL'] # print "ADHD:", [subject for subject in a if condition in a[subject] # and a[subject]['Dx'] == 'ADHD'] HIGH = [ a[subject][condition][region]['mse'] for subject in a if condition in a[subject] and a[subject]['Dx'] == 'CONTROL' and int(subject) < 1038] print "500:",[sub for sub in a if int(sub) <= 1037 and a[sub]['Dx'] == 'CONTROL'] # All_subs # print "Controls:", [subject for subject in a if condition in a[subject] # and a[subject]['Dx'] == 'CONTROL'] average_LOW= np.mean(LOW,0) average_HIGH = np.mean(HIGH,0) # print "AVERAGE ADHD:", average_ADHD # print "AVERAGE CONTROL:", average_CONTROL LOW_stderr = scipy.stats.sem(average_LOW,0)#/np.sqrt(np.shape(average_ADHD)[0]) HIGH_stderr = scipy.stats.sem(average_HIGH,0)#/np.sqrt(np.shape(average_CONTROL[0])) #print scipy.stats.ttest_ind(LOW,HIGH, axis=0)[1] plt.errorbar(range(1,21),average_LOW, yerr=LOW_stderr, xerr=None, color="b") plt.errorbar(range(1,21),average_HIGH, yerr=HIGH_stderr, xerr=None, color="r") # plt.plot(range(1,21),average_ADHD,"r") # plt.plot(range(1,21),average_CONTROL,"b") # #plt.xlabel("Scale") # plt.ylabel("mSampEn") plt.title(region) plt.legend(['250Hz', '500Hz'], loc=4) pdf.savefig(fig) plt.close() pdf.close()
from django.db import models class Category(models.Model): title = models.CharField(max_length=255)
import torch import torch.nn as nn import logging logger = logging.getLogger(__name__) def get_concat(concat: str, embedding_dim: int): """ :param concat: Concatenation style :param embedding_dim: Size of inputs that are subject to concatenation :return: Function that performs concatenation, Size of concatenation output """ concat_func = None concat_dim = None if concat == 'simple': concat_func = lambda a, b: torch.cat((a, b), dim=1) concat_dim = 2 * embedding_dim elif concat == 'dif': # x = np.abs(a-b) concat_func = lambda a, b: (a - b).abs() concat_dim = 1 * embedding_dim elif concat == 'prod': # x = a * b concat_func = lambda a, b: a * b concat_dim = 1 * embedding_dim elif concat == 'dif-prod': # x = np.hstack((np.abs(a-b), a * b)) concat_func = lambda a, b: torch.cat(((a - b).abs(), a * b), dim=1) concat_dim = 2 * embedding_dim elif concat == '3d-prod': # x = np.hstack((a, b, a*b)) concat_func = lambda a, b: torch.cat((a, b, a * b), dim=1) concat_dim = 3 * embedding_dim elif concat == '3d-dif': # x = np.hstack((a, b, np.abs(a-b))) concat_func = lambda a, b: torch.cat((a, b, (a - b).abs()), dim=1) concat_dim = 3 * embedding_dim elif concat == '4d-prod-dif': # x = np.hstack((a, b, a*b, np.abs(a-b))) concat_func = lambda a, b: torch.cat((a, b, a * b, (a - b).abs()), dim=1) concat_dim = 4 * embedding_dim else: raise ValueError('Unsupported concat mode') logger.debug(f'concat_dim = {concat_dim} ({concat})') return concat_func, concat_dim def get_mlp(input_dim, output_dim, hidden_dim, hidden_layers_count=1, dropout_p=0., activation_cls=nn.ReLU): """ Generate a fully-connected layer (MLP) with dynamic input, output and hidden dimension, and hidden layer count. - when dropout_p > 0, then dropout is applied with given probability after the activation function. :param input_dim: :return: Sequential layer """ layers = [ # first layer nn.Linear(input_dim, hidden_dim), activation_cls(), ] if dropout_p > 0: layers.append(nn.Dropout(dropout_p)) for layer_idx in range(1, hidden_layers_count): layers.append(nn.Linear(hidden_dim, hidden_dim)), layers.append(activation_cls()), if dropout_p > 0: layers.append(nn.Dropout(dropout_p)) # last layer layers.append(nn.Linear(hidden_dim, output_dim)) # TODO fill linear layers # nn.init.xavier_normal_(self.classifier.weight) # Fills the input Tensor with values according to the method described in “Understanding the difficulty of training deep feedforward neural networks” - Glorot, X. & Bengio, Y. (2010), using a normal distribution. # kaiming_normal_ # Fills the input Tensor with values according to the method described in “Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification” - He, K. et al. (2015), using a normal distribution. return nn.Sequential(*layers)
import os import subprocess import sys def main(): cmd = sys.argv[1:] h_file = None try: index = cmd.index('-o') h_file = cmd[index+1] cmd[index+1] = os.path.dirname(h_file) except (ValueError, IndexError): pass p = subprocess.run(cmd, capture_output=True, text=True) if p.returncode: if p.stdout: sys.stderr.write('stdout:\n{}\n'.format(p.stdout)) if p.stderr: sys.stderr.write('stderr:\n{}\n'.format(p.stderr)) sys.exit(p.returncode) if h_file and h_file.endswith(('.fbs.h', '.fbs64.h')): cpp_file = '{}.cpp'.format(h_file[:-2]) with open(cpp_file, 'w') as f: f.write('#include "{}"\n'.format(os.path.basename(h_file))) sys.exit(0) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Thu Nov 14 21:04:47 2019 @author: Henri_2 """ from __future__ import print_function from keras.utils import np_utils import numpy """ This function cuts the notes list into "sequence_length" long sequences and their respective outputs: X notes from the list and the X+1:th note as the output of the sequence. These sequences are used to train the network""" def make_sequence(note_tubles, n_unique, notenames, tubles_to_int): print('total length of training data:', len(note_tubles), ' notes') print('number of individual notes-duration combinations: ', n_unique) # cut the notes list into sequences of length sequence_length sequence_length = 50 net_input = [] output = [] for i in range(0, len(note_tubles) - sequence_length, 1): sequence_in = note_tubles[i: i + sequence_length] sequence_out = note_tubles[i + sequence_length] for key in sequence_in: net_input.append(tubles_to_int[key]) output.append(tubles_to_int[sequence_out]) patterns = int(len(net_input)/(sequence_length)) print(patterns) input_array = numpy.asarray(net_input) input_array = input_array.reshape(patterns, sequence_length, 1) #normalize the input input_array = input_array/float(n_unique) #convert the output to binary class matrix output = np_utils.to_categorical(output) return (input_array, output)
from django.urls import path from django.urls.resolvers import URLPattern from .views import dotaciones, insertar_dotacion, asignar_dotacion urlpatterns = { path('dotacion/', dotaciones, name='dotaciones_list' ), path('insertar_dotacion/', insertar_dotacion, name='insertar_dotacion' ), path('asignar_dotacion/', asignar_dotacion, name='asignar_dotacion' ), }
import random import hashlib def create_salt(): salt = '' seq = '0123456789abcdefghijklmnopqrstuvwxyz' rng = random.randint(5, 10) i = 0 while i < rng: i += 1 salt += random.choice(seq) return salt def hashed_password(password, salt): hashed_password = hashlib.sha256((salt + password).encode('utf8')).hexdigest() return hashed_password def allowed_file(filename): ALLOWED_EXTENSIONS = set(['mp3']) return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
from flask_restful import Resource from app.auth import authenticate class BasicProtectedResource(Resource): method_decorators = [authenticate]
from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium_api import * from utils import * class TreeholePage: __post_locator = (By.XPATH, '//ol[@class="commentlist"]/li[contains(@id, "comment")]') __open_comment_locator = (By.XPATH, '//div[@class="jandan-vote"]/a[@class="tucao-btn"]') __current_page_locator = (By.XPATH, '//span[@class="current-comment-page"]') __next_page_locator = (By.XPATH, '//a[@class="previous-comment-page"]') __previous_page_locator = (By.XPATH, '//a[@class="next-comment-page"]') __bad_content_locator = (By.XPATH, '//a[@class="view_bad"]') def __init__(self, driver, parse=True): driver.get('http://i.jandan.net/treehole') self.url = driver.current_url self.current_page_number = int(retain_number(wait_for_element_present( driver, self.__current_page_locator).text)) if parse: self.open_bad_content(driver) self.post_list = self.parse_post_list(driver) print(driver.page_source) def parse_post_list(self, driver): print("Parsing post list...") post_list = [] post_elements = wait_for_elements_present(driver, self.__post_locator, 'Obtaining posts...') for post_element in post_elements: post = self.Post(post_element, driver) post_list.append(post) print(post) # self.write_to_json(post_list) return post_list def go_to_next_page(self, driver, parse=True): scroll_to_and_click_button(driver, self.__next_page_locator) return TreeholePage(driver, parse) def go_to_previous_page(self, driver, parse=True): scroll_to_and_click_button(driver, self.__previous_page_locator) return TreeholePage(driver, parse) def open_bad_content(self, driver): try: bad_content_elements = wait_for_elements_present(driver, self.__bad_content_locator, timeout=3) for bad_content_element in bad_content_elements: scroll_to_element(driver, bad_content_element) bad_content_element.click() except TimeoutException: print("No bad content in this page.") def __eq__(self, other): if isinstance(other, TreeholePage): return self.url == other.url return False def __str__(self): return str(self.__dict__) def __repr__(self): return str(self.__dict__) def to_json(self): return self.__dict__ class Post: __user_locator = (By.XPATH, './b') __time_locator = (By.XPATH, './span[@class="time"]') __id_locator = (By.XPATH, './span[@class="righttext"]/a') __text_locator = (By.XPATH, './div[@class="commenttext"]/p') __oo_locator = (By.XPATH, './div[@class="jandan-vote"]//a[@class="comment-like like"]/following-sibling::span') __xx_locator = (By.XPATH, './div[@class="jandan-vote"]//a[@class="comment-unlike unlike"]/following-sibling::span') __comment_count_locator = (By.XPATH, './/a[@class="tucao-btn"]') __open_comment_locator = (By.XPATH, './div[@class="jandan-vote"]/a[@class="tucao-btn"]') __hot_comment_locator = (By.XPATH, './/div[@class="tucao-hot"]/div[@class="tucao-row"]') __comment_locator = (By.XPATH, './/div[@class="tucao-list"]/div[@class="tucao-row"]') def __init__(self, post_element, driver): self.post_user, self.post_time, self.post_id, self.post_oo, self.post_xx, self.post_text, self.comment_count, self.hot_comment_list, self.comment_list = self.parse_post( post_element, driver) def parse_post(self, post_element, driver): print("Parsing post...") post_user = wait_for_element_present(post_element, self.__user_locator).text post_time = wait_for_element_present(post_element, self.__time_locator).text.strip()[2:] post_id = wait_for_element_present(post_element, self.__id_locator).text post_oo = wait_for_element_present(post_element, self.__oo_locator).text post_xx = wait_for_element_present(post_element, self.__xx_locator).text post_text = '' post_text_elements = wait_for_elements_present(post_element, self.__text_locator) for post_text_element in post_text_elements: post_text += '\n' + post_text_element.text comment_list = [] hot_comment_list = [] comment_count = self.parse_comment_count(post_element) if comment_count != '0': self.open_comment_section(post_element, driver) print("Parsing comments...") comment_elements = wait_for_elements_present(post_element, self.__comment_locator) for comment_element in comment_elements: comment = self.Comment(comment_element, post_id) comment_list.append(comment) # list(set(comment_list)) try: print("Parsing hot comments...") hot_comment_elements = wait_for_elements_present(post_element, self.__hot_comment_locator, timeout=1) for hot_comment_element in hot_comment_elements: hot_comment = self.Comment(hot_comment_element, post_id, is_hot_comment=True) hot_comment_list.append(hot_comment) # list(set(hot_comment_list)) except TimeoutException: pass return post_user, post_time, post_id, post_oo, post_xx, post_text, comment_count, hot_comment_list, comment_list def parse_comment_count(self, post_element): comment_count_string = wait_for_element_present(post_element, self.__comment_count_locator).text return retain_number(comment_count_string) def open_comment_section(self, post_element, driver): print("Opening comment section...") element = wait_for_element_present(post_element, self.__open_comment_locator) scroll_to_element(driver, element) element.click() # scroll_to_and_click_button(post_element, self.__open_comment_locator) def __eq__(self, other): if isinstance(other, TreeholePage.Post): return self.post_id == other.post_id return False def __str__(self): return str(self.__dict__) def __repr__(self): return str(self.__dict__) def to_json(self): return self.__dict__ class Comment: __user_locator = (By.XPATH, './/div[@class="tucao-author"]/span') __id_locator = (By.XPATH, './/span[@class="tucao-id"]') __text_locator = (By.XPATH, './/div[@class="tucao-content"]') __oo_locator = (By.XPATH, './/span[@class="tucao-oo"]') __xx_locator = (By.XPATH, './/span[@class="tucao-xx"]') def __init__(self, comment_element, post_id, is_hot_comment=False, ): self.comment_user, self.comment_id, self.comment_oo, self.comment_xx, self.comment_text = self.parse_comment( comment_element) self.is_hot_comment = is_hot_comment self.post_id = post_id def parse_comment(self, comment_element): comment_user = wait_for_element_present(comment_element, self.__user_locator).text comment_id = wait_for_element_present(comment_element, self.__id_locator).text[1:] comment_text = '' comment_text_elements = wait_for_elements_present(comment_element, self.__text_locator) for comment_text_element in comment_text_elements: comment_text += '\n' + comment_text_element.text comment_oo = wait_for_element_present(comment_element, self.__oo_locator).text comment_xx = wait_for_element_present(comment_element, self.__xx_locator).text return comment_user, comment_id, comment_oo, comment_xx, comment_text def __eq__(self, other): if isinstance(other, TreeholePage.Post.Comment): return self.comment_id == other.comment_id return False def __str__(self): return str(self.__dict__) def __repr__(self): return str(self.__dict__) def to_json(self): return self.__dict__
from django.contrib import admin from goods.tasks import generate_static_index_html from django.core.cache import cache from .models import GoodsType, IndexPromotionBanner, IndexTypeGoodsBanner, IndexGoodsBanner, GoodsSKU, GoodsImage, Goods class BaseModelAdmin(admin.ModelAdmin): """ 抽象父管理类""" def save_model(self, request, obj, form, change): ''' 新增或更新表中数据时调用,重写''' super().save_model(request, obj, form, change) # 重新生成静态文件 generate_static_index_html.delay() # 清除首页的缓存数据 cache.delete("index_page_data") def delete_model(self, request, obj): ''' 删除表中数据时调用''' super().delete_model(request, obj) generate_static_index_html.delay() cache.delete("index_page_data") class IndexPromotionBannerAdmin(BaseModelAdmin): pass class GoodsTypeAdmin(BaseModelAdmin): pass class IndexGoodsBannerAdmin(BaseModelAdmin): pass class IndexTypeGoodsBannerAdmin(BaseModelAdmin): pass class GoodsSKUAdmin(BaseModelAdmin): pass class GoodsImageAdmin(BaseModelAdmin): pass class GoodsAdmin(BaseModelAdmin): pass admin.site.register(GoodsType, GoodsTypeAdmin) admin.site.register(IndexPromotionBanner, IndexPromotionBannerAdmin) admin.site.register(IndexGoodsBanner, IndexTypeGoodsBannerAdmin) admin.site.register(IndexTypeGoodsBanner, IndexTypeGoodsBannerAdmin) admin.site.register(GoodsSKU, GoodsSKUAdmin) admin.site.register(Goods, GoodsAdmin) admin.site.register(GoodsImage, GoodsImageAdmin)
class QuitException(Exception): def __init__(self, message: str = 'User exited current menu'): super().__init__(message) self.message = message def __repr__(self): return f'<QuitException: {self.message}>'
# Generated by Django 3.1.7 on 2021-06-17 23:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('frontend', '0001_initial'), ] operations = [ migrations.AddField( model_name='zinfo', name='percent', field=models.CharField(default='50%', max_length=10), preserve_default=False, ), ]
import numpy as np import pandas as pd import dlib import cv2 import os from scipy import interpolate class DlibVTExtractor(object): def __init__(self): pass def get_equi_dist(self, contour, M): contour = np.array(contour) d = np.diff(contour, axis=0) dist_from_vertex_to_vertex = np.hypot(d[:, 0], d[:, 1]) cumulative_dist_along_path = np.concatenate(([0], np.cumsum(dist_from_vertex_to_vertex, axis=0))) dist_steps = np.linspace(0, cumulative_dist_along_path[-1], M) contour = interpolate.interp1d(cumulative_dist_along_path, contour, axis=0)(dist_steps) return contour def prepare_train_data(self, src_dir, dst_dir): if not os.path.exists(dst_dir): os.mkdir(dst_dir) f1_files = [f for f in os.listdir(src_dir) if (f.endswith('.avi') and 'f1' in f)] f5_files = [f for f in os.listdir(src_dir) if (f.endswith('.avi') and 'f5' in f)] m3_files = [f for f in os.listdir(src_dir) if (f.endswith('.avi') and 'm3' in f)] avi_files = np.concatenate((f1_files, f5_files, m3_files)) with open(os.path.join(dst_dir, 'vt_shape_dlib.xml'), 'w') as out_xml: out_xml.write("<?xml version='1.0' encoding='ISO-8859-1'?>\n") out_xml.write("<?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?>\n") out_xml.write("<dataset>\n") out_xml.write("<name> Training VT </name>\n") out_xml.write("<images>\n") for file in avi_files: vid_name = os.path.join(src_dir, file) cap = cv2.VideoCapture(vid_name) fnum = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) gtname = os.path.join(src_dir, file[:-4] + '.csv') gt = pd.read_csv(gtname, header=None) gt = gt.iloc[:, :].values pnts = gt[:fnum, :160] lands = gt[:fnum, 161:] for f in range(fnum): ret, frame = cap.read() cv2.imwrite(os.path.join(dst_dir, file[:-4] + '_frame_' + str(f) + '.jpg'), frame) vt_cont = np.reshape(pnts[f, :], (80, 2), order='F') vt_cont = self.get_equi_dist(vt_cont, 80) vt_cont = np.array(vt_cont, dtype=np.int32) vt_land = np.reshape(lands[f, :], (6, 2), order='F') vt_land = np.array(vt_land, np.int32) x, y, w, h = cv2.boundingRect(vt_cont) out_xml.write("<image file='{}'>\n".format(file[:-4] + '_frame_' + str(f) + '.jpg')) out_xml.write("<box top='{}' left='{}' width='{}' height='{}'>\n".format(x - 5, y - 5, w + 10, h + 10)) for j in range(80): out_xml.write("<part name='{}' x='{}' y='{}'/>\n".format(str(j), vt_cont[j, 0], vt_cont[j, 1])) out_xml.write("</box>\n") out_xml.write("</image>\n") out_xml.write("</images>\n") out_xml.write("</dataset>\n") def train_shape_predictor(self, output_name, input_xml): print('[INFO] trining shape predictor....') # get the training options options = dlib.shape_predictor_training_options() options.tree_depth = 4 options.nu = 0.1 options.cascade_depth = 15 options.feature_pool_size = 400 options.num_test_splits = 100 options.oversampling_amount = 10 options.be_verbose = True options.num_threads = 4 # start training the model dlib.train_shape_predictor(input_xml, output_name, options) def train_shape_detector(self, output_name, input_xml): print('[INFO] training shape detector....') # get the training options options = dlib.simple_object_detector_training_options() options.add_left_right_image_flips = False options.C = 5 options.num_threads = 4 options.be_verbose = True # start training the model dlib.train_simple_object_detector(input_xml, output_name, options) if __name__=="__main__": estimator = DlibVTExtractor() estimator.prepare_train_data('data/usc-timit', 'data/dlib') estimator.train_shape_detector('models/dlib/dlib_vt_detector.svm', 'data/dlib/vt_shape_dlib.xml') estimator.train_shape_predictor('models/dlib/dlib_vt_predictor.dat', 'data/dlib/vt_shape_dlib.xml')
# -*- coding: utf-8 -*- """ This is part of WebScout software Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en Docs RU: http://hack4sec.pro/wiki/index.php/WebScout License: MIT Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en) Thread class for FuzzerHeaders module """ from __future__ import division import threading import Queue import time from requests.exceptions import ConnectionError from classes.Registry import Registry from libs.common import file_to_list class FuzzerHeadersThread(threading.Thread): """ Thread class for FuzzerHeaders module """ queue = None method = None url = None counter = None last_action = 0 def __init__(self, queue, domain, protocol, method, delay, counter, result): threading.Thread.__init__(self) self.queue = queue self.method = method.lower() self.domain = domain self.result = result self.counter = counter self.protocol = protocol self.done = False self.bad_words = file_to_list(Registry().get('wr_path') + "/bases/bad-words.txt") self.headers = self._get_headers() self.http = Registry().get('http') self.delay = int(delay) def _get_headers(self): return file_to_list(Registry().get('wr_path') + "/bases/fuzzer-headers.txt") def run(self): """ Run thread """ req_func = getattr(self.http, self.method) need_retest = False while True: self.last_action = int(time.time()) if self.delay: time.sleep(self.delay) try: if not need_retest: url = self.queue.get() for header in self.headers: try: resp = req_func( "{0}://{1}{2}".format(self.protocol, self.domain, url), headers={header.lower(): Registry().get('fuzzer_evil_value')}, #headers={header.lower(): Registry().get('config')['fuzzer']['headers_evil_value']}, ) except ConnectionError: need_retest = True self.http.change_proxy() continue if resp is None: continue if resp.status_code > 499 and resp.status_code < 600: self.result.append( {"url": url, "words": ["{0} Status code".format(resp.status_code)], "header": header} ) continue found_words = [] for bad_word in self.bad_words: if resp.content.lower().count(bad_word): found_words.append(bad_word) if len(found_words): self.result.append({"url": url, "words": found_words, "header": header}) self.counter.up() self.queue.task_done(url) need_retest = False except Queue.Empty: self.done = True break except BaseException as e: print url + " " + str(e) self.queue.task_done(url)
# import library import time import matplotlib import matplotlib.pylab as plt import serial # inisialisasi port serial s=serial.Serial('com6', 2400) def readlineCR(port): # Fungsi khusus buat baca feed data serial (string) dari vCOM rv = "" # dengan terminator carriage return (CR) / '\r' atau '' while True: ch = port.read() rv += ch if ch=='\r' or ch=='': return rv # Proses buat Figure grafik sama inisialisasi datanya fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax1.cla() ax1.set_title('Suhu vs Waktu') ax1.set_xlabel('Waktu (s)') ax1.set_ylabel('Suhu (C)') plt.ion() # Set interactive mode ON, so matplotlib will not be blocking the window plt.show(False) # Set to false so that the code doesn't stop here cur_time = time.time() ax1.hold(True) x, y = [], [] times = [time.time() - cur_time] # Create blank array to hold time values y.append(0) plt.grid(True, 'both') line1, = ax1.plot(times, y, 'ro-', label='Suhu') fig.show() fig.canvas.draw() background = fig.canvas.copy_from_bbox(ax1.bbox) # cache the background tic = time.time() i = 0 # Proses feeding data ke plot grafik while True: fields = int(float(readlineCR(s))) times.append(time.time() - cur_time) y.append(fields) # this removes the tail of the data so you can run for long hours. You can cache this # and store it in a pickle variable in parallel. if len(times) > 50: y.pop(0) times.pop(0) # axis plot adaptif terhadap data xmin, xmax, ymin, ymax = [min(times), max(times)+0.5, min(y)-5,max(y)+5] # feed the new data to the plot and set the axis limits again line1.set_xdata(times) line1.set_ydata(y) plt.axis([xmin, xmax, ymin, ymax]) # blit = true, ambil background, data aja yang di draw terus fig.canvas.restore_region(background) # restore background ax1.draw_artist(line1) # redraw just the points fig.canvas.blit(ax1.bbox) # fill in the axes rectangle fig.canvas.flush_events() i += 1
from os import path from numpy import dtype, fromfile __author__ = "Yuri E. Corilo" __date__ = "Jun 19, 2019" class ReadMidasDatFile(): ''' Reads Midas data files, works for both Predator Analysis data and Thermo DataStation ''' def __init__(self, filename_path): ''' Constructor ''' raise NotImplementedError("This class is not yet implemented, if you want to use it please contact the author at corilo@pnnl.gov or feel free to implement it") if not path.isfile(filename_path): raise Exception("File does not exist: "+ filename_path) self.filename_path = filename_path def read_file(self): data_file = open(self.filename_path, 'rb') # modo_de_ions = "POSITIVE ION MODE" d_params = self.parse_parameters(self.parameter_filename_location) transient_data = self.get_transient_data(data_file, d_params, d_params) return transient_data, d_params def get_transient_data(self, data_file, d_params): #dt = np.dtype('<f') if d_params.get("storage_type").split()[0] == "int": dt = dtype('i2') else: dt = dtype('<f') #dt = np.dtype(int) myarray = fromfile(data_file, dtype=dt) data_file.close() if d_params.get("storage_type").split()[0] == "int": return myarray * d_params.get("VoltageScale") else: return myarray def parse_parameter(self, f): output_parameters = {} output_parameters["filename_path"] = self.d_directory_location line = f.readline() while line != "Data:\n": if line[0:8] == "highfreq": final_frequency = float(line.split(":")[1]) output_parameters["exc_high_freq"] = final_frequency elif line[0:7] == "lowfreq": initial_frequency = float(line.split(":")[1]) output_parameters["exc_low_freq"] = initial_frequency elif line[0:9] == "sweeprate": sweeprate = float(line.split(":")[1]) output_parameters['sweeprate'] = sweeprate elif line[0:13] == "Source Coeff0": Acoef = float(line.split(":")[1]) output_parameters["Aterm"] = Acoef #print f.readline() elif line[0:13] == "Source Coeff1": output_parameters["Bterm"] = "Bcoef" elif line[0:13] == "Voltage Scale": voltage_scale = float(line.split(":")[1]) output_parameters["VoltageScale"] = voltage_scale elif line[0:9] == "Bandwidth": bandwidth = float(line.split(":")[1]) output_parameters["bandwidth"] = bandwidth elif line[0:11] == "Data Points": datapoints = float(line.split(":")[1]) output_parameters["number_data_points"] = datapoints elif line[0:12] == "Storage Type": storage_type = line.split(":")[1] output_parameters["storage_type"] = storage_type elif line[0:12] == "Trap Voltage": trap_voltage = float(line.split(":")[1]) #Bcoef = Bcoef*trap_voltage output_parameters["trap_voltage"] = trap_voltage line = f.readline() return output_parameters
import Queue #Global ALPHABET = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H',9:'I',10:'J', 11:'K',12:'L',13:'M',14:'N',15:'O',16:'P',17:'Q',18:'R',19:'S', 20:'T',21:'U',22:'V',23:'W',24:'X',25:'Y',26:'Z'} def senate(num, listSenators): q = Queue.PriorityQueue() order = list() # Put into PQ for i in range(num): q.put((-(listSenators[i]), ALPHABET[i+1])) while not q.empty(): num, letter = q.get() order.append(letter) num += 1 if num < 0: q.put((num, letter)) # print order newOrder = list() if len(order) % 2 == 0: for i in range(0,len(order)-1,2): newOrder.append(order[i]+order[i+1]) else: for i in range(0,len(order)-3,2): newOrder.append(order[i]+order[i+1]) newOrder.append(order[-3]) newOrder.append(order[-2]+order[-1]) return ' '.join(newOrder) #newOrder = list() # put together #for i in range(len(order)): # newOrder def main(): t = int(raw_input()) # read a line with a single integer for i in xrange(1, t + 1): numberSenators = int(raw_input()) listSen = [int(s) for s in raw_input().split(" ")] #print listSen order = senate(numberSenators, listSen) # word = aLastWord(raw_input()) print ("Case #{}: {}".format(i, order)) # raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. # t = int(raw_input()) # read a line with a single integer # for i in xrange(1, t + 1): # n, m = [int(s) for s in raw_input().split(" ")] # read a list of integers, 2 in this case # print "Case #{}: {} {}".format(i, n + m, n * m) # check out .format's specification for more formatting options if __name__=='__main__': main()
#这基本是一个标准的inorder traversal #对于BST而言,inorder traversal return的结果就是从小到大的 #这个code其实就是在94题标准的inorder traversal的基础上加了 def kthSmallest(self, root, k): stack = [] while True: while root: stack.append(root) root = root.left if not stack: return # the order of pop is the same as # BST order, so the first time will # pop the smallest element, and so on, # we track this pop operation, after k # times, we get the answer node = stack.pop() k -= 1 if k == 0: return node.val root = node.right
from setuptools import setup, find_packages version = '1.0b0' setup(name='fbimn.verteidigung', version=version, description="Verteidigungstermin Inhaltstyp", long_description="""Verteidigungstermin Archetype, basierend auf ATEvent. """, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Framework :: Plone", "Framework :: Zope2", "Framework :: Zope3", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='zope archetypes plone', author='Jakob Goepel', author_email='jgoepel at imn htwk-leipzig de', url='http://portal.imn.htwk-leipzig.de', license='GPL', packages=find_packages(exclude=['ez_setup']), namespace_packages=['fbimn'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', #'Products.AutocompleteWidget', 'Products.Archetypes', 'Products.ATContentTypes', 'Products.validation', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
def print_list(alist): for i in alist: if type(i) is list: print_list(i) else: print(i,end=' ') a=[3, 4, 5, 6, 7, 9, 11, 13, 15, 17] import random ta=[] for i in range(20): ta.append(random.randint(1,10000)) print(ta) tb=ta[:10] tb.sort() ta[:10]=tb tb=ta[10:] tb.sort(reverse=True) ta[10:]=tb print(ta) random.shuffle(a)#打乱顺序 print_list(a) print() a.sort()#默认升序 print_list(a) print() a.sort(reverse=True)#降序排序 print_list(a) print() """ lambda:这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数,是从LISP借用来的,可以用在任何需要函数的地方: >>> g = lambda x: x * 2 >>> g(3) 6 >>> (lambda x: x * 2)(3) 6 lambda表达式返回一个函数对象 例子: func = lambda x,y:x+y func相当于下面这个函数 def func(x,y): return x+y 注意def是语句而lambda是表达式 下面这种情况下就只能用lambda而不能用def [(lambda x:x*x)(x) for x in range(1,11)] """ a.sort(key=lambda x:len(str(x)))#自定义排序 print_list(a) print() print(a) """sorted返回新列表,并不对原列表修改""" a=[9, 7, 6, 5, 4, 3, 17, 15, 13, 11] b=sorted(a)#默认升序 print(a, ' ', b) print('id a:',id(a),'; id b:',id(b)) b=sorted(a, reverse=True) print(a, ' ', b) print('id a:',id(a),'; id b:',id(b)) """逆序排列""" a=[random.randint(50,100) for i in range(10)] print(a) a.reverse() print(a) """reserved :不对原列表修改,返回逆序后的迭代对象""" b=reversed(a) print(b) print(list(b)) print(b) for i in b:#b为迭代对象,之前list(b)访问过后,已经迭代结束,不能再次迭代 print(i,end=' ')
"""A note on keeping code DRY: here I would optimally create one function that can dynamically check different DB tables depending on which parameters are passed. For the sake of speed I'm not doing that here since I won't always need to check if the record is in the DB before returning the related object, e.g. in the case of getting a state object from the DB to create a relationship between the new address and the state. Also, this code assumes the front end would be checking input for formatting, e.g. making sure a zipcode is a 5 digit string. The ORM layer provides protection from SQL injection so there isn't any manual validation in that regard.""" import database_things as db def find_username(username, dbsession): """Checks the db if there is a username matching the passed parameter already and returns the username object. If there isn't, it writes the username to the db and returns the new username object.""" result = dbsession.query(db.User).filter_by(username=username).first() # Need to extract the object from the ORM result proxy. if result is None: # Create a new instance of user username_object = db.User(username) dbsession.add(username_object) return username_object else: # Assign the existing user object to the variable return result def find_city(city, dbsession): """Checks the db if there is a city matching the passed parameter already and returns the city object. If there isn't, it writes the city to the db and returns the new city object.""" # Since we're creating the FK relation based on ID, and hence the casing has no bearing on # whether the city record associates with the address, I'm upcasing the city to prevent dupes. city = str(city) city = city.upper() result = dbsession.query(db.City).filter_by(city_name=city).first() if result is None: # Create a new instance of city city_object = db.City(city) # I'm adding the city without committing the transaction since it would also # commit the address insert transaction that's still open in routes.py. dbsession.add(city_object) return city_object else: # Assign the existing user object to the variable return result def find_state(state, dbsession): """Fetches a state object by state abbreviation and returns it. Assumes that the caller gives it the abbreviation formatted like this: CA It doesn't check if the state is present first since the state menu is a dropdown so the user cannot submit an invalid state selection.""" return dbsession.query(db.State).filter_by(state_abbreviation=state).first() def find_zipcode(zipcode, dbsession): result = dbsession.query(db.Zipcode).filter_by(zipcode=zipcode).first() if result is None: # Create a new instance of zipcode zipcode_obj = db.Zipcode(zipcode) # I'm adding the city without committing the transaction since it would also # commit the address insert transaction that's still open in routes.py. dbsession.add(zipcode_obj) return zipcode_obj else: # Assign the existing user object to the variable return result
from flask import Flask, request, session, g, redirect, url_for, abort, render_template from flask.ext.sqlalchemy import SQLAlchemy import csv import os # creating the application app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) # databases init db = SQLAlchemy(app) # acode model '''class Acode(db.Model): id = db.Column(db.String(5), primary_key=True) resource = db.Column(db.String(100)) def __init__(self, id, resource): self.id = id; self.resource = resource; def __repr__(self): return 'key = {0} resource = {1}'.format(self.id, self.resource) ''' #db init def init_db2(): from models import Acode db.drop_all() db.session.commit() db.create_all() db.session.commit() with open('ocodes_raw.csv', 'rb') as csvfile: ocode_read = csv.reader(csvfile, delimiter=',') for row in ocode_read: print row[0] temp_code = Acode(row[0], row[1]) db.session.add(temp_code) db.session.commit() # db methods #def connect_db(): # return sqlite3.connect(app.config['DATABASE']) #@app.before_request #def before_request(): # g.db = connect_db() #@app.teardown_request #def teardown_request(exception): # db = getattr(g, 'db', None) # if db is not None: # db.close() @app.route('/') def index(): from a_forms import AcodeForm form = AcodeForm() return render_template('front.html', form=form, error=False) @app.route('/code', methods=['POST']) def redirect_code(): from a_forms import AcodeForm from models import Acode form = AcodeForm() ocode = request.form['code'] redir_url = Acode.query.filter_by(id=ocode).first() if redir_url is None: return render_template('front.html', form=form, error=True) else: return redirect(redir_url.resource) # return redir_url """ code snippet to hack around db @app.route('/adminhack') def fix_db(): from a_forms import AcodeForm from models import Acode bugged = Acode.query.get('129p') bugged.resource = 'http://files.axcesscapon.com/pdf/enrichments/ME01.pdf' db.session.commit() print "wololo" return "hello world" """ if __name__ == '__main__': app.run()
from flask import (Flask, g, render_template, flash, redirect, url_for, abort) from flask.ext.bcrypt import check_password_hash from flask.ext.login import (LoginManager, login_user, logout_user, login_required, current_user) from app import * import forms import models login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(userid): try: return models.User.get(models.User.id == userid) except models.DoesNotExist: return None @app.before_request def before_request(): """Connect to the database before each request.""" g.db = models.DATABASE g.db.connect() g.user = current_user @app.after_request def after_request(response): """Close the database connection after each request.""" g.db.close() return response @app.route('/user/<nickname>') def user_profile(nickname): user = models.User.get(models.User.nickname == nickname) if not user: flash('User could not be found.') else: profile = models.UserProfile.get(models.UserProfile.user == user) return render_template( 'user-profile.html', profile=profile, user=user) @app.route('/register', methods=('GET', 'POST')) def register(): form = forms.RegistrationForm() if form.validate_on_submit(): flash('Yay! You registered.', 'success') models.User.create_user( email=form.email.data, password=form.password.data) return redirect(url_for('index')) return render_template('register.html', form=form) @app.route('/logout') @login_required def logout(): logout_user() flash("You've been logged out.", 'success') return redirect(url_for('index')) @app.route('/members') def members(): user_data = models.User.select().where(models.User.confirmed == True) print(user_data) return render_template('members.html', rows=user_data) @app.route('/', methods=('GET', 'POST')) def index(): print(current_user) login_form = forms.LoginForm() if login_form.validate_on_submit(): try: user = models.User.get(models.User.email == login_form.email.data) except models.DoesNotExist: flash("Your email or password doesn't match.", 'error') else: if check_password_hash(user.password, login_form.password.data): login_user(user) print(current_user) flash("You've been successfully logged in!", 'success') return redirect(url_for('members')) else: flash("Your email or password doesn't match.", 'error') return render_template('index.html', form=login_form) if __name__ == '__main__': models.initialize('db_trendlinks.db') try: models.User.create_user( email='kenneth@teamtreehouse.com', password='password', admin=True ) except ValueError: pass app.run(debug=DEBUG, host=HOST, port=PORT)
from flask import Flask from flask_session import Session from flask_restful import Api from flask_cors import CORS from flask_socketio import SocketIO from routes import ResourceManager from models.User import User from .sockets import sockets from .redis import RedisSessionInterface from utils.database import init_default_content, clean_default_content from .database import URI_USED, init_db # import redis socketio = SocketIO(async_mode="gevent") class NeoAPI(object): def __init__(self, config): self.config = config self.app = Flask(__name__) self.app.config['SQLALCHEMY_DATABASE_URI'] = URI_USED self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False self.app.config['SECRET_KEY'] = config.neo_secret self.app.config["SESSION_TYPE"] = "null" from sockets import sockets as socket_blueprint self.app.register_blueprint(socket_blueprint) self.session = Session() self.app.session_interface = RedisSessionInterface() self.session.init_app(self.app) self.api = Api(self.app) CORS(self.app) ResourceManager.add_account_resources(self.api) ResourceManager.add_device_routes(self.api) ResourceManager.add_api_resources(self.api) ResourceManager.add_cookies_resources(self.api) ResourceManager.add_payment_resources(self.api) ResourceManager.add_circle_logic_resources(self.api) ResourceManager.add_circle_resources(self.api) ResourceManager.add_conversation_logic_resources(self.api) ResourceManager.add_conversation_resources(self.api) ResourceManager.add_media_resources(self.api) ResourceManager.add_media_logic_resources(self.api) ResourceManager.add_message_resources(self.api) ResourceManager.add_user_message_resources(self.api) ResourceManager.add_device_message_resources(self.api) socketio.init_app(self.app) init_db(self.app) def activate_testing(self): self.app.config['TESTING'] = True self.app.app_context().push() User.CreateNeoAdmin(self.config.admin_password) init_default_content(self.config.beta_user1_password, self.config.beta_user2_password) return self.app.test_client() def create_app(config): neo = NeoAPI(config) if config.use_redis: sockets.storage.set_conf(config.use_redis, config.redis_url) with neo.app.app_context(): User.CreateNeoAdmin(config.admin_password) init_default_content(config.beta_user1_password, config.beta_user2_password) return neo.app
import sqlite3 from flask import json, g def get_db(): db = getattr(g, '_database', None) if db is None: def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d db = g._database = sqlite3.connect('craftbeerpi.db') db.row_factory = dict_factory return db class DBModel(object): __priamry_key__ = "id" __as_array__ = False __order_by__ = None __json_fields__ = [] def __init__(self, args): self.__setattr__(self.__priamry_key__, args.get(self.__priamry_key__)) for f in self.__fields__: if f in self.__json_fields__: if args.get(f) is not None: if isinstance(args.get(f) , dict) or isinstance(args.get(f) , list) : self.__setattr__(f, args.get(f)) else: self.__setattr__(f, json.loads(args.get(f))) else: self.__setattr__(f, None) else: self.__setattr__(f, args.get(f)) @classmethod def get_all(cls): cur = get_db().cursor() if cls.__order_by__ is not None: cur.execute("SELECT * FROM %s ORDER BY %s.'%s'" % (cls.__table_name__,cls.__table_name__,cls.__order_by__)) else: cur.execute("SELECT * FROM %s" % cls.__table_name__) if cls.__as_array__ is True: result = [] for r in cur.fetchall(): result.append( cls(r)) else: result = {} for r in cur.fetchall(): result[r.get(cls.__priamry_key__)] = cls(r) return result @classmethod def get_one(cls, id): cur = get_db().cursor() cur.execute("SELECT * FROM %s WHERE %s = ?" % (cls.__table_name__, cls.__priamry_key__), (id,)) r = cur.fetchone() if r is not None: return cls(r) else: return None @classmethod def delete(cls, id): cur = get_db().cursor() cur.execute("DELETE FROM %s WHERE %s = ? " % (cls.__table_name__, cls.__priamry_key__), (id,)) get_db().commit() @classmethod def insert(cls, **kwargs): cur = get_db().cursor() if cls.__priamry_key__ is not None and kwargs.has_key(cls.__priamry_key__): query = "INSERT INTO %s (%s, %s) VALUES (?, %s)" % ( cls.__table_name__, cls.__priamry_key__, ', '.join("'%s'" % str(x) for x in cls.__fields__), ', '.join(['?'] * len(cls.__fields__))) data = () data = data + (kwargs.get(cls.__priamry_key__),) for f in cls.__fields__: if f in cls.__json_fields__: data = data + (json.dumps(kwargs.get(f)),) else: data = data + (kwargs.get(f),) else: query = 'INSERT INTO %s (%s) VALUES (%s)' % ( cls.__table_name__, ', '.join("'%s'" % str(x) for x in cls.__fields__), ', '.join(['?'] * len(cls.__fields__))) data = () for f in cls.__fields__: if f in cls.__json_fields__: data = data + (json.dumps(kwargs.get(f)),) else: data = data + (kwargs.get(f),) cur.execute(query, data) get_db().commit() i = cur.lastrowid kwargs["id"] = i return cls(kwargs) @classmethod def update(cls, **kwargs): cur = get_db().cursor() query = 'UPDATE %s SET %s WHERE %s = ?' % ( cls.__table_name__, ', '.join("'%s' = ?" % str(x) for x in cls.__fields__),cls.__priamry_key__) data = () for f in cls.__fields__: if f in cls.__json_fields__: data = data + (json.dumps(kwargs.get(f)),) else: data = data + (kwargs.get(f),) data = data + (kwargs.get(cls.__priamry_key__),) cur.execute(query, data) get_db().commit() return cls(kwargs)
import random as r import time as t def GenerateRandomIntArray(lenght): n = [] n = r.sample(range(0,20000),lenght) return n def bubbleSort(vetor): n = len(vetor) jCounter = 0 for i in range(n): for j in range(0, n - i - 1): jCounter += 1 if vetor[j] > vetor[j + 1]: vetor[j], vetor[j+1] = vetor[j+1], vetor[j] return ("Externo {}".format(i), "Interno {}".format(jCounter)) antes = t.time() print(bubbleSort(GenerateRandomIntArray(1000))) depois = t.time() total = (depois-antes)*1000 print(total)