repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
gohdan/DFC
known_files/hashes/core/model/modx/mail/phpmailer/language/phpmailer.lang-fa.php
114
ModX Revolution 2.5.0 = 71a9a71365fbadabd3c026814147a5ee ModX Revolution 2.3.3 = 8f4246cdb74b6ff5b2557a1cbbc1657b
gpl-3.0
lichunlincn/cshotfix
CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Editor/Injector/MonoCecil/Mono.Cecil/DeferredModuleReader.cs
486
using Editor_Mono.Cecil.PE; using System; namespace Editor_Mono.Cecil { internal sealed class DeferredModuleReader : ModuleReader { public DeferredModuleReader(Image image) : base(image, ReadingMode.Deferred) { } protected override void ReadModule() { this.module.Read<ModuleDefinition, ModuleDefinition>(this.module, delegate(ModuleDefinition module, MetadataReader reader) { base.ReadModuleManifest(reader); return module; }); } } }
gpl-3.0
UMN-Hydro/GSFLOW_pre-processor
python_scripts/MODFLOW_scripts/MODFLOW_NWT_lib_test.py
76197
# -*- coding: utf-8 -*- """ Created on Sun Sep 17 22:34:30 2017 MODFLOW_NWT_lib This library includes all the separate matlab functions for writing the different MODFLOW input files @author: gcng """ import numpy as np import pandas as pd # for data structures and reading in data from text file import matplotlib.pyplot as plt # matlab-like plots slashstr = '/' #%% # baesd on: write_nam_MOD_f2_NWT.m def write_nam_MOD_f2_NWT(GSFLOW_indir, GSFLOW_outdir, infile_pre, fil_res_in, sw_2005_NWT): # v2 - allows for restart option (init) # _NWT: from Leila's email, her work from spring 2017, incorporates # MODFLOW-NWT. # Edits made to Leila's version, which incorrectly called both (LPF, PCG) and UPW. # MODFLOW-NWT will default to MODFLOW-2005 if given LPF and PCG. # # sw_2005_NWT: 1 for MODFLOW-2005; 2 for MODFLOW-NWT algorithm (both can be # carried out with MODFLOW-NWT code) # # - directories # # MODFLOW input filesfil_res_in # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # infile_pre = 'test2lay_py' # - write to this file (within indir) fil_nam = infile_pre + '.nam' # all assumed to be in GSFLOW_dir fil_ba6 = infile_pre +'.ba6' if sw_2005_NWT == 1: fil_lpf = infile_pre +'.lpf' fil_pcg = infile_pre +'.pcg' elif sw_2005_NWT == 2: fil_upw = infile_pre +'.upw' fil_nwt = infile_pre +'.nwt' fil_oc = infile_pre +'.oc' fil_dis = infile_pre +'.dis' fil_uzf = infile_pre +'.uzf' fil_sfr = infile_pre +'.sfr' fil_res_out = infile_pre +'.out' # write to restart file # ------------------------------------------------------------------------ # -- .nam file with full paths fil_nam_0 = GSFLOW_indir + slashstr + fil_nam fobj = open(fil_nam_0, 'w+') fobj.write('LIST 7 ' + GSFLOW_outdir + slashstr + 'test.lst \n') # MODFLOW output file fobj.write('BAS6 8 ' + GSFLOW_indir + slashstr + fil_ba6 + '\n') if sw_2005_NWT == 1: fobj.write('LPF 11 ' + GSFLOW_indir + slashstr + fil_lpf + '\n') fobj.write('PCG 19 ' + GSFLOW_indir + slashstr + fil_pcg + '\n') elif sw_2005_NWT == 2: fobj.write('UPW 25 ' + GSFLOW_indir + slashstr + fil_upw + '\n') fobj.write('NWT 17 ' + GSFLOW_indir + slashstr + fil_nwt + '\n') fobj.write('OC 22 ' + GSFLOW_indir + slashstr + fil_oc + '\n') fobj.write('DIS 10 ' + GSFLOW_indir + slashstr + fil_dis + '\n') fobj.write('UZF 12 ' + GSFLOW_indir + slashstr + fil_uzf + '\n') fobj.write('SFR 13 ' + GSFLOW_indir + slashstr + fil_sfr + '\n') if len(fil_res_in) != 0: fobj.write('IRED 90 ' + fil_res_in + '\n'); fobj.write('IWRT 91 ' + GSFLOW_outdir + slashstr + fil_res_out + '\n') fobj.write('DATA(BINARY) 34 ' + GSFLOW_outdir + 'test.bud \n'); # MODFLOW LPF output file, make sure 34 is unit listed in lpf file!! fobj.write('DATA(BINARY) 51 ' + GSFLOW_outdir + slashstr + 'testhead.dat \n') # MODFLOW output file fobj.write('DATA(BINARY) 61 ' + GSFLOW_outdir + slashstr + 'uzf.dat \n') # MODFLOW output file fobj.write('DATA 52 ' + GSFLOW_outdir + slashstr + 'ibound.dat \n') # MODFLOW output file fobj.close() #%% # based on: write_dis_MOD2_f # write_dis_MOD (for 3D domains) # 11/17/16 # # v1 - 11/30/16 start to include GIS data for Chimborazo's Gavilan Machay # watershed; topo.asc for surface elevation (fill in bottom elevation # based on uniform thickness of single aquifer) def write_dis_MOD2_f(GSFLOW_indir, infile_pre, surfz_fil, NLAY, DZ, perlen_tr, sw_spinup_restart): # # ==== TO RUN AS SCRIPT =================================================== # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # # # infile_pre = 'test1lay'; # # NLAY = 1; # # DZ = 10; # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # # infile_pre = 'test2lay_py' # NLAY = 2 # DZ = [100, 50] # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # # perlen_tr = 365 # ok if too long # # GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/' # # # for various files: ba6, dis, uzf, lpf # surfz_fil = GIS_indir + 'topo.asc' # # surfz_fil = GIS_indir + 'SRTM_new_20161208.asc' # # # for various files: ba6, uzf # mask_fil = GIS_indir + 'basinmask_dischargept.asc' # sw_spinup_restart = 1 # 1: spinup (2 periods: steady-state and transient), 2: restart (1 period: transient) ## ========================================================================= # - write to this file # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; dis_file = infile_pre + '.dis' # - read in this file for surface elevation (for TOP(NROW,NCOL)) # surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; # - read in this file for elevation of layer bottoms (for BOTM(NROW,NCOL,NLAY)) # (layer 1 is top layer) botmz_fil = '' # - domain dimensions, maybe already in surfz_fil and botm_fil{}? # NLAY = 1; # NROW = 1058; # NCOL = 1996; # # - domain boundary (UTM zone 17S, outer boundaries) # north = 9841200; # south = 9835900; # east = 751500; # west = 741500; # # - space discretization # DELR = (east-west)/NCOL; # width of column [m] # DELC = (north-south)/NROW; # height of row [m] # DZ = 10; # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # DZ = [5; 5]; # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # - time discretization if sw_spinup_restart == 1: PERLEN = [1, perlen_tr]; # 2 periods: 1-day steady-state and multi-day transient elif sw_spinup_restart == 2: PERLEN = [perlen_tr]; # 1 period: multi-day transient comment1 = '# test file for Gavilan Machay' comment2 = '# test file' # - The following will be assumed: LAYCBD = np.zeros((1,NLAY), int); # no confining layer below layer ITMUNI = 4; # [d] LENUNI = 2; # [m] if sw_spinup_restart == 1: NPER = 2; # 1 SS then 1 transient SsTr_flag = ['ss', 'tr'] else: NPER = 1 # 1 transient SsTr_flag = ['tr'] NSTP = PERLEN TSMULT = 1 # must have daily time step to correspond with PRMS ## ------------------------------------------------------------------------ # -- Read in data from files f = open(surfz_fil, 'r') sdata = {} for i in range(6): line = f.readline() line = line.rstrip() # remove newline characters key, value = line.split(': ') try: value = int(value) except: value = float(value) sdata[key] = value f.close() NSEW = [sdata['north'], sdata['south'], sdata['east'], sdata['west']] NROW = sdata['rows'] NCOL = sdata['cols'] # - space discretization DELR = (NSEW[2]-NSEW[3])/NCOL # width of column [m] DELC = (NSEW[0]-NSEW[1])/NROW # height of row [m] TOP = np.genfromtxt(surfz_fil, skip_header=6, delimiter=' ', dtype=float) BOTM = np.zeros((NROW, NCOL, NLAY), float) BOTM[:,:,0] = TOP-DZ[0]; for ilay in range(1,NLAY): BOTM[:,:,ilay] = BOTM[:,:,ilay-1]-DZ[ilay] # -- Discretization file: fobj = open(GSFLOW_indir + slashstr + dis_file, 'w+') # fobj = open('/home/gcng/test.txt', 'w') fobj.write(comment1 + '\n'); fobj.write(comment2 + '\n'); _out = np.array([NLAY, NROW, NCOL, NPER, ITMUNI, LENUNI]) # for 1D arrays np.savetxt(fobj, _out[None], delimiter=' ', fmt='%5s %5s %5s %5s %5s %5s NLAY, NROW, NCOL, NPER, ITMUNI, LENUNI') np.savetxt(fobj, LAYCBD, delimiter=' ', fmt='%d') # fobj.write('CONSTANT %7.3f DELR\n' % (DELR)) # fobj.write('CONSTANT %7.3f DELC\n' % (DELC)) fobj.write('CONSTANT %g DELR\n' % (DELR)) fobj.write('CONSTANT %g DELC\n' % (DELC)) fobj.write('INTERNAL 1.0 (FREE) 0 TOP ELEVATION OF LAYER 1 \n'); np.savetxt(fobj, TOP, delimiter=' ', fmt='%10g') for ii in range(NLAY): fobj.write('INTERNAL 1.0 (FREE) 0 BOTM ELEVATION OF LAYER %d \n' % (ii+1)) np.savetxt(fobj, BOTM[:,:,ii], delimiter=' ', fmt='%10g') for ii in range(NPER): fobj.write(' %g %d %g %s PERLEN, NSTP, TSMULT, Ss/Tr (stress period %4d)\n' % (PERLEN[ii], NSTP[ii], TSMULT, SsTr_flag[ii], ii+1)) fobj.close() # -- plot domain discretization TOP_to_plot = TOP.copy() TOP_to_plot[TOP <= 0] == np.nan BOTM_to_plot = BOTM.copy() BOTM_to_plot[BOTM <= 0] == np.nan fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(2,2,1) im = ax.imshow(TOP_to_plot) im.set_clim(3800, 6200) # use im.get_clim() to get the limits and generalize fig.colorbar(im, orientation='horizontal') plt.title('TOP') for ilay in range(NLAY): plt.subplot(2,2,2+ilay) im = plt.imshow(BOTM_to_plot[:,:,ilay]) im.set_clim(3800, 6200) fig.colorbar(im, orientation='horizontal') plt.title('BOTM lay' + str(ilay+1)); # # figure # for ilay = 1:NLAY # subplot(2,2,double(ilay)) # if ilay == 1 # X = TOP - BOTM(:,:,ilay); # else # X = BOTM(:,:,ilay-1)-BOTM(:,:,ilay); # end # # m = X(X>0); m = min(m(:)); # imagesc(X), #caxis([m*0.9, max(X(:))]), # cm = colormap; # cm(1,:) = [1 1 1]; # colormap(cm); # colorbar # title(['DZ', ' lay', num2str(ilay)]); # end #%% # based on: write_ba6_MOD3_2.m # (had to be careful of numerical convergence problems; set constant head for # outer boundary to avoid these. Later resolved with NWT by Leila) def write_ba6_MOD3_2(GSFLOW_indir, infile_pre, mask_fil, fl_BoundConstH): # # ==== TO RUN AS SCRIPT =================================================== # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # slashstr = '/' # # # infile_pre = 'test1lay'; # # NLAY = 1; # # DZ = 10; # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # # infile_pre = 'test2lay_py' # NLAY = 2 # DZ = [100, 50] # [NLAYx1] [m] ***testing # # GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/' # # # for various files: ba6, dis, uzf, lpf # surfz_fil = GIS_indir + 'topo.asc' # # for various files: ba6, uzf # mask_fil = GIS_indir + 'basinmask_dischargept.asc' # # fl_BoundConstH = 1 # 1 for const head at high elev boundary, needed for # numerical convergence for AGU2016 poster. Maybe resolved with MODFLOW-NWT? # # ========================================================================= # - write to this file # GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; ba6_file = infile_pre + '.ba6' # - domain dimensions, maybe already in surfz_fil and botm_fil{}? # NLAY = 1; # NROW = 50; # NCOL = 50; # -- IBOUND(NROW,NCOL,NLAY): <0 const head, 0 no flow, >0 variable head # use basin mask (set IBOUND>0 within watershed, =0 outside watershed, <0 at discharge point and 2 neighboring pixels) # mask_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/basinmask_dischargept.asc'; f = open(mask_fil, 'r') sdata = {} for i in range(6): line = f.readline() line = line.rstrip() # remove newline characters key, value = line.split(': ') try: value = int(value) except: value = float(value) sdata[key] = value f.close() NSEW = [sdata['north'], sdata['south'], sdata['east'], sdata['west']] NROW = sdata['rows'] NCOL = sdata['cols'] IBOUND = np.genfromtxt(mask_fil, skip_header=6, skip_footer=1, delimiter=' ', dtype=float) f = open(mask_fil, 'r') last_line = f.readlines() last_line = last_line[-1].rstrip() f.close() value1, value2 = last_line.split(': ') value2 = value2.split(' ') dischargePt_rowi = int(value2[1]) dischargePt_coli = int(value2[3]) # - force some cells to be active to correspond to stream reaches print "Warning!! Hard-coded to set some IBOUND values to be active!! Check Andy's GIS algorithm..." IBOUND[14-1,33-1] = 1 IBOUND[11-1,35-1] = 1 IBOUND[12-1,34-1] = 1 IBOUND[7-1,43-1] = 1 # find boundary cells IBOUNDin = IBOUND[1:-1-1+1,1:-1-1+1] IBOUNDu = IBOUND[0:-1-2+1,1:-1-1+1] # up IBOUNDd = IBOUND[2:,1:-1-1+1] # down IBOUNDl = IBOUND[1:-1-1+1,0:-1-2+1] # left IBOUNDr = IBOUND[1:-1-1+1,2:] # right # - inner boundary is constant head ind_bound = ((IBOUNDin==1) & ((IBOUNDin-IBOUNDu==1) | (IBOUNDin-IBOUNDd==1) | (IBOUNDin-IBOUNDl==1) | (IBOUNDin-IBOUNDr==1))) # - outer boundary is constant head # ind_bound = ((IBOUNDin==0) & ((IBOUNDin-IBOUNDu==-1) | (IBOUNDin-IBOUNDd==-1) | # (IBOUNDin-IBOUNDl==-1) | (IBOUNDin-IBOUNDr==-1))) # -- init head: base on TOP and BOTM dis_file = GSFLOW_indir + slashstr + infile_pre + '.dis' # dis_file = '/home/gcng/Shortcuts/AndesWaterResources/GSFLOW/inputs/MODFLOW/test2lay.dis' f = open(dis_file, 'r') for i in range(3): # first 2 lines are comments line = f.readline().rstrip() line = line.split() NLAY = int(line[0]) NROW = int(line[1]) NCOL = int(line[2]) NPER = int(line[3]) ITMUNI = int(line[4]) LENUNI = int(line[5]) line = f.readline().rstrip() LAYCBD = np.array(line.split(), float) line = f.readline().rstrip() line = line.split() DELR = float(line[1]) line = f.readline().rstrip() line = line.split() DELC = float(line[1]) f.close() TOP = np.genfromtxt(dis_file, skip_header=7, max_rows=NROW, dtype=float) BOTM = np.zeros((NROW, NCOL, NLAY),float); for ii in range(NLAY): BOTM[:,:,ii] = np.genfromtxt(dis_file, skip_header=7+(ii+1)*(NROW+1), \ max_rows=NROW, dtype=float) # - make boundary cells constant head above a certain elevation # IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 4500) = -1; if fl_BoundConstH == 1: IBOUNDin[ind_bound & (TOP[1:-1-1+1,1:-1-1+1] > 3500)] = -1 # ***this used for AGU2016 to have convergence IBOUND[1:-1-1+1,1:-1-1+1] = IBOUNDin # - make discharge point and neighboring cells constant head IBOUND[dischargePt_rowi-1,dischargePt_coli-1] = -2 # downgrad of discharge pt # IBOUND[dischargePt_rowi-2,dischargePt_coli-1] = -1 # neighbor points IBOUND[dischargePt_rowi,dischargePt_coli-1] = -1 IBOUND[dischargePt_rowi-1,dischargePt_coli] = -2 # downgrad of discharge pt IBOUND[dischargePt_rowi-2,dischargePt_coli] = -1 # neighbor points IBOUND[dischargePt_rowi,dischargePt_coli] = -1 IBOUND[dischargePt_rowi-1,dischargePt_coli-1] = 1 # downgrad of discharge pt M = np.ones((NROW,NCOL,NLAY),float) M[:,:,0] = IBOUND M[:,:,1] = IBOUND IBOUND = M # - initHead(NROW,NCOL,NLAY) initHead = BOTM[:,:,0] + (TOP-BOTM[:,:,0])*0.9; # within top layer # # (no more than 10m below top): # Y = nan(NROW,NCOL,2); Y(:,:,1) = initHead; Y(:,:,2) = TOP-10; # initHead = max(Y,[],3); M = np.ones((NROW,NCOL,NLAY),float) M[:,:,0] = initHead M[:,:,1] = initHead initHead = M # - assumed values HNOFLO = -999.99 ## ------------------------------------------------------------------------ # -- Write ba6 file fil_ba6_0 = GSFLOW_indir + slashstr + ba6_file fobj = open(fil_ba6_0, 'w+') fobj.write('# basic package file --- %d layers, %d rows, %d columns\n' % (NLAY, NROW, NCOL)) fobj.write('FREE\n') for ilay in range(NLAY): fobj.write('INTERNAL 1 (FREE) 3 IBOUND for layer %d \n' % (ilay+1)) np.savetxt(fobj, IBOUND[:,:,ii], delimiter=' ', fmt='%4d') fobj.write(' %f HNOFLO\n' % (HNOFLO)); for ilay in range(NLAY): fobj.write('INTERNAL 1 (FREE) 3 init head for layer %d \n' % (ilay+1)) np.savetxt(fobj, initHead[:,:,ii], delimiter=' ', fmt='%7g') fobj.close() # # -- Plot basics # for ii = 1:2 # if ii == 1, # X0 = IBOUND; ti0 = 'IBOUND'; # elseif ii == 2 # X0 = initHead; ti0 = 'init head'; # end # figure # for ilay = 1:NLAY # subplot(2,2,double(ilay)) # X = X0(:,:,ilay); # m = X(X>0); m = min(m(:)); # imagesc(X), #caxis([m*0.9, max(X(:))]), # cm = colormap; # # cm(1,:) = [1 1 1]; # colormap(cm); # colorbar # title([ti0, ' lay', num2str(ilay)]); # end # end #%% # based on write_lpf_MOD2_f2_2.m def write_lpf_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY): # # =========== TO RUN AS SCRIPT =========================================== # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # # slashstr = '/'; # # # infile_pre = 'test1lay'; # # NLAY = 1; # # DZ = 10; # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # # infile_pre = 'test2lay_py' # NLAY = 2 # DZ = [100, 50] # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/' # # # for various files: ba6, dis, uzf, lpf # surfz_fil = GIS_indir + 'topo.asc' # # for various files: ba6, uzf # mask_fil = GIS_indir + 'basinmask_dischargept.asc' # # # for sfr # segment_fil_all = [] # segment_fil_all.append(GIS_indir + 'segment_data_4A_INFORMATION.txt') # segment_fil_all.append(GIS_indir + 'segment_data_4B_UPSTREAM.txt') # segment_fil_all.append(GIS_indir + 'segment_data_4C_DOWNSTREAM.txt') # # # ==================================================================== # codes pixels by distance from streams, for specifying hyd cond strm_buffer_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/segments_buffer2.asc' print 'specifying hyd cond based on distance from stream!' # - write to this file # GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; # lpf_file = 'test.lpf'; lpf_file = infile_pre + '.lpf' # - domain dimensions, maybe already in surfz_fil and botm_fil{}? # NLAY = 2; # surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; f = open(surfz_fil, 'r') sdata = {} for i in range(6): line = f.readline() line = line.rstrip() # remove newline characters key, value = line.split(': ') try: value = int(value) except: value = float(value) sdata[key] = value f.close() NSEW = [sdata['north'], sdata['south'], sdata['east'], sdata['west']] NROW = sdata['rows'] NCOL = sdata['cols'] # - space discretization DELR = (NSEW[2]-NSEW[3])/NCOL # width of column [m] DELC = (NSEW[0]-NSEW[1])/NROW # height of row [m] # - set TOP to surface elevation [m] TOP = np.genfromtxt(surfz_fil, skip_header=6, delimiter=' ', dtype=float) # get strm_buffer info (pixels around streams, for hyd cond) strm_buffer = np.genfromtxt(strm_buffer_fil, skip_header=6, delimiter=' ', dtype=float) # -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files # (temp place-holder) hydcond = 2*np.ones((NROW,NCOL,NLAY),float) # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) # hydcond[:,:,1] = 0.5 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) # hydcond[:,:,1] = 0.1 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond[:,:,0] = 0.1 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) # hydcond[:,:,0] = 0.01 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond[:,:,1] = 0.01 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = 2e-6*np.ones((NROW,NCOL,NLAY),float) # constant 2e-6 /m for Sagehen Sy = 0.15*np.ones((NROW,NCOL,NLAY),float) # 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy # = Sy in Sagehen (lower Sy under ridges for volcanic rocks) # # use strm_buffer (and elev?) # K = strm_buffer; # 0: very far from stream, 5: farthest from stream in strm_buffer, 1: closest to stream # K(strm_buffer==0) = 0.04; # very far from streams # K(strm_buffer==0 & TOP>5000) = 0.03; # very far from streams # K(strm_buffer>=1) = 0.5; # close to streams # K(strm_buffer>=2) = 0.4; # K(strm_buffer>=3) = 0.3; # K(strm_buffer>=4) = 0.15; # K(strm_buffer==5) = 0.08; # farthest from stream and high # hydcond(:,:,1) = K; # hydcond(:,:,2) = 0.01; # use strm_buffer (and elev?) K = np.copy(strm_buffer) # 0: very far from stream, 5: farthest from stream in strm_buffer, 1: closest to stream K[strm_buffer==0] = 0.04 # very far from streams K[(strm_buffer==0) & (TOP>5000)] = 0.03 # very far from streams # K(strm_buffer>=1) = 0.5; # close to streams K[strm_buffer>=1] = 0.25 # close to streams K[strm_buffer>=2] = 0.15 K[strm_buffer>=3] = 0.08 K[strm_buffer>=4] = 0.08 K[strm_buffer==5] = 0.08 # farthest from stream and high hydcond[:,:,0] = K; hydcond[:,:,1] = 0.01 # -- assumed input values flow_filunit = 34 # make sure this matches namefile!! hdry = 1e30 # head assigned to dry cells nplpf = 0 # number of LPF parameters (if >0, key words would follow) laytyp = np.zeros((NLAY,1),int) laytyp[0] = 1; # flag, top>0: "covertible", rest=0: "confined" (does not have WT) layave = np.zeros((NLAY,1),int) # flag, layave=1: harmonic mean for interblock transmissivity chani = np.ones((NLAY,1),int); # flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = np.zeros((NLAY,1),int) # flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond laywet = np.zeros((NLAY,1),int) laywet[0]=1 # flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1 # flag, 1 for at least 1 transient stress period (for Ss and Sy) WETFCT = 1.001 # 1.001 for Sagehen, wetting (convert dry cells to wet) IWETIT = 4 # number itermations for wetting IHDWET = 0 # wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) ## ------------------------------------------------------------------------ fmt1 = '' for ii in range(NLAY): fmt1 = fmt1 + '%2d ' fil_lpf_0 = GSFLOW_indir + slashstr + lpf_file fobj = open(fil_lpf_0, 'w+') fobj.write('# LPF package inputs\n'); fobj.write('%d %g %d ILPFCB,HDRY,NPLPF\n' % (flow_filunit, hdry, nplpf)) _out = np.squeeze(laytyp) # for 1D arrays fmt12 = fmt1 + ' LAYTYP' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(layave) # for 1D arrays fmt12 = fmt1 + ' LAYAVE' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(chani) # for 1D arrays fmt12 = fmt1 + ' CHANI' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(layvka) # for 1D arrays fmt12 = fmt1 + ' LAYVKA' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(laywet) # for 1D arrays fmt12 = fmt1 + ' LAYWET' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) if any(laywet == 1): fobj.write('%g %d %d WETFCT, IWETIT, IHDWET\n' % (WETFCT, IWETIT, IHDWET)) # -- Write HKSAT and Ss, Sy (if Tr) in .lpf file # loop thru layers (different entry for each layer) for ilay in range(NLAY): fobj.write('INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n' % (ilay+1)) np.savetxt(fobj, hydcond[:,:,ilay], delimiter=' ', fmt=' %4.2e') fobj.write('INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n' % (ilay+1)) np.savetxt(fobj, VKA[:,:,ilay], delimiter=' ', fmt=' %4.2e') if fl_Tr: fobj.write('INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n' % (ilay+1)) np.savetxt(fobj, Ss[:,:,ilay], delimiter=' ', fmt=' %4.2e') if laytyp[ilay] > 0: # convertible, i.e. unconfined fobj.write('INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n' % (ilay+1)) np.savetxt(fobj, Sy[:,:,ilay], delimiter=' ', fmt=' %4.2e') if laywet[ilay] > 0: fobj.write('INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n' % (ilay+1)) np.savetxt(fobj, WETDRY[:,:,ilay], delimiter=' ', fmt=' %4.2f') fobj.write('\n') fobj.close() # figure # for ilay = 1:NLAY # subplot(2,2,double(ilay)) # X = hydcond(:,:,ilay); # m = X(X>0); m = min(m(:)); # imagesc(X), #caxis([m*0.9, max(X(:))]), # cm = colormap; # # cm(1,:) = [1 1 1]; # caxis([0 max(X(:))]) # colormap(cm); # colorbar # title(['hydcond', num2str(ilay)]); # end #%% # Based on write_upw_MOD2_f2_2.m # (which is almost identical to write_lpf_MOD2_f2_2.m; only changes for upw are # to comment out WETFCT, IWETIT, and IHDWET; set LAYWET all to 0. Some edits # made to Leila's script.) def write_upw_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY): # # =========== TO RUN AS SCRIPT =========================================== # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # # slashstr = '/'; # # # infile_pre = 'test1lay'; # # NLAY = 1; # # DZ = 10; # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # # infile_pre = 'test2lay_py' # NLAY = 2 # DZ = [100, 50] # [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) # GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/' # # # for various files: ba6, dis, uzf, lpf # surfz_fil = GIS_indir + 'topo.asc' # # for various files: ba6, uzf # mask_fil = GIS_indir + 'basinmask_dischargept.asc' # # # for sfr # segment_fil_all = [] # segment_fil_all.append(GIS_indir + 'segment_data_4A_INFORMATION.txt') # segment_fil_all.append(GIS_indir + 'segment_data_4B_UPSTREAM.txt') # segment_fil_all.append(GIS_indir + 'segment_data_4C_DOWNSTREAM.txt') # # # ==================================================================== # codes pixels by distance from streams, for specifying hyd cond strm_buffer_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/segments_buffer2.asc' print 'specifying hyd cond based on distance from stream!' # - write to this file # GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; # lpf_file = 'test.lpf'; lpf_file = infile_pre + '.upw' # - domain dimensions, maybe already in surfz_fil and botm_fil{}? # NLAY = 2; # surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; f = open(surfz_fil, 'r') sdata = {} for i in range(6): line = f.readline() line = line.rstrip() # remove newline characters key, value = line.split(': ') try: value = int(value) except: value = float(value) sdata[key] = value f.close() NSEW = [sdata['north'], sdata['south'], sdata['east'], sdata['west']] NROW = sdata['rows'] NCOL = sdata['cols'] # - space discretization DELR = (NSEW[2]-NSEW[3])/NCOL # width of column [m] DELC = (NSEW[0]-NSEW[1])/NROW # height of row [m] # - set TOP to surface elevation [m] TOP = np.genfromtxt(surfz_fil, skip_header=6, delimiter=' ', dtype=float) # get strm_buffer info (pixels around streams, for hyd cond) strm_buffer = np.genfromtxt(strm_buffer_fil, skip_header=6, delimiter=' ', dtype=float) # -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files # (temp place-holder) hydcond = 2*np.ones((NROW,NCOL,NLAY),float) # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) # hydcond[:,:,1] = 0.5 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) # hydcond[:,:,1] = 0.1 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond[:,:,0] = 0.1 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) # hydcond[:,:,0] = 0.01 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond[:,:,1] = 0.01 # m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = 2e-6*np.ones((NROW,NCOL,NLAY),float) # constant 2e-6 /m for Sagehen Sy = 0.15*np.ones((NROW,NCOL,NLAY),float) # 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy # = Sy in Sagehen (lower Sy under ridges for volcanic rocks) # # use strm_buffer (and elev?) # K = strm_buffer; # 0: very far from stream, 5: farthest from stream in strm_buffer, 1: closest to stream # K(strm_buffer==0) = 0.04; # very far from streams # K(strm_buffer==0 & TOP>5000) = 0.03; # very far from streams # K(strm_buffer>=1) = 0.5; # close to streams # K(strm_buffer>=2) = 0.4; # K(strm_buffer>=3) = 0.3; # K(strm_buffer>=4) = 0.15; # K(strm_buffer==5) = 0.08; # farthest from stream and high # hydcond(:,:,1) = K; # hydcond(:,:,2) = 0.01; # use strm_buffer (and elev?) K = np.copy(strm_buffer) # 0: very far from stream, 5: farthest from stream in strm_buffer, 1: closest to stream K[strm_buffer==0] = 0.04 # very far from streams K[(strm_buffer==0) & (TOP>5000)] = 0.03 # very far from streams # K(strm_buffer>=1) = 0.5; # close to streams K[strm_buffer>=1] = 0.25 # close to streams K[strm_buffer>=2] = 0.15 K[strm_buffer>=3] = 0.08 K[strm_buffer>=4] = 0.08 K[strm_buffer==5] = 0.08 # farthest from stream and high hydcond[:,:,0] = K; hydcond[:,:,1] = 0.01 # -- assumed input values flow_filunit = 34 # make sure this matches namefile!! hdry = 1e30 # head assigned to dry cells, so easy to detect occurrence nplpf = 0 # number of LPF parameters (if >0, key words would follow) iphdry = 1 # flag to set head to HDRY when it drops below 1e-4 LENUNI above cell bottom laytyp = np.zeros((NLAY,1),int) laytyp[0] = 1; # flag, top>0: "covertible", rest=0: "confined" (does not have WT) layave = np.zeros((NLAY,1),int) # flag, layave=1: harmonic mean for interblock transmissivity chani = np.ones((NLAY,1),int); # flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = np.zeros((NLAY,1),int) # flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond laywet = np.zeros((NLAY,1),int) # laywet[0]=1 # flag, 1: wetting on for top convertible cells, 0: off for confined # ***Edited from Leila's script: MODFLOW-NWT manual says LAYWET should always # be set to zero in the UPW Package because all layers with LAYTYP(NLAY)>0 are assumed to be wettable # laywet[0]=1 # flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1 # flag, 1 for at least 1 transient stress period (for Ss and Sy) # Comment these three out to turn .lpf to .upw # WETFCT = 1.001 # 1.001 for Sagehen, wetting (convert dry cells to wet) # IWETIT = 4 # number itermations for wetting # IHDWET = 0 # wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) ## ------------------------------------------------------------------------ fmt1 = '' for ii in range(NLAY): fmt1 = fmt1 + '%2d ' fil_lpf_0 = GSFLOW_indir + slashstr + lpf_file fobj = open(fil_lpf_0, 'w+') fobj.write('# UPW package inputs\n'); # Edited Leila's file, which omitted IPHDRY fobj.write('%d %g %d %d ILPFCB,HDRY,NPLPF,IPHDRY\n' % (flow_filunit, hdry, nplpf, iphdry)) _out = np.squeeze(laytyp) # for 1D arrays fmt12 = fmt1 + ' LAYTYP' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(layave) # for 1D arrays fmt12 = fmt1 + ' LAYAVE' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(chani) # for 1D arrays fmt12 = fmt1 + ' CHANI' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(layvka) # for 1D arrays fmt12 = fmt1 + ' LAYVKA' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) _out = np.squeeze(laywet) # for 1D arrays fmt12 = fmt1 + ' LAYWET' np.savetxt(fobj, _out[None], delimiter=' ', fmt=fmt12) # comment out to turn lpf to upw # if any(laywet == 1): # fobj.write('%g %d %d WETFCT, IWETIT, IHDWET\n' % (WETFCT, IWETIT, IHDWET)) # -- Write HKSAT and Ss, Sy (if Tr) in .lpf file # loop thru layers (different entry for each layer) for ilay in range(NLAY): fobj.write('INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n' % (ilay+1)) np.savetxt(fobj, hydcond[:,:,ilay], delimiter=' ', fmt=' %4.2e') fobj.write('INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n' % (ilay+1)) np.savetxt(fobj, VKA[:,:,ilay], delimiter=' ', fmt=' %4.2e') if fl_Tr: fobj.write('INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n' % (ilay+1)) np.savetxt(fobj, Ss[:,:,ilay], delimiter=' ', fmt=' %4.2e') if laytyp[ilay] > 0: # convertible, i.e. unconfined fobj.write('INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n' % (ilay+1)) np.savetxt(fobj, Sy[:,:,ilay], delimiter=' ', fmt=' %4.2e') # Editing Leila's file: laywet should always be 0 for UPW # if laywet[ilay] > 0: # fobj.write('INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n' % (ilay+1)) # np.savetxt(fobj, WETDRY[:,:,ilay], delimiter=' ', fmt=' %4.2f') fobj.write('\n') fobj.close() # figure # for ilay = 1:NLAY # subplot(2,2,double(ilay)) # X = hydcond(:,:,ilay); # m = X(X>0); m = min(m(:)); # imagesc(X), #caxis([m*0.9, max(X(:))]), # cm = colormap; # # cm(1,:) = [1 1 1]; # caxis([0 max(X(:))]) # colormap(cm); # colorbar # title(['hydcond', num2str(ilay)]); # end #%% # based on write_OC_PCG_MOD_f.m def write_OC_PCG_MOD_f(GSFLOW_indir, infile_pre, perlen_tr, sw_spinup_restart): # # =========== TO RUN AS SCRIPT =========================================== # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # perlen_tr = 365*30 + np.ceil(365*30/4) # slashstr = '/' # # ======================================================================== # - write to this file fil_pcg = infile_pre + '.pcg' fil_oc = infile_pre + '.oc' # -- shoud match .dis if sw_spinup_restart == 1: NPER = 2 # 1 SS then 1 transient PERLEN = [1, int(perlen_tr)] # 2 periods: 1-day steady-state and multi-day transient elif sw_spinup_restart == 2: NPER = 1 # 1 SS then 1 transient PERLEN = [int(perlen_tr)] # 2 periods: 1-day steady-state and multi-day transient NSTP = PERLEN # -- pcg and oc files are not changed with this script # fil_pcg_0 = fullfile(MODtest_dir0, fil_pcg); fil_pcg_0 = GSFLOW_indir + slashstr + fil_pcg fobj = open(fil_pcg_0, 'w+') # fobj.write('# Preconditioned conjugate-gradient package\n'); # fobj.write(' 50 30 1 MXITER, ITER1, NPCOND\n') # fobj.write(' 0000.001 .001 1. 2 1 1 1.00\n') # fobj.write(' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n') # # sagehen example: # fobj.write('# Preconditioned conjugate-gradient package\n') # fobj.write(' 1000 450 1 MXITER, ITER1, NPCOND\n') # fobj.write(' 0.001 0.08 1.0 2 1 0 -0.05 0.70\n') # fobj.write(' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n') # sagehen example: fobj.write('# Preconditioned conjugate-gradient package\n'); fobj.write(' 1000 450 1 MXITER, ITER1, NPCOND\n') fobj.write(' 0.001 0.08 1.0 2 1 0 -0.05 0.70\n') fobj.write(' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n') fobj.close(); # fil_oc_0 = (MODtest_dir0, fil_oc); # "PRINT": to listing file # "SAVE": to file with unit number in name file fil_oc_0 = GSFLOW_indir + slashstr + fil_oc fobj = open(fil_oc_0, 'w+') fobj.write('HEAD PRINT FORMAT 20\n') fobj.write('HEAD SAVE UNIT 51\n') fobj.write('COMPACT BUDGET AUX\n') fobj.write('IBOUND SAVE UNIT 52\n') for per_i in range(NPER): for stp_i in range(0,int(NSTP[per_i]),30): # print every 30 days fobj.write('PERIOD %d STEP %d\n' % (per_i+1, stp_i+1)) if stp_i+1 == NSTP[per_i]: # only at end of stress period fobj.write(' PRINT HEAD\n') fobj.write(' SAVE IBOUND\n') fobj.write(' PRINT BUDGET\n') fobj.write(' SAVE HEAD\n') fobj.write(' SAVE BUDGET\n') fobj.close() #%% # based on make_sfr2_f_Mannings # def make_sfr2_f_Mannings(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all, sw_spinup_restart): # Note: assume .dis file already created!! (reads in TOP for setting STRTOP) # # ======== TO RUN AS SCRIPT =============================================== # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # infile_pre = 'test2lay_py' # # # for sfr # GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/' # reach_fil = GIS_indir + 'reach_data.txt' # segment_fil_all = [] # segment_fil_all.append(GIS_indir + 'segment_data_4A_INFORMATION_Man.txt') # segment_fil_all.append(GIS_indir + 'segment_data_4B_UPSTREAM_Man.txt') # segment_fil_all.append(GIS_indir + 'segment_data_4C_DOWNSTREAM_Man.txt') # # ========================================================================= ## sfr_file = infile_pre + '.sfr' # -- Refer to GSFLOW manual p.202, SFR1 manual, and SFR2 manual # - Refer to Fig. 1 of SFR1 documentation for segment vs. reach numbering # You need the following inputs (with corresponding structures) # the followings are used to write item 1 fl_nstrm = -1 # flag for stream reaches, <0: include unsaturated zone below (sagehen: >0) nsfrpar = 0 #Always Zero nparseg = 0 #Always Zero const = 86400. #Conversion factor used in calculating depth for a stream reach (86400 in sagehen example) dleak = 0.0001 #Tolerance level of stream depth used in computing leakage between each stream (0.0001 in sagehen example) istcb1 = -1 #Flag for writing stream-aquifer leakage values (>0: file unit, <0: write to listing file) istcb2 = 0 #Flag for writing to a seperate formatted file information on inflows&outflows isfropt = 3 #defines input structure; saturated or non-saturated zone (1: No UZ; 3: UZ, unsat prop at start of simulation), sagehen uses 3 nstrail = 10 #Number of trailing-waive increments, incr for better mass balance (10-20 rec'd, sagehen uses 8) isuzn = 1 #Maximum number of vertical cells used to define the unsaturated zone beneath a stream reach (for icalc=1 (Mannings for depth): use isuzn=1) nsfrsets = 40 #Maximum number of different sets of trailing waves used to allocate arrays. irtflg = 0 #Flag whether transient streamflow routing is active project_name = 'TestProject' # used to name the output file (.sfr) # data_indir = '/home/gcng/workspace/matlab_files/GSFLOW_pre-processor/MODFLOW_scripts/sfr_final/data/'; # data_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; # items reach_data_all = pd.read_csv(reach_fil) # used to write item 2: assumes if sw_spinup_restart == 1: NPER = 2 # used for item 3 elif sw_spinup_restart == 2: NPER = 1 # used for item 3 # items 4a: # NSEG ICALC OUTSEG IUPSEG IPRIOR NSTRPTS FLOW RUNOFF ETSW PPTSW ROUGHCH ROUGHBK CDPTH FDPTH AWDTH BWDTH segment_data_4A = pd.read_csv(segment_fil_all[0]); # used to write items 4a segment_data_4B = pd.read_csv(segment_fil_all[1]); # used to write items 4b (ignored for ICALC=3 in 4a) segment_data_4C = pd.read_csv(segment_fil_all[2]); # used to write items 4c (ignored for ICALC=3 in 4a) # ------------------------------------------------------------------------- # In case the input text files (e.g. reach_data.txt) contain header lines (comments) nstrm = reach_data_all.shape[0] if fl_nstrm < 0: nstrm = -nstrm # sort rows according to increasing segment numbers reach_data_all = reach_data_all.sort_values(by='ISEG', ascending=1) nss = max(reach_data_all['ISEG']) # sort rows according to increasing reach numbers colhead = reach_data_all.columns.get_values() ind_IREACH = np.array(np.where(colhead == 'IREACH')) for ii in range(nss): ind1 = (np.array(np.where(reach_data_all['ISEG'] == ii+1))) if ind1.size > 1: ind1 = np.squeeze(ind1) ind2 = np.array(reach_data_all['IREACH'])[ind1].argsort() # a = np.array(reach_data_all.iloc[ind1[ind2]]) # reach_data_all.iloc[ind1] = a reach_data_all.iloc[ind1] = np.array(reach_data_all.iloc[ind1[ind2]]) else: ind1 = np.ones((1,))* ind1[0] # renumber IREACH to start at 1 for each segment reach_data_all['IREACH'].iloc[ind1] = range(1,len(ind1)+1) reach_data_all.iloc[ind1,ind_IREACH[0]] = range(1,len(ind1)+1) # -- make sure STRTOP is within 1st layer # - read in TOP and BOTM from .dis file dis_file = GSFLOW_indir + slashstr + infile_pre + '.dis' # dis_file = '/home/gcng/Shortcuts/AndesWaterResources/GSFLOW/inputs/MODFLOW/test2lay.dis' f = open(dis_file, 'r') for i in range(3): # first 2 lines are comments line = f.readline().rstrip() line = line.split() NLAY = int(line[0]) NROW = int(line[1]) NCOL = int(line[2]) NPER = int(line[3]) ITMUNI = int(line[4]) LENUNI = int(line[5]) line = f.readline().rstrip() LAYCBD = np.array(line.split(), float) line = f.readline().rstrip() line = line.split() DELR = float(line[1]) line = f.readline().rstrip() line = line.split() DELC = float(line[1]) f.close() TOP = np.genfromtxt(dis_file, skip_header=7, max_rows=NROW, dtype=float) BOTM = np.zeros((NROW, NCOL, NLAY),float); for ii in range(NLAY): BOTM[:,:,ii] = np.genfromtxt(dis_file, skip_header=7+(ii+1)*(NROW+1), \ max_rows=NROW, dtype=float) # TOP for cells corresponding to reaches TOP_RCH = [] for ii in range(abs(nstrm)): ind_i = int(reach_data_all.loc[reach_data_all.index[ii],'IRCH']) ind_j = int(reach_data_all.loc[reach_data_all.index[ii],'JRCH']) TOP_RCH.append(TOP[ind_i-1,ind_j-1]) # BOTM for cells corresponding to reaches BOTM_RCH = [] for ii in range(abs(nstrm)): ind_i = int(reach_data_all.loc[reach_data_all.index[ii],'IRCH']) ind_j = int(reach_data_all.loc[reach_data_all.index[ii],'JRCH']) ind_k = int(reach_data_all.loc[reach_data_all.index[ii],'KRCH']) BOTM_RCH.append(BOTM[ind_i-1, ind_j-1, ind_k-1]) # - change STRTOP to be just below TOP print 'Changing STRTOP (stream top) to be just below (2m) corresponding grid TOP' STRTOP = np.array(TOP_RCH) - 2 # 2 m below TOP if any(STRTOP-reach_data_all['STRTHICK'] < BOTM_RCH): print 'Error! STRTOP is below BOTM of the corresponding layer! Exiting...' quit() reach_data_all.loc[:,'STRTOP'] = np.array(STRTOP) # # -- plot stream reaches # RCH_mask = np.copy(TOP) # for ii in range(abs(nstrm)): # RCH_mask[IRCH[ii]-1,JRCH[ii]-1] = np.amax(TOP)*2 # figure # subplot(2,2,1) # imagesc(TOP), colorbar, # cm = colormap; # cm(end,:) = [1 1 1]; # caxis([min(TOP(:)) max(TOP(:))* 1.25]); # colormap(cm); # subplot(2,2,2) # imagesc(RCH_mask), colorbar, # cm = colormap; # cm(end,:) = [1 1 1]; # caxis([min(TOP(:)) max(TOP(:))* 1.25]); # colormap(cm); # RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); # for ii = 1:abs(nstrm), RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); end # for ii = 1:abs(nstrm), SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); end # figure # imagesc(RCH_NUM), colorbar, # colormap(jet(1+max(IREACH))); # caxis([-0.5 max(IREACH)+0.5]) # figure # imagesc(SEG_NUM), colorbar, # colormap(jet(1+max(ISEG))); # caxis([-0.5 max(ISEG)+0.5]) # # when running as script: to visualize segments one at a time # for j = 1: max(ISEG) # RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); # ind = find(ISEG==j); # for ii = ind(:)' # RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); # SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); # end # # figure(100) # imagesc(RCH_NUM), colorbar, # colormap(jet(1+max(RCH_NUM(:)))); # caxis([-0.5 max(RCH_NUM(:))+0.5]) # title(['reaches for seg ', num2str(j)]); # figure(101) # imagesc(SEG_NUM), colorbar, # colormap(jet(1+max(SEG_NUM(:)))); # caxis([-0.5 max(SEG_NUM(:))+0.5]) # title(['seg ', num2str(j)]); # pause # end # -- threshold slope at minimum 0.001 print 'threshold slope at minimum 0.001 for numerical reasons' ind = np.where(reach_data_all['SLOPE'] < 0.01) reach_data_all.loc[reach_data_all.index[ind],'SLOPE'] = 0.001 print 'setting various streambed properties (overwriting values in ' + reach_fil + ')' # -- set streambed thickness (Sagehen uses constant 1m) reach_data_all.loc[:,'STRTHICK'] = 1 # [m] # -- set streambed hydraulic conductivity (Sagehen example: 5 m/d) reach_data_all.loc[:,'STRHC1'] = 5 # [m] # set streambed theta_s reach_data_all.loc[:,'THTS'] = 0.35 # set streambed initial theta reach_data_all.loc[:,'THTI'] = 0.3 # set streambed Brooks-Corey exp (sagehen example is 3.5) reach_data_all.loc[:,'EPS'] = 3.5 # set streambed unsaturated zone saturated hydraulic conductivity # (sagehen example is 0.3 m/d) reach_data_all.loc[:,'UHC'] = 0.3 nss = segment_data_4A.shape[0] # if isstruct(stress_periods) # stress_periods = stress_periods.data; # end # - specify only for 2 stress periods: stress_periods = np.zeros((NPER, 3)) # itmp, irdflg, iptflg (latter 2 are set to 0) stress_periods[0,0] = nss if NPER > 1: stress_periods[1:,0] = -1 # ------------------------------------------------------------------------- # First put 4A, 4B and 4C data all together in a cell array # size(cell) = nitems x 1 x nperiods # In this case, nitems is 3 (i.e. 4A, 4B and 4C) nitems = 3 nperiods = stress_periods.shape[0] # ------------------------------------------------------------------------- # validate some of the input data if nstrm < 0: if not any(isfropt == np.array([1, 2, 3, 4, 5])): print 'Error: ISFROPT should be set to an integer of 1, 2, 3, 4 or 5.' quit() if nsfrpar != 0: print 'Error: nsfrpar must be 0 because parameters not supported in GSFLOW' quit() if nparseg != 0: print 'Error: nparseg must be 0 because parameters not supported in GSFLOW' quit() # ------------------------------------------------------------------------- # Ouput file fobj = open(GSFLOW_indir + slashstr + sfr_file, 'w+') # Write header lines (item 0) heading = '# Streamflow-Routing (SFR7) input file.\n' fobj.write(heading); fobj.write('# %s simulation \n' % (project_name)); # Item 1 fobj.write(' %5d %5d %5d %5d %8.2f %8.4f %5d %5d' % (nstrm, nss, nsfrpar, nparseg, const, dleak, istcb1, istcb2)) if isfropt >= 1: fobj.write(' %5d' % (isfropt)) if isfropt == 1: fobj.write(' %5d\n' % (irtflg)) elif isfropt > 1: fobj.write(' %5d %5d %5d %5d\n' % (nstrail, isuzn, nsfrsets, irtflg)) else: fobj.write('\n'); # Item 2 if isfropt == 1: ncols_reach = 10 elif isfropt == 2: ncols_reach = 13 elif isfropt == 3: ncols_reach = 14 else: ncols_reach = 6 reach_data_copy = reach_data_all.iloc[:, 0:ncols_reach] p = ncols_reach - 5 fmt_reach = ' %5d %5d %5d %5d %5d' for p_i in range(p): fmt_reach = fmt_reach + ' %8.3f' np.savetxt(fobj, np.array(reach_data_copy), fmt=fmt_reach) # Item 3 and 4 nper = stress_periods.shape[0] for iper in range(nper): # write item 3 to the file np.savetxt(fobj, stress_periods[iper,:][np.newaxis], fmt=' %5d') itmp = stress_periods[iper,0] if itmp > 0: # segment_data_4A for iitmp in range(int(itmp)): # start loop over itmp (num_segments) dummy4a = segment_data_4A.iloc[iitmp,:] # write item 4a to the file fobj.write(' %5d %5d %5d %5d' % (dummy4a['NSEG'], dummy4a['ICALC'], dummy4a['OUTSEG'], dummy4a['IUPSEG'])) if dummy4a['IUPSEG'] > 0: fobj.write(' %5d' % (dummy4a['IPRIOR'])) if dummy4a['ICALC'] == 4: fobj.write(' %5d' % (dummy4a['NSTRPTS'])) fobj.write(' %8.3f %8.3f %8.3f %8.3f' % (dummy4a['FLOW'], dummy4a['RUNOFF'], dummy4a['ETSW'], dummy4a['PPTSW'])) if (dummy4a['ICALC'] == 1) or (dummy4a['ICALC'] == 2): fobj.write(' %8.3f' % (dummy4a['ROUGHCH'])) if dummy4a['ICALC'] == 2: fobj.write(' %8.3f' % (dummy4a['ROUGHBK'])) if dummy4a['ICALC'] == 3: fobj.write(' %8.3f %8.3f %8.3f %8.3f' % (dummy4a['CDPTH'], dummy4a['FDPTH'], dummy4a['AWDTH'], dummy4a['BWDTH'])) fobj.write('\n') # write items 4b and 4c to the file for i in range(2): # start loop through 4a and 4b if i == 0: dummy4bc = segment_data_4B.iloc[iitmp,:] else: dummy4bc = segment_data_4C.iloc[iitmp,:] fl_no_4bc = 0 if (any(isfropt == np.array([0, 4, 5])) and (dummy4a['ICALC'] <= 0)): fmt = ' %8.3f %8.3f %8.3f %8.3f %8.3f' fobj.write(fmt % (dummy4bc['HCOND'+str(i+1)], dummy4bc['THICKM'+str(i+1)], dummy4bc['ELEVUPDN'+str(i+1)], dummy4bc['WIDTH'+str(i+1)], dummy4bc['DEPTH'+str(i+1)])) elif (any(isfropt == np.array([0, 4, 5])) and (dummy4a['ICALC'] == 1)): if i == 0: fobj.write(' %8.3f' % (dummy4bc['HCOND'+str(i+1)])) if (iper+1 == 1): # only for the first period fmt = ' %8.3f %8.3f %8.3f' fobj.write(fmt % (dummy4bc['THICKM'+str(i+1)], dummy4bc['ELEVUPDN'+str(i+1)], dummy4bc['WIDTH'+str(i+1)])) if ((isfropt == 4) or (isfropt == 5)): fmt = ' %8.3f %8.3f %8.3f' fobj.write(fmt % (dummy4bc['THTS'+str(i+1)], dummy4bc['THTI'+str(i+1)], dummy4bc['EPS'+str(i+1)])) if (isfropt == 5): fobj.write(' %8.3f' % (dummy4bc['UHC'+str(i+1)])) elif ((iper+1 > 1) and (isfropt == 0)): fmt = ' %8.3f %8.3f %8.3f' fobj.write(fmt % (dummy4bc['THICKM'+str(i+1)], dummy4bc['ELEVUPDN'+str(i+1)], dummy4bc['WIDTH'+str(i+1)])) elif (any(isfropt == np.array([0, 4, 5])) and (dummy4a['ICALC'] >= 2)): fobj.write(' %8.3f' % (dummy4bc['HCOND'+str(i+1)])) if not (any(isfropt == np.array([4, 5])) and (iper+1 > 1) and (dummy4a['ICALC'] == 2)): fobj.write(' %8.3f %8.3f' % (dummy4bc['THICKM'+str(i+1)], dummy4bc['ELEVUPDN'+str(i+1)])) if (any(isfropt == np.array([4, 5])) and (iper+1 == 1) and (dummy4a['ICALC'] == 2)): fmt = ' %8.3f %8.3f %8.3f' fobj.write(fmt % (dummy4bc['THTS'+str(i+1)], dummy4bc['THTI'+str(i+1)], dummy4bc['EPS'+str(i+1)])) if (isfropt == 5): fobj.write(' %8.3f' % (dummy4bc['UHC'+str(i+1)])) elif ((isfropt == 1) and (dummy4a['ICALC'] <= 1)): fobj.write(' %8.3f' % (dummy4bc['WIDTH'+str(i+1)])) if (icalc <= 0): fobj.write(' %8.3f' % (dummy4bc['DEPTH'+str(i+1)])) elif (any(isfropt == np.array([2, 3])) and (dummy4a['ICALC'] <= 1)): if (iper+1 == 1): fobj.write(' %8.3f' % (dummy4bc['WIDTH'+str(i+1)])) if (dummy4a['ICALC'] <= 0): fobj.write(' %8.3f' % (dummy4bc['DEPTH'+str(i+1)])) else: fl_no_4bc = 1 if fl_no_4bc == 0: fobj.write('\n') fobj.close() #%% def MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment): if data_type == 'INT': CNSTNT0 = str(int(CNSTNT)) fmt0 = '%7d' elif data_type == 'REAL': CNSTNT0 = str(float(CNSTNT)) fmt0 = '%7e' if np.array(data).size == 1: str0 = 'CONSTANT ' + fmt0 + ' %s \n' fobj.write(str0 % (data, comment)) else: fobj.write('INTERNAL %10s%20s%10s %s \n' % (CNSTNT0, '(FREE)', '-1', comment)) np.savetxt(fobj, data, delimiter=' ', fmt=fmt0) def make_uzf3_f_2(GSFLOW_indir, infile_pre, surfz_fil, mask_fil, sw_spinup_restart): print 'UZF: Had to play around alot with finf (infiltration) to get convergence!!' # ######### TO RUN AS SCRIPT ############################################## # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' # # MODFLOW output files # GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # # infile_pre = 'test2lay_py' # # NLAY = 2 # DZ = [100, 50] # [NLAYx1] [m] # # # length of transient stress period (follows 1-day steady-state period) [d] # # perlen_tr = 365 # ok if too long # perlen_tr = 365*30 + np.ceil(365*30/4) # # GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/' # # # use restart file as initial cond (empty string to not use restart file) # fil_res_in = '' # empty string to not use restart file ## fil_res_in = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/simdir/spinup30yr_constH/outputs/MODFLOW/test2lay.out' # empty string to not use restart file # # # for various files: ba6, dis, uzf, lpf # surfz_fil = GIS_indir + 'topo.asc' # # for various files: ba6, uzf # mask_fil = GIS_indir + 'basinmask_dischargept.asc' # # ######################################################################## # ------------------------------------------------------------------------- # You need the following inputs # - write to this file # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; uz_file = infile_pre + '.uzf' # surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; f = open(surfz_fil, 'r') sdata = {} for i in range(6): line = f.readline() line = line.rstrip() # remove newline characters key, value = line.split(': ') try: value = int(value) except: value = float(value) sdata[key] = value f.close() NSEW = [sdata['north'], sdata['south'], sdata['east'], sdata['west']] NROW = sdata['rows'] NCOL = sdata['cols'] # - set TOP to surface elevation [m] TOP = np.genfromtxt(surfz_fil, skip_header=6, delimiter=' ', dtype=float) if sw_spinup_restart == 1: NPER = 2 # **** ASSUMES PER 1 IS SS, PER 2 IS TR **** elif sw_spinup_restart == 2: NPER = 1 # **** ASSUMES PER 1 IS TR **** #Item 1: #NUZTOP: Which cell (layer) has recharge&discharge simulated in it; # 1:top layer has recharge/discharge and land-surface (at top) # 2:layer specificed in UZFBND, top of that layer is land-surface # 3:highest active layer, top of UZFBND is land-surface (*sagehen example, with watershed mask of UZFBND=1) NUZTOP = 3 IUZFOPT = 1 # 1: Vertical hydraulic conductivity is specified using VKS, 2: use VKA from LPF file IRUNFLG = 0 # >0: Groundwater discharged to land-surface is routed to streams or lakes (using IRUNBND) (*sagehen=0, ONLY avaliable in GSFLOW for SS) IETFLG = 0 # ~=0: Evaporation will be simulated. (*sagehen=0; GSFLOW: =0 for PRMS ET only, =1 for additional ET from below soil zone) IUZFCB1 = 61 #Flag for writing rates of groundwater recharge, ET&groundwater discharge in UBUDSV format.0:wont be written, >0: file unit number IUZFCB2 = 0 #Writing groundwater recharge, discharge&ET in UBUDSV3 format; >0: file unit number NTRAIL2 = 25 #Number of trailing waves to define theta profile, 10 to 20 usually ok, higher for better mass balance NSETS2 = 100 #Number of wave sets to simulate multiple infiltration periods, 20 usually ok. NUZGAG = 0 # number of cells for which to print detailed info on UZ water budget and theta (see uzgag below) SURFDEP = 1.0 # average undulation depth within finite diff cell (?) #Item 2-7: project_name = 'TestProject' # used to name the output file (.uzf) iuzfbnd = np.ones((NROW,NCOL),int) # [NROW,NCOL] layer w/ top as land-surface and/or w/ discharge/recharge (see NUZTOP), default: mask with 1's if IRUNFLG > 0: print 'Error! Input scripts only set up for IRUNFLG = 0!' quit() # irunbnd = importdata('./data/irunbnd.dat'); # [NROW,NCOL] only for IRUNFLG>0, stream seg to which gw discharge is routed # vks = importdata('./data/vks.dat'); # [NROW,NCOL] saturated K, no needed if using value in LPF (IUZFOPT=2), [m/d] vks = 4.*np.ones((NROW,NCOL)) # Ok to have following parameters as SCALAR (constant for all gridcells) or as ARRAY (NROWxNCOL) eps = 3.5 #Brooks-Corey epsilon of the unsaturated zone. thts = 0.35 #Saturated water content of the unsaturated zone thti = 0.0 #initial water content for each vertical column of cells-not specified for steady-state simulations if NUZGAG > 0: print 'Error! Input scripts only set up for UZGAG = 0!' quit() # uzgag = importdata('./data/uzgag.dat'); # only for NUZGAG>0; row, col, file unit for output, IUZOPT (flag for what data to output) # - infiltration (in general, not needed bc provided by PRMS, but option to apply for initial SS period for MODFLOW) if sw_spinup_restart == 1: NUZF1 = np.array([[1], -1*np.ones((NPER-1,1))]) # infiltration can ONLY specified for (initial) SS stress periods (o.w. calculated by PRMS) elif sw_spinup_restart == 2: NUZF1 = -1*np.ones((NPER,1)) # infiltration can ONLY specified for (initial) SS stress periods (o.w. calculated by PRMS) # A = importdata('./data/finf.dat'); # infiltration rate [NROW,NCOL,1], **max ONLY for 1 stress period: first SS stress period! [m/d] # finf = A'; # B = reshape(A', NCOL, NROW, NPER); # for i=1:size(B, 3) # finf(:, :, i) = transpose(B(:, :, i)); # end # finf = ones(NROW,NCOL); # finf(:,:,1) = ones(NROW,NCOL)*8.8e-5; # m/d (8.8e-4 m/d typical in Sagehen) # - set infiltration: FINF (for S.S. initialization) according to TOP (high elev only) f = open(mask_fil, 'r') sdata = {} for i in range(6): line = f.readline() f.close() IBOUND = np.genfromtxt(mask_fil, skip_header=6, skip_footer=1, delimiter=' ', dtype=float) f = open(mask_fil, 'r') last_line = f.readlines() last_line = last_line[-1].rstrip() f.close() value1, value2 = last_line.split(': ') value2 = value2.split(' ') dischargePt_rowi = int(value2[1]) dischargePt_coli = int(value2[3]) IBOUND[dischargePt_rowi-1,dischargePt_coli-1] = -2 # downgrad of discharge pt IBOUND[dischargePt_rowi-2,dischargePt_coli-1] = -1 # neighbor points IBOUND[dischargePt_rowi+1-1,dischargePt_coli-1] = -1 TOP_mask = TOP TOP_mask[IBOUND==0] = 0 a = np.where(TOP_mask.flatten()>0) NZ = np.array(a).size z_sort = np.sort(TOP_mask.flatten())[::-1] # descending order # this works: (for no sfr: converges, but mostly all dry) ind = TOP_mask > z_sort[int(round(NZ/10))] finf = np.zeros((NROW,NCOL)) finf[ind] = 4e-4; # m/d (8.8e-4 m/d typical in Sagehen) # testing: (for no sfr: kind of works, S.S. does not converge but transient mostly # does, starts wet then dries out) finf = np.zeros((NROW,NCOL)) ind = TOP_mask > z_sort[int(round(0.25*NZ))] finf[IBOUND!=0] = 4e-4 / 10 # m/d (8.8e-4 m/d typical in Sagehen) finf[ind] = 4e-4; # m/d (8.8e-4 m/d typical in Sagehen) # scale FINF by elev # (# Sagehen max 3*8.e-4, min 8.e-4 maxFINF = 3* 8.e-4 minFINF = 8e-4 midZ_factor = (2150-1928)/(2649-1928) # based on Sagehen, where FINF levels off; sagehen: 0.31 midZ = midZ_factor * (np.max(TOP_mask.flatten())-np.min(TOP_mask[TOP_mask>0])) + np.min(TOP_mask[TOP_mask>0]) m = (maxFINF-minFINF)/(np.max(TOP_mask.flatten())-np.min(TOP_mask[TOP_mask>0])) finf = m*(TOP_mask-np.min(TOP_mask[TOP_mask>0])) + minFINF finf[TOP_mask<=midZ] = 4e-4 finf[IBOUND==0] = 0 # # testing: # finf = np.zeros((NROW,NCOL)) # ind = TOP_mask > z_sort[int(round(0.25*NZ))] # finf[IBOUND!=0] = 4e-2 / 10 # m/d (8.8e-4 m/d typical in Sagehen) # finf[ind] = 4e-2 # m/d (8.8e-4 m/d typical in Sagehen) # finf[:] = 0; # finf[IBOUND!=0] = 4e-4 / 100 # m/d (8.8e-4 m/d typical in Sagehen) # finf[ind] = 4e-5 # m/d (8.8e-4 m/d typical in Sagehen) # finf[ind] = 4e-4; # m/d (8.8e-4 m/d typical in Sagehen) - just this works # figure, subplot(2,2,1), # X = finf; # m = X(X>0); m = min(m(:)); # imagesc(X(:,:)), # caxis([m*0.9, max(X(:))]), # cm = colormap; # cm(1,:) = [1 1 1]; # colormap(cm); # colorbar # title('FINF (S.S. infil) [m/d]'); # - ET (in general, not needed bc provided by PRMS, but option to apply excess ET below PRMS' soil-zone, i.e. apply to MODFLOW's UZ) # pet = 5.0E-08; #array of ET demands rate (L/T), PET not used in GSFLOW # for IETFLG>0, specify how ET can be drawn from below soil-zone base; # assume same for all stress periods if IETFLG>0: NUZF2 = -1*ones((NPER,1)) # use ET from below soil-zone if sw_spinup_restart == 1: NUZF3 = np.array([[1], -1*np.ones((NPER-1,1))]) # only specify extdp for first stress periods NUZF4 = np.array([[1], -1*np.ones((NPER-1,1))]) # only specify extwc for first stress periods elif sw_spinup_restart == 2: NUZF3 = -1*np.ones((NPER,1)) # only specify extdp for first stress periods NUZF4 = -1*np.ones((NPER,1)) # only specify extdp for first stress periods extdp = 15.0*np.ones((NROW,NCOL)) #array of ET extiction zone~altitude of the soil-zone base;specified at least for 1st stress period; only for IETFLG>0 extwc = thts*0.9*np.ones((NROW,NCOL)) #array of Extinction water content; EXTWC must be between (THTS-Sy) and THTS; only for IETFLG>0 and # ------------------------------------------------------------------------- # Ouput file fname = GSFLOW_indir + slashstr + uz_file fobj = open(fname, 'w+') # Write header lines (item 0) heading = '# Unsaturated-Zone Flow (UZF) input file.\n'; fobj.write(heading); fobj.write('# %s simulation \n' % (project_name)) # Write item 1 fmtarr_int = '' for ii in range(9): fmtarr_int = fmtarr_int + ' %6d' fmtarr_int = fmtarr_int + ' %10.6E' fobj.write(fmtarr_int % (NUZTOP, IUZFOPT, IRUNFLG, IETFLG, IUZFCB1, IUZFCB2, NTRAIL2, NSETS2, NUZGAG, SURFDEP)) comment = ' NUZTOP IUZFOPT IRUNFLG IETFLG IUZFCB1 IUZFCB2 NTRAIL2 NSETS2 NUZGAG SURFDEP\n' fobj.write(comment) # Generally use these settings LOCAT = 'INTERNAL' CNSTNT = 1 IPRN = -1 # Write item2 [IUZFBND (NCOL, NROW)] - U2DINT # INTERNAL 1.0 (FREE) -1 # "INTERNAL" b/c data follows in same file, # 1.0 because all values scaled by 1.0 # -1 is IPRN print flag (<0 means value NOT printed to list file) comment = '#IUZFBND--AREAL EXTENT OF THE ACTIVE MODEL' data = iuzfbnd data_type = 'INT' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) # write item 3 [IRUNBND (NCOL, NROW)] - U2DINT if (IRUNFLG > 0): comment = '#IRUNBND--STREAM SEGMENTS OR LAKE NUMBERS' data = irunbnd data_type = 'INT' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) # write item 4 [VKS (NCOL, NROW)] - U2DREL if (IUZFOPT == 1): comment = '#VKS--VERTICAL HYDRAULIC CONDUCTIVITY OF THE UNSATURATED ZONE' data = vks data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) # write items 5, 6, 7 comment = '#EPS--BROOKS/COREY EPSILON' data = eps data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) comment = '#THTS--SATURATED WATER CONTENT' data = thts data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) if sw_spinup_restart == 2: # only if starts with transient period comment = '#THTI--INITIAL WATER CONTENT' data = thti data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) # write item 8 if (NUZGAG > 0): comment = '#IUZROW IUZCOL IFTUNIT IUZOPT--UNSATURATED FLOW OUTPUT'; for i in range(NUZGAG): dummyrow = uzgag[i, :] fobj.write(' %6d %6d %6d %6d %s\n' % (dummyrow, comment)) # write items 9-16 for iper in range(NPER): # write item 9 comment = '#NUZF1 FOR STRESS PERIOD ' + str(int(iper+1)) + '\n' fobj.write(' %6d %s' % (NUZF1[iper], comment)) # write item 10 if (NUZF1[iper] > 0): # ent = get_file_entry(transpose(finf(:, :, iper)), 'U2DREL', ... # 1.0, sprintf('#FINF--STRESS PERIOD #d', iper)); comment = '#FINF--STRESS PERIOD ' + str(int(iper+1)) data = finf data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) # --------------------------------------------------------------------- # items 11-16 if (IETFLG > 0): # write items 11 comment = '#NUZF2 FOR STRESS PERIOD (GSFLOW DOES NOT USE PET) ' + str(int(iper+1)) + '\n' fobj.write(' %6d %s' % (NUZF2[iper], comment)) # write item 12 (GSFLOW DOES NOT USE PET) # if (NUZF2(iper) > 0): # ----------------------------------------------------------------- # write items 13 comment = '#NUZF3 FOR STRESS PERIOD ' + str(int(iper+1)) + '\n' fobj.write(' %6d %s' % (NUZF3[iper], comment)) # write item 14 if (NUZF3[iper] > 0): comment = '#EXTDP FOR STRESS PERIOD ' + str(int(iper+1)) data = extdp data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) # ----------------------------------------------------------------- # write items 15 comment = '#NUZF4 FOR STRESS PERIOD ' + str(int(iper+1)) + '\n' fobj.write(' %6d %s' % (NUZF4[iper], comment)) # write item 16 if (NUZF4[iper] > 0): comment = '#EXTWC FOR STRESS PERIOD ' + str(int(iper+1)) data = extwc data_type = 'REAL' MOD_data_write2file(fobj, LOCAT, CNSTNT, IPRN, data_type, data, comment) fobj.close() #%% # Based on Leila's script NWT_write.m # Adapted into function def NWT_write_file(GSFLOW_indir, infile_pre): # ------------------------------------------------------------------------- # input variables # see Table 2., page 12 of MODFLOW-NWT Techniques and Methods # ######### TO RUN AS SCRIPT ############################################## # # - directories # # MODFLOW input files # GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/' ## # MODFLOW output files ## GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/' # # infile_pre = 'test2lay_py' # ######################################################################### # Iteration Control headtol = 1e-4; fluxtol = 500; maxiterout = 100; # Dry Cell Tolerance thickfact = 0.00001; # NWT Options linmeth = 1; iprnwt = 0; ibotav = 0; options = 'SPECIFIED'; # Under Relaxation Input dbdtheta = 0.7; dbdkappa = 0.0001; dbdgamma = 0.0; momfact = 0.1; #Residual Control backflag = 0; maxbackiter = 50; backtol = 1.2; backreduce = 0.75; # Linear Solution Control and Options for GMRES maxitinner = 50; ilumethod = 2; levfill = 1; stoptol = 1e-10; msdr = 10; # Linear Solution Control and Options for xMD iacl = 2; norder = 1; level = 1; north = 2; iredsys = 0; rrctols = 0.0; idroptol = 1; epsrn = 1e-3; hclosexmd = 1e-4; mxiterxmd = 50; filename = GSFLOW_indir + slashstr + infile_pre + '.nwt' headings = ['NWT Input File', 'Test Problem 3 for MODFLOW-NWT'] # ------------------------------------------------------------------------- fobj = open(filename, 'w+'); # item 0 ------- for head0 in headings: fobj.write('# ' + head0 + '\n') # item 1 ------- fobj.write('%10.3e %10.3e %4d %10.3e %d %d %d ' % (headtol, fluxtol, maxiterout, thickfact, linmeth, iprnwt, ibotav)) fobj.write('%s ' % (options)) if options == 'SPECIFIED': fobj.write('%10.3g %10.3g %10.3g %10.3g %d ' % (dbdtheta, dbdkappa, dbdgamma, momfact, backflag)) if backflag > 0: fobj.write('%d %10.3g %10.3' % (maxbackiter, backtol, backreduce)) fobj.write('\n'); # item 2a ------- if linmeth == 1: fobj.write('%4d %d %d %10.3g %2d' % (maxitinner, ilumethod, levfill, stoptol, msdr)) # item 2b ------- elif linmeth == 2: fobj.write('%d %d %2d %2d %d %10.3g %d %10.3g %10.3g %4d' % (iacl, norder, level, north, iredsys, rrctols, idroptol, epsrn, hclosexmd, mxiterxmd)) fobj.write('\n') fobj.close() # ------------------------------------------------------------------------- # End of the script
gpl-3.0
t-wissmann/qutebrowser
qutebrowser/utils/qtutils.py
13083
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2020 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. # FIXME:typing Can we have less "# type: ignore" in here? """Misc. utilities related to Qt. Module attributes: MAXVALS: A dictionary of C/Qt types (as string) mapped to their maximum value. MINVALS: A dictionary of C/Qt types (as string) mapped to their minimum value. MAX_WORLD_ID: The highest world ID allowed in this version of QtWebEngine. """ import io import operator import contextlib import typing import pkg_resources from PyQt5.QtCore import (qVersion, QEventLoop, QDataStream, QByteArray, QIODevice, QSaveFile, QT_VERSION_STR, PYQT_VERSION_STR, QFileDevice, QObject) from PyQt5.QtGui import QColor from PyQt5.QtWidgets import QApplication try: from PyQt5.QtWebKit import qWebKitVersion except ImportError: # pragma: no cover qWebKitVersion = None # type: ignore # noqa: N816 from qutebrowser.misc import objects from qutebrowser.utils import usertypes MAXVALS = { 'int': 2 ** 31 - 1, 'int64': 2 ** 63 - 1, } MINVALS = { 'int': -(2 ** 31), 'int64': -(2 ** 63), } class QtOSError(OSError): """An OSError triggered by a QFileDevice. Attributes: qt_errno: The error attribute of the given QFileDevice, if applicable. """ def __init__(self, dev: QFileDevice, msg: str = None) -> None: if msg is None: msg = dev.errorString() super().__init__(msg) self.qt_errno = None # type: typing.Optional[QFileDevice.FileError] try: self.qt_errno = dev.error() except AttributeError: pass def version_check(version: str, exact: bool = False, compiled: bool = True) -> bool: """Check if the Qt runtime version is the version supplied or newer. Args: version: The version to check against. exact: if given, check with == instead of >= compiled: Set to False to not check the compiled version. """ if compiled and exact: raise ValueError("Can't use compiled=True with exact=True!") parsed = pkg_resources.parse_version(version) op = operator.eq if exact else operator.ge result = op(pkg_resources.parse_version(qVersion()), parsed) if compiled and result: # qVersion() ==/>= parsed, now check if QT_VERSION_STR ==/>= parsed. result = op(pkg_resources.parse_version(QT_VERSION_STR), parsed) if compiled and result: # FInally, check PYQT_VERSION_STR as well. result = op(pkg_resources.parse_version(PYQT_VERSION_STR), parsed) return result # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-69904 MAX_WORLD_ID = 256 if version_check('5.11.2') else 11 def is_new_qtwebkit() -> bool: """Check if the given version is a new QtWebKit.""" assert qWebKitVersion is not None return (pkg_resources.parse_version(qWebKitVersion()) > pkg_resources.parse_version('538.1')) def is_single_process() -> bool: """Check whether QtWebEngine is running in single-process mode.""" if objects.backend == usertypes.Backend.QtWebKit: return False args = QApplication.instance().arguments() return '--single-process' in args def check_overflow(arg: int, ctype: str, fatal: bool = True) -> int: """Check if the given argument is in bounds for the given type. Args: arg: The argument to check ctype: The C/Qt type to check as a string. fatal: Whether to raise exceptions (True) or truncate values (False) Return The truncated argument if fatal=False The original argument if it's in bounds. """ maxval = MAXVALS[ctype] minval = MINVALS[ctype] if arg > maxval: if fatal: raise OverflowError(arg) return maxval elif arg < minval: if fatal: raise OverflowError(arg) return minval else: return arg def ensure_valid(obj: QObject) -> None: """Ensure a Qt object with an .isValid() method is valid.""" if not obj.isValid(): raise QtValueError(obj) def check_qdatastream(stream: QDataStream) -> None: """Check the status of a QDataStream and raise OSError if it's not ok.""" status_to_str = { QDataStream.Ok: "The data stream is operating normally.", QDataStream.ReadPastEnd: ("The data stream has read past the end of " "the data in the underlying device."), QDataStream.ReadCorruptData: "The data stream has read corrupt data.", QDataStream.WriteFailed: ("The data stream cannot write to the " "underlying device."), } if stream.status() != QDataStream.Ok: raise OSError(status_to_str[stream.status()]) def serialize(obj: QObject) -> QByteArray: """Serialize an object into a QByteArray.""" data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) serialize_stream(stream, obj) return data def deserialize(data: QByteArray, obj: QObject) -> None: """Deserialize an object from a QByteArray.""" stream = QDataStream(data, QIODevice.ReadOnly) deserialize_stream(stream, obj) def serialize_stream(stream: QDataStream, obj: QObject) -> None: """Serialize an object into a QDataStream.""" check_qdatastream(stream) stream << obj # pylint: disable=pointless-statement check_qdatastream(stream) def deserialize_stream(stream: QDataStream, obj: QObject) -> None: """Deserialize a QDataStream into an object.""" check_qdatastream(stream) stream >> obj # pylint: disable=pointless-statement check_qdatastream(stream) @contextlib.contextmanager def savefile_open( filename: str, binary: bool = False, encoding: str = 'utf-8' ) -> typing.Iterator[typing.Union['PyQIODevice', io.TextIOWrapper]]: """Context manager to easily use a QSaveFile.""" f = QSaveFile(filename) cancelled = False try: open_ok = f.open(QIODevice.WriteOnly) if not open_ok: raise QtOSError(f) if binary: new_f = PyQIODevice( f) # type: typing.Union[PyQIODevice, io.TextIOWrapper] else: new_f = io.TextIOWrapper(PyQIODevice(f), # type: ignore encoding=encoding) yield new_f new_f.flush() except: f.cancelWriting() cancelled = True raise finally: commit_ok = f.commit() if not commit_ok and not cancelled: raise QtOSError(f, msg="Commit failed!") def qcolor_to_qsscolor(c: QColor) -> str: """Convert a QColor to a string that can be used in a QStyleSheet.""" ensure_valid(c) return "rgba({}, {}, {}, {})".format( c.red(), c.green(), c.blue(), c.alpha()) class PyQIODevice(io.BufferedIOBase): """Wrapper for a QIODevice which provides a python interface. Attributes: dev: The underlying QIODevice. """ def __init__(self, dev: QIODevice) -> None: super().__init__() self.dev = dev def __len__(self) -> int: return self.dev.size() def _check_open(self) -> None: """Check if the device is open, raise ValueError if not.""" if not self.dev.isOpen(): raise ValueError("IO operation on closed device!") def _check_random(self) -> None: """Check if the device supports random access, raise OSError if not.""" if not self.seekable(): raise OSError("Random access not allowed!") def _check_readable(self) -> None: """Check if the device is readable, raise OSError if not.""" if not self.dev.isReadable(): raise OSError("Trying to read unreadable file!") def _check_writable(self) -> None: """Check if the device is writable, raise OSError if not.""" if not self.writable(): raise OSError("Trying to write to unwritable file!") def open(self, mode: QIODevice.OpenMode) -> contextlib.closing: """Open the underlying device and ensure opening succeeded. Raises OSError if opening failed. Args: mode: QIODevice::OpenMode flags. Return: A contextlib.closing() object so this can be used as contextmanager. """ ok = self.dev.open(mode) if not ok: raise QtOSError(self.dev) return contextlib.closing(self) def close(self) -> None: """Close the underlying device.""" self.dev.close() def fileno(self) -> int: raise io.UnsupportedOperation def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: self._check_open() self._check_random() if whence == io.SEEK_SET: ok = self.dev.seek(offset) elif whence == io.SEEK_CUR: ok = self.dev.seek(self.tell() + offset) elif whence == io.SEEK_END: ok = self.dev.seek(len(self) + offset) else: raise io.UnsupportedOperation("whence = {} is not " "supported!".format(whence)) if not ok: raise QtOSError(self.dev, msg="seek failed!") return self.dev.pos() def truncate(self, size: int = None) -> int: raise io.UnsupportedOperation @property def closed(self) -> bool: return not self.dev.isOpen() def flush(self) -> None: self._check_open() self.dev.waitForBytesWritten(-1) def isatty(self) -> bool: self._check_open() return False def readable(self) -> bool: return self.dev.isReadable() def readline(self, size: int = -1) -> QByteArray: self._check_open() self._check_readable() if size < 0: qt_size = 0 # no maximum size elif size == 0: return QByteArray() else: qt_size = size + 1 # Qt also counts the NUL byte if self.dev.canReadLine(): buf = self.dev.readLine(qt_size) else: if size < 0: buf = self.dev.readAll() else: buf = self.dev.read(size) if buf is None: raise QtOSError(self.dev) return buf # type: ignore def seekable(self) -> bool: return not self.dev.isSequential() def tell(self) -> int: self._check_open() self._check_random() return self.dev.pos() def writable(self) -> bool: return self.dev.isWritable() def write(self, data: str) -> int: # type: ignore self._check_open() self._check_writable() num = self.dev.write(data) # type: ignore if num == -1 or num < len(data): raise QtOSError(self.dev) return num def read(self, size: typing.Optional[int] = None) -> QByteArray: self._check_open() self._check_readable() if size in [None, -1]: buf = self.dev.readAll() else: buf = self.dev.read(size) # type: ignore if buf is None: raise QtOSError(self.dev) return buf class QtValueError(ValueError): """Exception which gets raised by ensure_valid.""" def __init__(self, obj: QObject) -> None: try: self.reason = obj.errorString() except AttributeError: self.reason = None err = "{} is not valid".format(obj) if self.reason: err += ": {}".format(self.reason) super().__init__(err) class EventLoop(QEventLoop): """A thin wrapper around QEventLoop. Raises an exception when doing exec_() multiple times. """ def __init__(self, parent: QObject = None) -> None: super().__init__(parent) self._executing = False def exec_( self, flags: QEventLoop.ProcessEventsFlag = QEventLoop.AllEvents ) -> int: """Override exec_ to raise an exception when re-running.""" if self._executing: raise AssertionError("Eventloop is already running!") self._executing = True status = super().exec_(flags) # type: ignore self._executing = False return status
gpl-3.0
stan-dev/pystan
tests/test_sample_exceptions.py
593
"""Tests for sampling related exceptions.""" import pytest import stan # program code designed to generate initialization failed error program_code = "parameters { real y; } model { y ~ uniform(10, 20); }" "" def test_initialization_failed(): posterior = stan.build(program_code, random_seed=1) with pytest.raises(RuntimeError, match=r"Initialization failed."): posterior.sample(num_chains=1) # run a second time, in case there are interactions with caching with pytest.raises(RuntimeError, match=r"Initialization failed."): posterior.sample(num_chains=1)
gpl-3.0
apelttom/AlgoritmosDeOrdenamiento
sorting/algs/impl/TopDownMergeSorter.java
1253
package pe.edu.pucp.algorithms.sorting.algs.impl; /** * Implementation of Top-Down Merge Sort algorithm. Based on the implementation * described in Robert Sedgewick's Algorithm book. * * @author Carlos Gavidia ([email protected]) * * @param <T> * Type of the array to be sorted */ public class TopDownMergeSorter<T extends Comparable<T>> extends MergeSorter<T> { public TopDownMergeSorter(Class<T> clazz, T[] data) { super(clazz, data); } /* * (non-Javadoc) * * @see pe.edu.pucp.algorithms.sorting.algs.BaseSorter#sortData() */ @Override public void sortData() { sortData(0, getLength() - 1); } /** * Sorting method that allows recursion. * * @param lowerIndex * Lower index. * @param higherIndex * Higher index. */ private void sortData(int lowerIndex, int higherIndex) { if (higherIndex <= lowerIndex) { return; } int midIndex = lowerIndex + (higherIndex - lowerIndex) / 2; sortData(lowerIndex, midIndex); sortData(midIndex + 1, higherIndex); merge(lowerIndex, midIndex, higherIndex); } }
gpl-3.0
mywot/firefox
data/settings.js
7558
/* content/settings.js Copyright © 2009 - 2012 WOT Services Oy <[email protected]> This file is part of WOT. WOT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WOT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with WOT. If not, see <http://www.gnu.org/licenses/>. */ wot.settings = { trigger: /^http(s)?\:\/\/(www\.)?mywot\.com\/([^\/]{2}(-[^\/]+)?\/)?settings\/.+/, forward: /^http(s)?\:\/\/(www\.)?mywot\.com\/([^\/]{2}(-[^\/]+)?\/)?settings(\/([^\/]+))?\/?$/, match: 6, addscript: function(js) { try { var script = unsafeWindow.document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("comment", "mywot"); script.text = js; var body = unsafeWindow.document.getElementsByTagName("body"); if (body && body.length > 0) { body[0].appendChild(script); } } catch (e) { wot.flog("settings.addscript: failed with ", e); } }, savesearch: function() { var state = {}; var inputs = document.getElementsByClassName("wotsearchpref"); for (var i = 0; i < inputs.length; ++i) { var attrs = {}; [ "id", "type" ].forEach(function(item) { attrs[item] = inputs[i].getAttribute(item); }); if (!/^wotsearch-/.test(attrs.id) || attrs.type != "checkbox" || inputs[i].checked) { continue; } var m = /^wotsearch-(.+)$/.exec(attrs.id); if (m && m[1]) { state[m[1]] = true; wot.log("settings.savesearch: disabled: " + attrs.id); } } wot.prefs.set("search:state", state); }, savesetting: function(elem) { var attrs = {}; [ "wotpref", "id", "type", "value" ].forEach(function(item) { attrs[item] = elem.getAttribute(item); }); if (!attrs.wotpref || !attrs.id || !attrs.type || /^wotsearch-/.test(attrs.id)) { return; } if (attrs.type == "checkbox" || attrs.type == "radio") { if (attrs.wotpref == "bool") { wot.prefs.set(attrs.id, !!elem.checked); } else { wot.log("settings.savesetting: " + attrs.type + " cannot be " + attrs.wotpref + "\n"); } } else { if (attrs.value == null) { if (attrs.wotpref == "string") { attrs.value = ""; } else { wot.log("settings.savesetting: missing value for " + attrs.id + "\n"); return; } } switch (attrs.wotpref) { case "string": wot.prefs.set(attrs.id, attrs.value.toString()); break; case "bool": wot.prefs.set(attrs.id, (attrs.value == "true")); break; case "int": wot.prefs.set(attrs.id, Number(attrs.value)); break; default: wot.log("settings.savesetting: unknown type " + attrs.wotpref + "\n"); break; } } }, saveinputs: function() { var inputs = document.getElementsByTagName("input"); for (var i = 0; i < inputs.length; ++i) { this.savesetting(inputs[i]); } }, save: function() { try { var save = document.getElementById("wotsave"); if (save) { var saveclass = save.getAttribute("class"); if (saveclass && saveclass.indexOf("disabled") >= 0) { return; } } this.saveinputs(); this.savesearch(); this.addscript("wotsettings_saved();"); } catch (e) { wot.log("settings.save: failed with " + e + "\n"); this.addscript("wotsettings_failed();"); } }, loadsearch: function() { var elem = document.getElementById("wotsearch"); if (!elem) { return; } var preftype = elem.getAttribute("wotpref"); if (preftype != "input") { return; } wot.prefs.get("search:state", function(name, state) { state = state || {}; wot.prefs.get("update:state", function(name, update) { update = update || { search: [] }; /* sort by display name */ update.search.sort(function(a, b) { if (a.display < b.display) { return -1; } if (a.display > b.display) { return 1; } return 0; }); update.search.forEach(function(item) { if (!item.display) { return; } var id = "wotsearch-" + item.name; var input = document.createElement("input"); var label = document.createElement("label"); input.setAttribute("id", id); input.setAttribute("class", "wotsearchpref"); input.setAttribute("type", "checkbox"); input.setAttribute("wotpref", "bool"); input.checked = !state[item.name]; label.setAttribute("for", id); label.innerText = item.display; elem.appendChild(input); elem.appendChild(label); elem.appendChild(document.createElement("br")); wot.log("settings.loadsearch: added " + id + "\n"); }); }); }); }, loadsetting: function(elem) { var attrs = {}; [ "wotpref", "id", "type" ].forEach(function(item) { attrs[item] = elem.getAttribute(item); }); if (!attrs.wotpref || !attrs.id || !attrs.type) { return; } var value = wot.prefs.get(attrs.id); if (value == null) { wot.flog("settings.loadsetting: " + attrs.id + " missing"); } else if (attrs.type == "checkbox" || attrs.type == "radio") { wot.flog("settings.loadsetting: " + attrs.id + " = " + !!value); elem.checked = !!value; } else { elem.setAttribute("value", value.toString()); } }, loadinputs: function() { wot.log("settings.loadinputs()"); var inputs = document.getElementsByTagName("input"); for (var i = 0; i < inputs.length; ++i) { this.loadsetting(inputs[i]); } }, load: function() { wot.flog("settings.load()"); try { this.loadinputs(); this.loadsearch(); [ "wotsave", "wotnext" ].forEach(function(id) { var elem = document.getElementById(id); if (elem) { elem.addEventListener("click", function() { wot.settings.save(); }, false); } }); /* TODO: levels */ // wot.bind("prefs:ready", function() { wot.settings.addscript("wotsettings_ready();"); wot.flog("settings.load: done\n"); // }); } catch (e) { wot.flog("settings.load: failed with ", e); } }, onload: function() { wot.log("settings.onload()"); if (window != window.top) { return; /* ignore the settings page if it's in a frame */ } var match = window.location.href.match(this.forward); wot.log("settings : match = " + match); if (match) { /* redirect to the correct settings language and version */ var section = match[this.match]; /* make sure we have set up authentication cookies */ wot.bind("my:ready", function() { wot.log("settings.my.ready | enter", wot.language); // parts of proper settings' page's url var components = [ wot.urls.settings, window.navigator.language, wot.platform, wot.version ]; if (section) components.push(section); // change location window.location.href = components.join("/"); }); } else if (this.trigger.test(window.location.href)) { /* load settings for this page */ document.addEventListener("DOMContentLoaded", function() { wot.settings.load(); }, false); if (document.readyState == "complete") { wot.settings.load(); } } wot.listen(); } }; wot.source = "Injection"; wot.initialize(function(){ wot.log('Injection inited'); wot.settings.onload(); });
gpl-3.0
thumty/thumty
thumty-server/src/test/java/org/eightlog/thumty/server/params/ThumbTrimTest.java
2704
package org.eightlog.thumty.server.params; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; /** * @author Iliya Grushevskiy <[email protected]> */ public class ThumbTrimTest { @Test public void shouldCheckCanParse() throws Exception { assertThat(ThumbTrim.canParse("trim")).isTrue(); assertThat(ThumbTrim.canParse("trim:1")).isTrue(); assertThat(ThumbTrim.canParse("trim:1.2")).isTrue(); assertThat(ThumbTrim.canParse("trim:top-left")).isTrue(); assertThat(ThumbTrim.canParse("trim:top-left:1")).isTrue(); assertThat(ThumbTrim.canParse("trim:top-left:1.2")).isTrue(); assertThat(ThumbTrim.canParse("trim:bottom-right")).isTrue(); assertThat(ThumbTrim.canParse("trim:bottom-right:1")).isTrue(); assertThat(ThumbTrim.canParse("trim:bottom-right:1.2")).isTrue(); assertThat(ThumbTrim.canParse("trim:")).isFalse(); assertThat(ThumbTrim.canParse("trim:1.1.")).isFalse(); assertThat(ThumbTrim.canParse("trim:1-2")).isFalse(); assertThat(ThumbTrim.canParse("trim:topleft")).isFalse(); assertThat(ThumbTrim.canParse("trim:top-left1")).isFalse(); assertThat(ThumbTrim.canParse("trim:top-left 1.2")).isFalse(); assertThat(ThumbTrim.canParse("trim:bottomright")).isFalse(); assertThat(ThumbTrim.canParse("trim:bottom-right1")).isFalse(); assertThat(ThumbTrim.canParse("trim:bottom-right 1.2")).isFalse(); } @Test public void shouldParse() throws Exception { assertThat(ThumbTrim.parse("trim")).isEqualTo(new ThumbTrim(0, 0, 0)); assertThat(ThumbTrim.parse("trim:1")).isEqualTo(new ThumbTrim(0, 0, 1)); assertThat(ThumbTrim.parse("trim:1.2")).isEqualTo(new ThumbTrim(0, 0, 1.2f)); assertThat(ThumbTrim.parse("trim:top-left")).isEqualTo(new ThumbTrim(0, 0, 0)); assertThat(ThumbTrim.parse("trim:top-left:1")).isEqualTo(new ThumbTrim(0, 0, 1)); assertThat(ThumbTrim.parse("trim:top-left:1.2")).isEqualTo(new ThumbTrim(0, 0, 1.2f)); assertThat(ThumbTrim.parse("trim:bottom-right")).isEqualTo(new ThumbTrim(1, 1, 0)); assertThat(ThumbTrim.parse("trim:bottom-right:1")).isEqualTo(new ThumbTrim(1, 1, 1)); assertThat(ThumbTrim.parse("trim:bottom-right:1.2")).isEqualTo(new ThumbTrim(1, 1, 1.2f)); } @Test public void shouldFormat() throws Exception { assertThat(new ThumbTrim(0, 0, 1).toString()).isEqualTo("trim:top-left:1.0"); assertThat(new ThumbTrim(1, 1, 1).toString()).isEqualTo("trim:bottom-right:1.0"); assertThat(new ThumbTrim(1, 1, 1.23f).toString()).isEqualTo("trim:bottom-right:1.23"); } }
gpl-3.0
TomasTomecek/dockpulp
dockpulp/imgutils.py
5479
# This file is part of dockpulp. # # dockpulp is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # dockpulp is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with dockpulp. If not, see <http://www.gnu.org/licenses/>. import contextlib import os import tarfile import simplejson as json # see https://github.com/pulp/pulp_docker/blob/master/common/pulp_docker/common/tarutils.py def get_metadata(tarfile_path): """ Given a path to a tarfile, which is itself the product of "docker save", this discovers what images (layers) exist in the archive and returns metadata about each. """ metadata = [] with contextlib.closing(tarfile.open(tarfile_path)) as archive: for member in archive.getmembers(): # find the "json" files, which contain all image metadata if os.path.basename(member.path) == 'json': image_data = json.load(archive.extractfile(member)) metadata.append(image_data) return metadata def get_metadata_pulp(md): """ Go through read metadata and figure out parents, IDs, and sizes. Current fields in metadata: parent: ID of the parent image, or None if there is none size: size in bytes as reported by docker """ details = {} # At some point between docker 0.10 and 1.0, it changed behavior # of whether these keys are capitalized or not. for image_data in md: image_id = image_data.get('id', image_data.get('Id')) details[image_id] = { 'parent': image_data.get('parent', image_data.get('Parent')), 'size': image_data.get('size', image_data.get('Size')) } return details def get_versions(md): """ Inspect the docker version used with the construction of each layer in an image. Return a dict of image-IDs to versions. """ vers = {} for data in md: image_id = data.get('id', data.get('Id')) vers[image_id] = data['docker_version'] return vers def check_repo(tarfile_path): """ Confirm the image has a "repositories" file where it should. The return code indicates the results of the check. 0 - repositories file is good, it passes the check 1 - repositories file is missing 2 - more than 1 repository is defined in the file, pulp requires 1 3 - repositories file references image IDs not in the tarball itself """ found = False repo_data = None seen_ids = [] with contextlib.closing(tarfile.open(tarfile_path)) as archive: for member in archive.getmembers(): # member.path can be: "repositories" or "./repositories" if os.path.basename(member.path) == "repositories": repo_data = json.load(archive.extractfile(member)) found = True if len(repo_data.keys()) != 1: return 2 else: seen_ids.append(os.path.basename(member.path)) val = repo_data.popitem()[1] # don't care about repo name at all for ver, iid in val.items(): if iid not in seen_ids: return 3 if found == False: return 1 return 0 def _get_hops(iid, md, hops=0): """ return how many parents (layers) an image has """ par = md[iid].get('parent', None) if par != None: return _get_hops(par, md, hops=hops+1) else: return hops def get_id(tarfile_path): """ Return the ID for this particular image, ignoring heritage and children """ meta_raw = get_metadata(tarfile_path) metadata = get_metadata_pulp(meta_raw) return get_top_layer(metadata) def get_top_layer(metadata): """ Returns the ID as get_id does, but starts with pulp image metadata. Provided for compatibility with atomic-reactor. """ images = metadata.keys() parents = 0 youngest = images[0] for image in images: pars = _get_hops(image, metadata) if pars > parents: youngest = image parents = pars return youngest # not used, might be useful later def get_ancestry(image_id, metadata): """ Given an image ID and metadata about each image, this calculates and returns the ancestry list for that image. It walks the "parent" relationship in the metadata to assemble the list, which is ordered with the child leaf at the top. """ image_ids = [] while image_id: image_ids.append(image_id) image_id = metadata[image_id].get('parent') return tuple(image_ids) def get_top_layer(pulp_md): """ Find the top (youngest) layer. """ # Find layers that are parents layers = set() parents = set() for img_hash, value in pulp_md.iteritems(): layers.add(img_hash) if 'parent' in value: parents.add(value['parent']) else: # Base layer has no 'parent' but it itself a parent parents.add(img_hash) # Any layers not parents are the youngest. return list(layers - parents)[0]
gpl-3.0
idega/platform2
src/com/idega/core/component/data/ICObjectBMPBean.java
12077
//idega 2001 - Tryggvi Larusson /* *Copyright 2001 idega.is All Rights Reserved. */ package com.idega.core.component.data; //import java.util.*; import java.sql.SQLException; import java.text.Collator; import java.util.Collection; import java.util.List; import java.util.Vector; import javax.ejb.FinderException; import com.idega.core.file.data.ICFile; import com.idega.data.EntityFinder; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.data.query.MatchCriteria; import com.idega.data.query.SelectQuery; import com.idega.data.query.Table; import com.idega.data.query.WildCardColumn; import com.idega.exception.IWBundleDoesNotExist; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.PresentationObject; import com.idega.repository.data.RefactorClassRegistry; /** *@author <a href="mailto:[email protected]">Tryggvi Larusson</a> *@version 1.3 */ public class ICObjectBMPBean extends com.idega.data.GenericEntity implements ICObject { public static final String COMPONENT_TYPE_ELEMENT = "iw.element"; public static final String COMPONENT_TYPE_BLOCK = "iw.block"; public static final String COMPONENT_TYPE_APPLICATION = "iw.application"; public static final String COMPONENT_TYPE_APPLICATION_COMPONENT = "iw.application.component"; public static final String COMPONENT_TYPE_DATA = "iw.data"; public static final String COMPONENT_TYPE_HOME = "iw.home"; public static final String COMPONENT_TYPE_PROPERTYHANDLER = "iw.propertyhandler"; public static final String COMPONENT_TYPE_INPUTHANDLER = "iw.inputhandler"; public static final String COMPONENT_TYPE_SEARCH_PLUGIN = "iw.searchplugin"; private static final String object_type_column_name = "OBJECT_TYPE"; private static final String class_name_column_name = "CLASS_NAME"; private final static String BUNDLE_COLUMN_NAME = "BUNDLE"; private final static String class_value_column_name = "CLASS_VALUE"; private final static String icon_file = "ICON_FILE"; private static final String COLUMN_OBJECT_NAME = "OBJECT_NAME"; public ICObjectBMPBean() { super(); } public ICObjectBMPBean(int id) throws SQLException { super(id); } public void initializeAttributes() { //par1: column name, par2: visible column name, par3-par4: editable/showable, par5 ... addAttribute(getIDColumnName()); addAttribute(getColumnObjectName(), "Name", true, true, java.lang.String.class); addAttribute(getClassNameColumnName(), "Class Name", true, true, java.lang.String.class); addAttribute(getObjectTypeColumnName(), "Class Name", true, true, java.lang.String.class, "one-to-many", ICObjectType.class); addAttribute(getBundleColumnName(), "Bundle", true, true, java.lang.String.class, 1000); addManyToOneRelationship(getColumnClassValue(), "Class File", ICFile.class); addManyToOneRelationship(getColumnIcon(), "Icon", ICFile.class); //addAttribute("settings_url","Sl?? stillingas??u",true,true,"java.lang.String"); //addAttribute("class_value","Klasi sj?lfur",true,true,"java.sql.Blob"); //addAttribute("small_icon_image_id","Icon 16x16 (.gif)",false,false,"java.lang.Integer","many-to-one","com.idega.data.genericentity.Image"); //addAttribute("small_icon_image_id","Icon 16x16 (.gif)",false,false,java.lang.Integer.class); //addAttribute("image_id","MyndN?mer",false,false,"java.lang.Integer","one-to-many","com.idega.projects.golf.entity.ImageEntity"); getEntityDefinition().setBeanCachingActiveByDefault(true); } private String getColumnObjectName() { return COLUMN_OBJECT_NAME; } public static String getObjectTypeColumnName() { return object_type_column_name; } public static String getClassNameColumnName() { return class_name_column_name; } public static String getColumnClassValue() { return class_value_column_name; } public static String getColumnIcon() { return icon_file; } private static List componentList; public static List getAvailableComponentTypes() { try { ICObjectTypeHome gtHome = (ICObjectTypeHome) IDOLookup.getHome(ICObjectType.class); List list = new Vector(gtHome.findAll()); return list; } catch (IDOLookupException e) { e.printStackTrace(); } catch (FinderException e1) { e1.printStackTrace(); } return getAvailableComponentTypesOld(); } private static List getAvailableComponentTypesOld() { if (componentList == null) { componentList = new Vector(); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_ELEMENT); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_BLOCK); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_APPLICATION); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_APPLICATION_COMPONENT); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_DATA); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_HOME); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_PROPERTYHANDLER); componentList.add(com.idega.core.component.data.ICObjectBMPBean.COMPONENT_TYPE_SEARCH_PLUGIN); } return componentList; } public static ICObject getICObject(String className) { try { List l = EntityFinder.findAllByColumn(getStaticInstance(ICObject.class), getClassNameColumnName(), className); return (ICObject) l.get(0); } catch (Exception e) { return null; } } public static void removeICObject(String className) { try { ICObject instance = (ICObject) com.idega.data.GenericEntity.getStaticInstance(ICObject.class); instance.deleteMultiple(getClassNameColumnName(), className); } catch (Exception e) { } } public void insertStartData() throws Exception { /*ICObject obj = ((com.idega.core.data.ICObjectHome)com.idega.data.IDOLookup.getHomeLegacy(ICObject.class)).createLegacy(); obj.setName("Table"); obj.setObjectClass(Table.class); obj.setObjectType("iw.element"); obj.insert(); obj = ((com.idega.core.data.ICObjectHome)com.idega.data.IDOLookup.getHomeLegacy(ICObject.class)).createLegacy(); obj.setName("Image"); obj.setObjectClass(com.idega.presentation.Image.class); obj.setObjectType("iw.element"); obj.insert(); obj = ((com.idega.core.data.ICObjectHome)com.idega.data.IDOLookup.getHomeLegacy(ICObject.class)).createLegacy(); obj.setName("NewsModule"); obj.setObjectClass(NewsReader.class); obj.setObjectType("iw.block"); obj.insert(); obj = ((com.idega.core.data.ICObjectHome)com.idega.data.IDOLookup.getHomeLegacy(ICObject.class)).createLegacy(); obj.setName("TextModule"); obj.setObjectClass(TextReader.class); obj.setObjectType("iw.block"); obj.insert(); obj = ((com.idega.core.data.ICObjectHome)com.idega.data.IDOLookup.getHomeLegacy(ICObject.class)).createLegacy(); obj.setName("LoginModule"); obj.setObjectClass(Login.class); obj.setObjectType("iw.block"); obj.insert();*/ } public String getEntityName() { return "IC_OBJECT"; } public void setDefaultValues() { //setColumn("image_id",1); //setColumn("small_icon_image_id",1); //setObjectType("iw.block"); } public String getName() { return getStringColumnValue(getColumnObjectName()); } public void setName(String object_name) { setColumn(getColumnObjectName(), object_name); } public String getClassName() { return getStringColumnValue(getClassNameColumnName()); } public void setClassName(String className) { setColumn(getClassNameColumnName(), className); } public Class getObjectClass() throws ClassNotFoundException { String className = getClassName(); if (className != null) { return RefactorClassRegistry.forName(className); } else { //throw new ClassNotFoundException("Class NULL not found"); return null; } } public void setObjectClass(Class c) { setClassName(c.getName()); } public PresentationObject getNewInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException { return (PresentationObject) getObjectClass().newInstance(); } public String getObjectType() { return getStringColumnValue(getObjectTypeColumnName()); } public void setObjectType(String objectType) { setColumn(getObjectTypeColumnName(), objectType); } public String getBundleIdentifier() { return getStringColumnValue(getBundleColumnName()); } public void setBundleIdentifier(String bundleIdentifier) { setColumn(getBundleColumnName(), bundleIdentifier); } public void setBundle(IWBundle bundle) { setBundleIdentifier(bundle.getBundleIdentifier()); } public IWBundle getBundle(IWMainApplication iwma)throws IWBundleDoesNotExist { return iwma.getBundle(getBundleIdentifier()); } public static String getBundleColumnName() { return BUNDLE_COLUMN_NAME; } public Collection ejbFindAll() throws FinderException { return idoFindAllIDsBySQL(); } public Collection ejbFindAllByObjectType(String type) throws FinderException { //return super.idoFindPKsByQuery(super.idoQueryGetSelect().appendWhere().appendEqualsQuoted(this.getObjectTypeColumnName(), type)); Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table,ICObjectBMPBean.getObjectTypeColumnName(),MatchCriteria.EQUALS,type,true)); return idoFindPKsByQuery(query); } public Collection ejbFindAllByObjectTypeAndBundle(String type, String bundle) throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table,ICObjectBMPBean.getObjectTypeColumnName(),MatchCriteria.EQUALS,type,true)); query.addCriteria(new MatchCriteria(table,ICObjectBMPBean.getBundleColumnName(),MatchCriteria.EQUALS,bundle,true)); /* IDOQuery query = super.idoQueryGetSelect().appendWhere().appendEqualsQuoted(this.getObjectTypeColumnName(), type) .appendAndEqualsQuoted(this.getBundleColumnName(),bundle); */ //System.out.println(query.toString()); return super.idoFindPKsByQuery(query); } public Collection ejbFindAllByBundle(String bundle) throws FinderException{ //return super.idoFindPKsByQuery(super.idoQueryGetSelect().appendWhere().appendEqualsQuoted(this.getBundleColumnName(), bundle)); Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table,ICObjectBMPBean.getBundleColumnName(),MatchCriteria.EQUALS,bundle,true)); return idoFindPKsByQuery(query); } public Object ejbFindByClassName(String className) throws FinderException{ //return super.idoFindOnePKByQuery(super.idoQueryGetSelect().appendWhere().appendEqualsQuoted(getClassNameColumnName(), className)); Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table,ICObjectBMPBean.getClassNameColumnName(),MatchCriteria.EQUALS,className,true)); return idoFindOnePKByQuery(query); } public Collection ejbFindAllBlocksByBundle(String bundle) throws FinderException { return ejbFindAllByObjectTypeAndBundle(COMPONENT_TYPE_BLOCK, bundle); } public Collection ejbFindAllBlocks() throws FinderException { return ejbFindAllByObjectType(COMPONENT_TYPE_BLOCK); } public Collection ejbFindAllElementsByBundle(String bundle) throws FinderException { return ejbFindAllByObjectTypeAndBundle(COMPONENT_TYPE_ELEMENT, bundle); } public Collection ejbFindAllElements() throws FinderException { return ejbFindAllByObjectType(COMPONENT_TYPE_ELEMENT); } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object obj) { if (obj instanceof ICObject) { return Collator.getInstance().compare(this.getName(), ((ICObject)obj).getName()); } return super.compareTo(obj); } }
gpl-3.0
iptux/DroidUi
examples/intent.py
4234
# -*- coding: utf-8 -*- # # intent.py # extract intent constants from android.content.Intent # # Copyright (C) 2012-2015 Tommy Alex. All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # # Create: 2013-05-21 01:15 import DroidUi as Ui # standard intent constants # http://developer.android.com/reference/android/content/Intent.html ACTION = ( 'ACTION_MAIN', 'ACTION_VIEW', 'ACTION_ATTACH_DATA', 'ACTION_EDIT', 'ACTION_PICK', 'ACTION_CHOOSER', 'ACTION_GET_CONTENT', 'ACTION_DIAL', 'ACTION_CALL', 'ACTION_SEND', 'ACTION_SENDTO', 'ACTION_ANSWER', 'ACTION_INSERT', 'ACTION_DELETE', 'ACTION_RUN', 'ACTION_SYNC', 'ACTION_PICK_ACTIVITY', 'ACTION_SEARCH', 'ACTION_WEB_SEARCH', 'ACTION_FACTORY_TEST', ) BROADCAST = ( 'ACTION_TIME_TICK', 'ACTION_TIME_CHANGED', 'ACTION_TIMEZONE_CHANGED', 'ACTION_BOOT_COMPLETED', 'ACTION_PACKAGE_ADDED', 'ACTION_PACKAGE_CHANGED', 'ACTION_PACKAGE_REMOVED', 'ACTION_PACKAGE_RESTARTED', 'ACTION_PACKAGE_DATA_CLEARED', 'ACTION_UID_REMOVED', 'ACTION_BATTERY_CHANGED', 'ACTION_POWER_CONNECTED', 'ACTION_POWER_DISCONNECTED', 'ACTION_SHUTDOWN', ) CATEGORY = ( 'CATEGORY_DEFAULT', 'CATEGORY_BROWSABLE', 'CATEGORY_TAB', 'CATEGORY_ALTERNATIVE', 'CATEGORY_SELECTED_ALTERNATIVE', 'CATEGORY_LAUNCHER', 'CATEGORY_INFO', 'CATEGORY_HOME', 'CATEGORY_PREFERENCE', 'CATEGORY_TEST', 'CATEGORY_CAR_DOCK', 'CATEGORY_DESK_DOCK', 'CATEGORY_LE_DESK_DOCK', 'CATEGORY_HE_DESK_DOCK', 'CATEGORY_CAR_MODE', 'CATEGORY_APP_MARKET', ) EXTRA = ( 'EXTRA_ALARM_COUNT', 'EXTRA_BCC', 'EXTRA_CC', 'EXTRA_CHANGED_COMPONENT_NAME', 'EXTRA_DATA_REMOVED', 'EXTRA_DOCK_STATE', 'EXTRA_DOCK_STATE_HE_DESK', 'EXTRA_DOCK_STATE_LE_DESK', 'EXTRA_DOCK_STATE_CAR', 'EXTRA_DOCK_STATE_DESK', 'EXTRA_DOCK_STATE_UNDOCKED', 'EXTRA_DONT_KILL_APP', 'EXTRA_EMAIL', 'EXTRA_INITIAL_INTENTS', 'EXTRA_INTENT', 'EXTRA_KEY_EVENT', 'EXTRA_ORIGINATING_URI', 'EXTRA_PHONE_NUMBER', 'EXTRA_REFERRER', 'EXTRA_REMOTE_INTENT_TOKEN', 'EXTRA_REPLACING', 'EXTRA_SHORTCUT_ICON', 'EXTRA_SHORTCUT_ICON_RESOURCE', 'EXTRA_SHORTCUT_INTENT', 'EXTRA_STREAM', 'EXTRA_SHORTCUT_NAME', 'EXTRA_SUBJECT', 'EXTRA_TEMPLATE', 'EXTRA_TEXT', 'EXTRA_TITLE', 'EXTRA_UID', ) FLAG = ( 'FLAG_GRANT_READ_URI_PERMISSION', 'FLAG_GRANT_WRITE_URI_PERMISSION', 'FLAG_GRANT_PERSISTABLE_URI_PERMISSION', 'FLAG_GRANT_PREFIX_URI_PERMISSION', 'FLAG_DEBUG_LOG_RESOLUTION', 'FLAG_FROM_BACKGROUND', 'FLAG_ACTIVITY_BROUGHT_TO_FRONT', 'FLAG_ACTIVITY_CLEAR_TASK', 'FLAG_ACTIVITY_CLEAR_TOP', 'FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET', 'FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS', 'FLAG_ACTIVITY_FORWARD_RESULT', 'FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY', 'FLAG_ACTIVITY_MULTIPLE_TASK', 'FLAG_ACTIVITY_NEW_DOCUMENT', 'FLAG_ACTIVITY_NEW_TASK', 'FLAG_ACTIVITY_NO_ANIMATION', 'FLAG_ACTIVITY_NO_HISTORY', 'FLAG_ACTIVITY_NO_USER_ACTION', 'FLAG_ACTIVITY_PREVIOUS_IS_TOP', 'FLAG_ACTIVITY_RESET_TASK_IF_NEEDED', 'FLAG_ACTIVITY_REORDER_TO_FRONT', 'FLAG_ACTIVITY_SINGLE_TOP', 'FLAG_ACTIVITY_TASK_ON_HOME', 'FLAG_RECEIVER_REGISTERED_ONLY', ) def intent(): def write(file, dict, keys = None): if keys is None: keys = sorted(dict) for k in keys: try: v = dict[k] except KeyError: print('no such key:', k) continue try: v = int(v) if v > 10: v = hex(v) file.write('%s = %s\n' % (k, v)) except: file.write('%s = \'%s\'\n' % (k, v)) del dict[k] file.write('\n') f = open('intent.txt', 'w+') consts = Ui.Class('android.content.Intent').consts() for i in (ACTION, BROADCAST, CATEGORY, EXTRA, FLAG): write(f, consts, i) write(f, consts) f.close() if __name__ == '__main__': intent()
gpl-3.0
davqvist/CustomAchievements
src/main/java/com/davqvist/customachievements/block/BlockTrophy.java
7196
package com.davqvist.customachievements.block; import com.davqvist.customachievements.material.MaterialStandard; import com.davqvist.customachievements.reference.Reference; import com.davqvist.customachievements.tileentity.TileEntityTrophy; import com.davqvist.customachievements.utility.LogHelper; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.BlockHorizontal; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.ArrayList; import java.util.List; public class BlockTrophy extends Block implements ITileEntityProvider { protected AxisAlignedBB BOUNDING_BOX = new AxisAlignedBB( 0, 0, 0, 1, 0.0625 * 6, 1 ); public static final PropertyDirection FACING = BlockHorizontal.FACING; public BlockTrophy(){ super( MaterialStandard.STANDARD ); this.setCreativeTab( CreativeTabs.MISC ); setHardness( 1.5F ); this.setDefaultState( this.blockState.getBaseState().withProperty( FACING, EnumFacing.SOUTH ) ); setRegistryName( "trophy" ); this.setUnlocalizedName( "trophy" ); } @Override @SideOnly(Side.CLIENT) public void addInformation( ItemStack stack, EntityPlayer player, List<String> tooltip, boolean advanced ){ NBTTagCompound compound = stack.getTagCompound(); if( compound != null ){ if( compound.hasKey( "item" ) ){ ItemStack is = ItemStack.loadItemStackFromNBT( (NBTTagCompound) compound.getTag( "item" ) ); if( is != null ){ tooltip.add( "Item: " + is.getDisplayName() ); } } if( compound.hasKey( "player" ) ){ String splayer = compound.getString( "player" ); if( !splayer.isEmpty() ){ tooltip.add( "Player: " + splayer ); } } } } @Override public void onBlockPlacedBy( World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack ){ NBTTagCompound compound = stack.getTagCompound(); if( compound != null ){ TileEntity te = worldIn.getTileEntity( pos ); if( te instanceof TileEntityTrophy ){ if( compound.hasKey( "item" ) ){ ItemStack is = ItemStack.loadItemStackFromNBT( (NBTTagCompound) compound.getTag( "item" ) ); if( is != null ){ ((TileEntityTrophy) te).setItemStack( is ); } } if( compound.hasKey( "player" ) ){ String player = compound.getString( "player" ); if( !player.isEmpty() ){ ((TileEntityTrophy) te).setPlayer( player ); } } ((TileEntityTrophy) te).setFacing( placer.getHorizontalFacing().getOpposite() ); } } } @Override public IBlockState getStateForPlacement( World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, ItemStack stack ){ return this.getDefaultState().withProperty( FACING, placer.getHorizontalFacing().getOpposite() ); } @Override protected BlockStateContainer createBlockState(){ return new BlockStateContainer( this, new IProperty[] {FACING} ); } @Override public int getMetaFromState( IBlockState state ){ EnumFacing facing = (EnumFacing)state.getValue( FACING ); return facing.getHorizontalIndex(); } @Override public IBlockState getStateFromMeta( int meta ){ return this.getDefaultState().withProperty( FACING, EnumFacing.getHorizontal( meta ) ); } @Override public void breakBlock( World worldIn, BlockPos pos, IBlockState state ){ if( !worldIn.isRemote ){ TileEntity te = worldIn.getTileEntity( pos ); ItemStack stack = getItemFromBlock( worldIn, pos ); if( stack != null ){ worldIn.spawnEntityInWorld( new EntityItem( worldIn, pos.getX(), pos.getY(), pos.getZ(), stack ) ); } } super.breakBlock( worldIn, pos, state ); } @Override public boolean rotateBlock( World world, BlockPos pos, EnumFacing axis ){ TileEntity te = world.getTileEntity( pos ); if( te instanceof TileEntityTrophy ){ EnumFacing newfacing = ( (TileEntityTrophy) te).getFacing().rotateY(); ((TileEntityTrophy) te).setFacing( newfacing ); world.setBlockState( pos, world.getBlockState( pos ).withProperty( FACING, newfacing ) ); return true; } return false; } public ItemStack getPickBlock( IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player ){ return getItemFromBlock( world, pos ); } private ItemStack getItemFromBlock( World world, BlockPos pos ){ TileEntity te = world.getTileEntity( pos ); ItemStack stack = new ItemStack( Item.getItemFromBlock( this ) ); if( te instanceof TileEntityTrophy ){ NBTTagCompound compound = new NBTTagCompound(); compound = te.writeToNBT( compound ); stack.setTagCompound( compound ); } return stack; } @Override public List<ItemStack> getDrops( IBlockAccess world, BlockPos pos, IBlockState state, int fortune ){ return new ArrayList<ItemStack>(); } @Override public boolean isOpaqueCube( IBlockState blockState ){ return false; } @Override public TileEntity createNewTileEntity( World worldIn, int meta ){ return new TileEntityTrophy(); } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos ){ return BOUNDING_BOX; } @Override public String getUnlocalizedName(){ return String.format( "tile.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName( super.getUnlocalizedName() ) ); } protected String getUnwrappedUnlocalizedName( String unlocalizedName ){ return unlocalizedName.substring( unlocalizedName.indexOf(".") + 1 ); } }
gpl-3.0
tech-team/case-finder
src/main/java/proxy/ProxyInfo.java
2711
package proxy; public class ProxyInfo implements Comparable<ProxyInfo> { private String ip; private int port; private String country = ""; private int rating = 0; private int workingPerc = 0; private int responseTimePerc = 0; private int downloadSpeedPerc = 0; private int unreliability = 0; private int era; public ProxyInfo(String ip, int port) { this.ip = ip; this.port = port; } public ProxyInfo(String ip, int port, String country) { this.ip = ip; this.port = port; this.country = country; } public ProxyInfo(String ip, int port, String country, int rating, int workingPerc, int responseTimePerc, int downloadSpeedPerc) { this.ip = ip; this.port = port; this.country = country; this.rating = rating; this.workingPerc = workingPerc; this.responseTimePerc = responseTimePerc; this.downloadSpeedPerc = downloadSpeedPerc; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public int getWorkingPerc() { return workingPerc; } public void setWorkingPerc(int workingPerc) { this.workingPerc = workingPerc; } public int getResponseTimePerc() { return responseTimePerc; } public void setResponseTimePerc(int responseTimePerc) { this.responseTimePerc = responseTimePerc; } public int getDownloadSpeedPerc() { return downloadSpeedPerc; } public void setDownloadSpeedPerc(int downloadSpeedPerc) { this.downloadSpeedPerc = downloadSpeedPerc; } public void increaseReliability() { unreliability -= 1; } public void decreaseReliability() { decreaseReliability(1); } public int getUnreliability() { return unreliability; } @Override public int compareTo(ProxyInfo o) { return this.unreliability - o.unreliability; } public void decreaseReliability(int count) { unreliability += count; } public void setEra(int era) { this.era = era; } public int getEra() { return era; } @Override public String toString() { return ip + ":" + port; } }
gpl-3.0
muziekklas/TfsMigrationUtility
TFSMigrationUtility/TFSMigrationUtility.Core.Test/Properties/AssemblyInfo.cs
1434
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TFSMigrationUtility.Core.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TFSMigrationUtility.Core.Test")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e505c883-4c4a-4de5-951c-17053d808ef5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
brainly/ui-components
components/card-deck/src/js/vendor/closest-polyfil.js
290
// IE/Edge/OperaMini do not support Node.closest yet function closest(el, sel) { do { if ((el.matches && el.matches(sel)) || (el.matchesSelector && el.matchesSelector(sel))) { return el; } el = el.parentElement; } while (el); return null; } export default closest;
gpl-3.0
waikato-datamining/adams-base
adams-core/src/main/java/adams/flow/processor/GraphicalOutputProducingProcessor.java
1486
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphicalOutputProducingProcessor.java * Copyright (C) 2011-2018 University of Waikato, Hamilton, New Zealand */ package adams.flow.processor; import java.awt.Component; /** * Interface for processors that can generate graphical output. * * @author fracpete (fracpete at waikato dot ac dot nz) */ public interface GraphicalOutputProducingProcessor extends ActorProcessor { /** * Returns whether graphical output was generated. * * @return true if graphical output was generated */ public boolean hasGraphicalOutput(); /** * Returns the graphical output that was generated. * * @return the graphical output */ public Component getGraphicalOutput(); /** * Returns the title for the dialog. * * @return the title */ public String getTitle(); }
gpl-3.0
WorldGrower/WorldGrower
src/org/worldgrower/gui/ImageListRenderer.java
1955
/******************************************************************************* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.worldgrower.gui; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; class ImageListRenderer<T> implements ListCellRenderer<T> { private final DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer(); private final ImageIds[] imageIds; private final ImageInfoReader imageInfoReader; public ImageListRenderer(ImageIds[] imageIds, ImageInfoReader imageInfoReader) { super(); this.imageIds = imageIds; this.imageInfoReader = imageInfoReader; defaultRenderer.setOpaque(false); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); ImageIds id = imageIds[index]; if (id != null) { renderer.setIcon(new ImageIcon(imageInfoReader.getImage(id, null))); } return renderer; } }
gpl-3.0
demisang/yii2-dropbox-backup
BackupController.php
6449
<?php /** * @copyright Copyright (c) 2020 Ivan Orlov * @license https://github.com/demisang/yii2-dropbox-backup/blob/master/LICENSE * @link https://github.com/demisang/yii2-dropbox-backup#readme * @author Ivan Orlov <[email protected]> */ namespace demi\backup\dropbox; use Yii; use yii\helpers\Console; use yii\console\Controller; use yii\base\InvalidConfigException; use Spatie\Dropbox\Client; /** * Console command for doing backup and upload them to Dropbox * * @property-read \demi\backup\Component $component * @property-read Client $client */ class BackupController extends Controller { /** * Name of \demi\backup\Component in Yii components. Default Yii::$app->backup * * @var string */ public $backupComponent = 'backup'; /** * Dropbox app identifier. https://www.dropbox.com/developers/apps * * @var string */ public $dropboxAppKey; /** * Dropbox app secret. https://www.dropbox.com/developers/apps * * @var string */ public $dropboxAppSecret; /** * Dropbox access token for user which will be get up backups. * * To get this navigate to https://www.dropbox.com/developers/apps/info/<AppKey> * and press OAuth 2: Generated access token button. * * @var string */ public $dropboxAccessToken; /** * Path in the dropbox where would be saved backups * * @var string */ public $dropboxUploadPath = '/'; /** * [Optional] Guzzle Client instance for "spatie/dropbox-api" Client contructor * @see \Spatie\Dropbox\Client::__construct() * * @var \GuzzleHttp\Client */ public $guzzleClient; /** * [Optional] Set max chunk size per request (determines when to switch from "one shot upload" to upload session and * defines chunk size for uploads via session). * @see \Spatie\Dropbox\Client::__construct() * * @var int */ public $maxChunkSize = Client::MAX_CHUNK_SIZE; /** * [Optional] How many times to retry an upload session start or append after RequestException. * @see \Spatie\Dropbox\Client::__construct() * * @var int */ public $maxUploadChunkRetries = 0; /** @var bool if TRUE: will be deleted files in the dropbox when $expiryTime has come */ public $autoDelete = true; /** * Number of seconds after which the file is considered deprecated and will be deleted. * By default 1 month (2592000 seconds). * * @var int */ public $expiryTime = 2592000; /** * Dropbox SDK Client instance * * @var Client */ protected $_client; /** * @inheritdoc * @throws InvalidConfigException */ public function init() { if ($this->dropboxAccessToken === null && ($this->dropboxAppKey === null || $this->dropboxAppSecret === null)) { throw new InvalidConfigException('You must set "' . get_class($this) . '::$dropboxAccessToken" OR ($dropboxAppKey AND $dropboxAppSecret)'); } parent::init(); } /** * Run new backup creation and storing into Dropbox */ public function actionIndex() { // Make new backup $backupFile = $this->component->create(); // Get name for new dropbox file $dropboxFile = basename($backupFile); // Dropbox client instance $client = $this->client; // Read backup file $f = fopen($backupFile, 'rb'); // Upload to dropbox $client->upload($this->getFilePathWithDir($dropboxFile), $f); // Close backup file @fclose($f); $this->stdout('Backup file successfully uploaded into dropbox: ' . $dropboxFile . PHP_EOL, Console::FG_GREEN); if ($this->autoDelete) { // Auto removing files from dropbox that oldest of the expiry time $this->actionRotateOldFiles(); } // Cleanup server backups $this->component->deleteJunk(); } /** * Removing files from dropbox that oldest of the expiry time */ public function actionRotateOldFiles() { // Get all files from dropbox backups folder $files = $this->client->listFolder($this->dropboxUploadPath); $files = $files['entries']; // Calculate expired time $expiryDate = time() - $this->expiryTime; foreach ($files as $file) { // Skip non-files if ($file['.tag'] !== 'file') { continue; } // Dropbox file last modified time $filetime = strtotime($file['client_modified']); // If time is come - delete file if ($filetime <= $expiryDate) { $filepath = $this->getFilePathWithDir($file['name']); $this->client->delete($filepath); $this->stdout('expired file was deleted from dropbox: ' . $filepath . PHP_EOL, Console::FG_YELLOW); } } } /** * Get Dropbox SDK Client * * @return Client */ public function getClient() { if ($this->_client instanceof Client) { return $this->_client; } /** @noinspection ProperNullCoalescingOperatorUsageInspection As client contructor argument */ $access = $this->dropboxAccessToken ?? [$this->dropboxAppKey, $this->dropboxAppSecret]; return $this->_client = new Client( $access, // 'accessToken' or ['appKey', 'appSecret'] $this->guzzleClient, $this->maxChunkSize, $this->maxUploadChunkRetries ); } /** * Set Dropbox SDK Client * * @param Client $client */ public function setClient(Client $client) { $this->_client = $client; } /** * Get Backup component * * @return \demi\backup\Component * @throws \yii\base\InvalidConfigException */ public function getComponent() { /** @noinspection PhpIncompatibleReturnTypeInspection Yii always return correct class or trows Exception */ return Yii::$app->get($this->backupComponent); } /** * Return full path to file * * @param string $filename * * @return string */ protected function getFilePathWithDir($filename) { return rtrim($this->dropboxUploadPath, '/\\') . '/' . $filename; } }
gpl-3.0
maxammann/SimpleClans2
SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/converter/ConvertedClanPlayer.java
1173
/* * This file is part of SimpleClans2 (2012). * * SimpleClans2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SimpleClans2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SimpleClans2. If not, see <http://www.gnu.org/licenses/>. * * Last modified: 06.11.12 19:19 */ package com.p000ison.dev.simpleclans2.converter; /** * Represents a ConvertedClan */ public class ConvertedClanPlayer { private long id; private String name; public ConvertedClanPlayer(long id, String name) { this.id = id; this.name = name; } public long getId() { return id; } public String getName() { return name; } }
gpl-3.0
CryptoExperts/wb_contest_submission_server
services/web-dev/static/js/flot.js
2249
$(function() { var programs = getProgramsToPlot(); function dataGrowth(start, end, factor) { var minutes = Math.floor((end-start)/60); return [...Array(minutes+1).keys()].map(i => [start*1000 + i*60000, factor*Math.pow(i/1440,2)]); } function dataDecrease(start, peak, end, factor) { var minutes_before_peak = Math.floor((peak-start)/60); var minutes_after_peak = Math.floor((end-peak)/60); var minutes_decrease = Math.min(minutes_before_peak, minutes_after_peak); return [...Array(minutes_decrease+1).keys()].map(i => [peak*1000 + i*60000, factor*Math.pow((minutes_before_peak-i)/1440,2)]); } function getData() { var now = Math.floor(Date.now() / 1000); var deadline = Math.floor(new Date('2021-09-11T00:00:00Z').getTime() / 1000); now = Math.min(now, deadline); var strawberries = []; programs.forEach(function(p) { var strawberry_curve; if (p.ts_break > 0) { strawberry_curve1 = dataGrowth(p.ts_publish, p.ts_break, p.performance); strawberry_curve2 = dataDecrease(p.ts_publish, p.ts_break, now, p.performance); strawberry_curve = strawberry_curve1.concat(strawberry_curve2); } else { strawberry_curve = dataGrowth(p.ts_publish, now, p.performance); } strawberries.push({ color: p.color, label: "&nbsp;" + p.name + " (" + p.id + ")&nbsp;&nbsp;", data: strawberry_curve }); }); return [strawberries]; } // Set up the control widget var updateInterval = 600000; // 10 min var data = getData(); var plotStrawberry = $.plot("#strawberryholder", data[0] , { series: {shadowSize: 0}, yaxis: {min: 0, position: "right"}, xaxis: { show: true, mode: "time", timeformat: "%m/%d" }, legend: { position: "nw", noColumns: 2, margin: 10} }); function update() { console.log("update chart at: ", Date()); var data = getData() plotStrawberry.setData(data[0]); plotStrawberry.draw(); setTimeout(update, updateInterval); } update(); });
gpl-3.0
rafa1231518/CommunityBot
lib/xml2js-req/xmlbuilder/lodash/_baseLt.js
379
'use strict'; /** * The base implementation of `_.lt` which doesn't coerce arguments to numbers. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } module.exports = baseLt;
gpl-3.0
NablaWebkom/django-wiki
wiki/plugins/links/mdx/djangowikilinks.py
4454
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Wikipath Extension for Python-Markdown ====================================== Converts [Link Name](wiki:ArticleName) to relative links pointing to article. Requires Python-Markdown 2.0+ Basic usage: >>> import markdown >>> text = "Some text with a [Link Name](wiki:ArticleName)." >>> html = markdown.markdown(text, ['wikipath(base_url="/wiki/view/")']) >>> html '<p>Some text with a <a class="wikipath" href="/wiki/view/ArticleName/">Link Name</a>.</p>' Dependencies: * [Python 2.3+](http://python.org) * [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/) ''' from __future__ import absolute_import, unicode_literals from os import path as os_path import markdown from wiki import models try: # Markdown 2.1.0 changed from 2.0.3. We try importing the new version first, # but import the 2.0.3 version if it fails from markdown.util import etree # @UnusedImport except ImportError: from markdown import etree # @UnresolvedImport @Reimport @UnusedImport class WikiPathExtension(markdown.Extension): def __init__(self, configs): # set extension defaults self.config = { 'base_url': [ '/', 'String to append to beginning of URL.'], 'html_class': [ 'wikipath', 'CSS hook. Leave blank for none.'], 'default_level': [ 2, 'The level that most articles are created at. Relative links will tend to start at that level.']} # Override defaults with user settings for key, value in configs: # self.config[key][0] = value self.setConfig(key, value) def extendMarkdown(self, md, md_globals): self.md = md # append to end of inline patterns WIKI_RE_1 = r'\[(?P<linkTitle>[^\]]*?)\]\(wiki:(?P<wikiTitle>[^\)]*?)\)' wikiPathPattern1 = WikiPath(WIKI_RE_1, self.config, False, markdown_instance=md) wikiPathPattern1.md = md md.inlinePatterns.add('djangowikipath', wikiPathPattern1, "<reference") WIKI_RE_2 = r'\[\[(?P<wikiTitle>[^\]]*?)\]\]' wikiPathPattern2 = WikiPath(WIKI_RE_2, self.config, True, markdown_instance=md) wikiPathPattern2.md = md md.inlinePatterns.add('djangowikipathshort', wikiPathPattern2, "<reference") class WikiPath(markdown.inlinepatterns.Pattern): def __init__(self, pattern, config, shorthand, **kwargs): markdown.inlinepatterns.Pattern.__init__(self, pattern, **kwargs) self.config = config self.shorthand = shorthand def handleMatch(self, m): article_title = m.group('wikiTitle') absolute = False if article_title.startswith("/"): absolute = True article_title = article_title.strip("/") revisions = models.ArticleRevision.objects.filter(title = article_title) if len(revisions) != 0: revision = revisions[0] slug = "" parents = models.URLPath.objects.filter(article_id = revision.article_id) while len(parents) != 0 and parents[0].slug != None: slug = parents[0].slug + "/" + slug parents = models.URLPath.objects.filter(id = parents[0].parent_id) path = self.config['base_url'][0] + slug else: path = "" a = etree.Element('a') label = "" if not self.shorthand: label = m.group('linkTitle') if label == "": label = article_title if path == "": a.set('class', self.config['html_class'][0] + " linknotfound") a.set('href', path) a.text = label else: a.set('href', path) a.set('class', self.config['html_class'][0]) a.text = label return a def _getMeta(self): """ Return meta data or config data. """ base_url = self.config['base_url'][0] html_class = self.config['html_class'][0] if hasattr(self.md, 'Meta'): if 'wiki_base_url' in self.md.Meta: base_url = self.md.Meta['wiki_base_url'][0] if 'wiki_html_class' in self.md.Meta: html_class = self.md.Meta['wiki_html_class'][0] return base_url, html_class def makeExtension(configs=None): return WikiPathExtension(configs=configs)
gpl-3.0
WEEE-Open/weeelab-telegram-bot
variables.py
2913
import os # system library needed to read the environment variables def __unpack_wol(wol): wol = wol.split('|') result = {} for machine in wol: machine = machine.split(':', 1) result[machine[0]] = machine[1] return result # get environment variables OC_URL = os.environ.get('OC_URL') # url of the OwnCloud server OC_USER = os.environ.get('OC_USER') # OwnCloud username OC_PWD = os.environ.get('OC_PWD') # OwnCloud password # path of the log file to read in OwnCloud (/folder/file.txt) LOG_PATH = os.environ.get('LOG_PATH') TOLAB_PATH = os.environ.get('TOLAB_PATH') QUOTES_PATH = os.environ.get('QUOTES_PATH') QUOTES_GAME_PATH = os.environ.get('QUOTES_GAME_PATH') DEMOTIVATIONAL_PATH = os.environ.get('DEMOTIVATIONAL_PATH') # base path LOG_BASE = os.environ.get('LOG_BASE') # path of the file to store bot users in OwnCloud (/folder/file.txt) USER_BOT_PATH = os.environ.get('USER_BOT_PATH') TOKEN_BOT = os.environ.get('TOKEN_BOT') # Telegram token for the bot API TARALLO = os.environ.get('TARALLO') # tarallo URL TARALLO_TOKEN = os.environ.get('TARALLO_TOKEN') # tarallo token LDAP_SERVER = os.environ.get('LDAP_SERVER') # ldap.example.com LDAP_USER = os.environ.get('LDAP_USER') # cn=whatever,ou=whatever LDAP_PASS = os.environ.get('LDAP_PASS') # foo LDAP_SUFFIX = os.environ.get('LDAP_SUFFIX') # dc=weeeopen,dc=it LDAP_TREE_GROUPS = os.environ.get('LDAP_TREE_GROUPS') # ou=Groups,dc=weeeopen,dc=it LDAP_TREE_PEOPLE = os.environ.get('LDAP_TREE_PEOPLE') # ou=People,dc=weeeopen,dc=it LDAP_TREE_INVITES = os.environ.get('LDAP_TREE_INVITES') # ou=Invites,dc=weeeopen,dc=it LDAP_ADMIN_GROUPS = os.environ.get('LDAP_ADMIN_GROUPS') # ou=Group,dc=weeeopen,dc=it|ou=OtherGroup,dc=weeeopen,dc=it if LDAP_ADMIN_GROUPS is not None: LDAP_ADMIN_GROUPS = LDAP_ADMIN_GROUPS.split('|') INVITE_LINK = os.environ.get('INVITE_LINK') # https://example.com/register.php?invite= (invite code will be appended, no spaces in invite code) SSH_SCMA_USER = os.environ.get('SSH_SCMA_USER') # foo SSH_SCMA_HOST_IP = os.environ.get('SSH_SCMA_HOST_IP') # 10.20.30.40 SSH_SCMA_KEY_PATH = os.environ.get('SSH_SCMA_KEY_PATH') # /home/whatever/ssh_key SSH_PIALL_USER = os.environ.get('SSH_PIALL_USER') SSH_PIALL_HOST_IP = os.environ.get('SSH_PIALL_HOST_IP') SSH_PIALL_KEY_PATH = os.environ.get('SSH_PIALL_KEY_PATH') WOL_MACHINES = os.environ.get('WOL_MACHINES') # machine:00:0a:0b:0c:0d:0e|other:10:2a:3b:4c:5d:6e if WOL_MACHINES is not None: WOL_MACHINES = __unpack_wol(WOL_MACHINES) WOL_WEEELAB = os.environ.get('WOL_WEEELAB') # 00:0a:0b:0c:0d:0e WOL_I_AM_DOOR = os.environ.get('WOL_I_AM_DOOR') MAX_WORK_DONE = int(os.environ.get('MAX_WORK_DONE')) # 2000 WEEE_CHAT_ID = int(os.environ.get('WEEE_CHAT_ID')) WEEE_FOLD_ID = int(os.environ.get('WEEE_FOLD_ID')) WEEE_CHAT2_ID = int(os.environ.get('WEEE_CHAT2_ID'))
gpl-3.0
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Xml/MS/Internal/Xml/XPath/NumberFunctions.cs
4136
// Decompiled with JetBrains decompiler // Type: MS.Internal.Xml.XPath.NumberFunctions // Assembly: System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 50ABAB51-7DC3-4F0A-A797-0D0C2D124D60 // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Xml.dll using System; using System.Runtime; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class NumberFunctions : ValueQuery { private Query arg; private Function.FunctionType ftype; public override XPathResultType StaticType { get { return XPathResultType.Number; } } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public NumberFunctions(Function.FunctionType ftype, Query arg) { this.arg = arg; this.ftype = ftype; } private NumberFunctions(NumberFunctions other) : base((ValueQuery) other) { this.arg = Query.Clone(other.arg); this.ftype = other.ftype; } public override void SetXsltContext(XsltContext context) { if (this.arg == null) return; this.arg.SetXsltContext(context); } internal static double Number(bool arg) { return !arg ? 0.0 : 1.0; } internal static double Number(string arg) { return XmlConvert.ToXPathDouble((object) arg); } public override object Evaluate(XPathNodeIterator nodeIterator) { switch (this.ftype) { case Function.FunctionType.FuncNumber: return (object) this.Number(nodeIterator); case Function.FunctionType.FuncSum: return (object) this.Sum(nodeIterator); case Function.FunctionType.FuncFloor: return (object) this.Floor(nodeIterator); case Function.FunctionType.FuncCeiling: return (object) this.Ceiling(nodeIterator); case Function.FunctionType.FuncRound: return (object) this.Round(nodeIterator); default: return (object) null; } } public override XPathNodeIterator Clone() { return (XPathNodeIterator) new NumberFunctions(this); } public override void PrintQuery(XmlWriter w) { w.WriteStartElement(this.GetType().Name); w.WriteAttributeString("name", this.ftype.ToString()); if (this.arg != null) this.arg.PrintQuery(w); w.WriteEndElement(); } private double Number(XPathNodeIterator nodeIterator) { if (this.arg == null) return XmlConvert.ToXPathDouble((object) nodeIterator.Current.Value); object obj = this.arg.Evaluate(nodeIterator); switch (this.GetXPathType(obj)) { case XPathResultType.Number: return (double) obj; case XPathResultType.String: return NumberFunctions.Number((string) obj); case XPathResultType.Boolean: return NumberFunctions.Number((bool) obj); case XPathResultType.NodeSet: XPathNavigator xpathNavigator = this.arg.Advance(); if (xpathNavigator != null) return NumberFunctions.Number(xpathNavigator.Value); break; case (XPathResultType) 4: return NumberFunctions.Number(((XPathItem) obj).Value); } return double.NaN; } private double Sum(XPathNodeIterator nodeIterator) { double num = 0.0; this.arg.Evaluate(nodeIterator); XPathNavigator xpathNavigator; while ((xpathNavigator = this.arg.Advance()) != null) num += NumberFunctions.Number(xpathNavigator.Value); return num; } private double Floor(XPathNodeIterator nodeIterator) { return Math.Floor((double) this.arg.Evaluate(nodeIterator)); } private double Ceiling(XPathNodeIterator nodeIterator) { return Math.Ceiling((double) this.arg.Evaluate(nodeIterator)); } private double Round(XPathNodeIterator nodeIterator) { return XmlConvert.XPathRound(XmlConvert.ToXPathDouble(this.arg.Evaluate(nodeIterator))); } } }
gpl-3.0
zhonghuasheng/JAVA
basic/src/main/java/com/zhonghuasheng/basic/java/thread/thread/DaemonThreadExample.java
1208
package com.zhonghuasheng.basic.java.thread.thread; public class DaemonThreadExample { public static void main(String[] args) { System.out.println("main thread begin"); Thread thread1 = new Thread(new Runnable() { @Override public void run() { // 这是一个死循环,测试的是当用户线程结束后,守护线程也会被JVM回收掉 while(true) { System.out.println(Thread.currentThread().getName()); } } }, "Deamon Thread"); thread1.setDaemon(true); Thread thread2 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 200; i++) { System.out.println(Thread.currentThread().getName() + i); } } }, "User Thread"); // 添加钩子线程来查看JVM的退出 Runtime.getRuntime().addShutdownHook(new Thread(()-> { System.out.println("JVM existed"); })); thread1.start(); thread2.start(); System.out.println("main thread end"); } }
gpl-3.0
letsgoING/ArduBlock
Source/ardublock-master/ardublock-master/java/com/ardublock/translator/block/letsgoING/AndroidRemoteBlock1.java
1269
package com.ardublock.translator.block.letsgoING; import com.ardublock.translator.Translator; import com.ardublock.translator.block.TranslatorBlock; import com.ardublock.translator.block.exception.SocketNullException; import com.ardublock.translator.block.exception.SubroutineNotDeclaredException; public class AndroidRemoteBlock1 extends TranslatorBlock { public AndroidRemoteBlock1(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) { super(blockId, translator, codePrefix, codeSuffix, label); } private final static String serialEventFunction = " Ardudroid Remote;\n void serialEvent(){\n while(Serial.available()) \n { \n Remote.readBluetooth(); \n } \n Remote.getData();\n }\n"; public String toCode() throws SocketNullException, SubroutineNotDeclaredException { // Header hinzufügen translator.addHeaderFile("letsgoING_Ardudroid.h"); // Deklarationen hinzufügen translator.addDefinitionCommand(serialEventFunction); // setup hinzufügen // translator.addSetupCommand("Remote.BTbee_begin(9600);"); translator.addSetupCommand("Remote.BTserial_begin();"); // loop hinzufügen String ret = ""; return codePrefix + ret + codeSuffix; } }
gpl-3.0
IotaMyriad/SmartMirror
Widgets/InstalledWidgets/ExampleWidget2/ExampleExpandedWidget2.py
552
# -*- coding: utf-8 -*- from PyQt5.QtWidgets import * from Widgets.ExpandedWidget import ExpandedWidget class ExampleExpandedWidget2(ExpandedWidget): def __init__(self): super(ExampleExpandedWidget2, self).__init__() self.initUI() def initUI(self): self.layout = QVBoxLayout() self.widget = QWidget() self.widget.setStyleSheet("background-color:red;}") self.layout.addWidget(self.widget) self.setLayout(self.layout) @staticmethod def name(): return "ExampleWidget2"
gpl-3.0
miro-e25/Bandika
bandika/web/static-content/ckeditor/plugins/widget/lang/en.js
258
/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("widget","en",{move:"Click and drag to move",label:"%1 widget"});
gpl-3.0
manojdjoshi/dnSpy
dnSpy/dnSpy/Output/ThemeFontSettingsDefinitions.cs
1131
/* Copyright (C) 2014-2019 [email protected] This file is part of dnSpy dnSpy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. dnSpy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using dnSpy.Contracts.Settings.AppearanceCategory; using dnSpy.Contracts.Settings.Fonts; namespace dnSpy.Output { static class ThemeFontSettingsDefinitions { #pragma warning disable CS0169 [ExportThemeFontSettingsDefinition(AppearanceCategoryConstants.OutputWindow, FontType.TextEditor)] static readonly ThemeFontSettingsDefinition outputWindowThemeFontSettingsDefinition; #pragma warning restore CS0169 } }
gpl-3.0
rgugliel/CoxIter
docs/search/all_15.js
368
var searchData= [ ['weightsdotted_426',['weightsDotted',['../class_cox_iter.html#a5b524ed0a5abfadc4fa2a7ddf061ce85',1,'CoxIter']]], ['writegraph_427',['writeGraph',['../class_cox_iter.html#a46a591ed26ccbdd6480093fe69262b94',1,'CoxIter']]], ['writegraphtodraw_428',['writeGraphToDraw',['../class_cox_iter.html#a5d9fe1bfd7ca5c52530cac3d06ef3a64',1,'CoxIter']]] ];
gpl-3.0
MitosEHR/MitosEHR-Official
app/view/fees/PaymentEntryWindow.js
5578
//****************************************************************************** // new.ejs.php // New Patient Entry Form // v0.0.1 // // Author: Ernest Rodriguez // Modified: GI Technologies, 2011 // // MitosEHR (Electronic Health Records) 2011 //****************************************************************************** Ext.define('App.view.patientfile.PaymentEntryWindow', { extend:'Ext.window.Window', title:'Add New Payment', closeAction:'hide', modal:true, initComponent:function () { var me = this; me.items = [ { xtype:'form', defaults:{ margin:5 }, border:false, height:163, width:747, items:[ { xtype:'fieldcontainer', layout:'hbox', items:[ { fieldLabel:'Paying Entity', xtype:'mitos.payingentitycombo', name:'paying_entity', action: 'new_payment', labelWidth:98, width:220 }, { xtype:'patienlivetsearch', fieldLabel:'From', hideLabel:false, name:'payer_id', action: 'new_payment', anchor:null, labelWidth:42, width:300, margin:'0 0 0 25' }, { xtype:'textfield', fieldLabel:'No', action: 'new_payment', name:'check_number', labelWidth:47, width:167, margin:'0 0 0 25' } ] }, { xtype:'fieldcontainer', layout:'hbox', items:[ { fieldLabel:'Payment Method', xtype:'mitos.paymentmethodcombo', action: 'new_payment', labelWidth:98, name:'payment_method', width:220 }, { xtype:'mitos.billingfacilitiescombo', fieldLabel:'Pay To', action: 'new_payment', labelWidth:42, name:'pay_to', width:300, margin:'0 0 0 25' }, { xtype:'mitos.currency', fieldLabel:'Amount', action: 'new_payment', name:'amount', labelWidth:47, width:167, margin:'0 0 0 25', enableKeyEvents:true } ] }, { fieldLabel:'Post To Date', xtype:'datefield', name:'post_to_date', action:'new_payment', format:'Y-m-d', labelWidth:98, width:220 }, { fieldLabel:'Note', xtype : 'textareafield', grow : true, action: 'new_payment', name:'note', labelWidth:98, anchor:'100%' } ] } ]; me.buttons = [ { text:'Save', scope:me, handler: me.onSave }, '-', { text:'Reset', scope:me, handler:me.resetNewPayment } ]; me.callParent(arguments); }, onSave: function() { var me = this, panel, form, values; panel = me.down('form'); form = panel.getForm(); values = form.getFieldValues(); values.date_created = Ext.Date.format(new Date(), 'Y-m-d H:i:s'); if(form.isValid()) { Fees.addPayment(values, function(provider, response){ if(response.result.success){ form.reset(); me.hide(); }else{ app.msg('Oops!','Payment entry error') } }); } }, resetNewPayment:function () { var fields = this.query('[action="new_payment"]'); Ext.each(fields, function(field){ field.reset(); }); } }); //end Checkout class
gpl-3.0
bhermansyah/DRR-datacenter
scripts/misc-boedy1996/test_chart.py
3094
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE","geonode.settings") from netCDF4 import Dataset, num2date import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.ticker as ticker def get_month_name(monthNo): if monthNo==1: return 'January' elif monthNo==2: return 'February' elif monthNo==3: return 'March' elif monthNo==4: return 'April' elif monthNo==5: return 'May' elif monthNo==6: return 'June' elif monthNo==7: return 'July' elif monthNo==8: return 'August' elif monthNo==9: return 'September' elif monthNo==10: return 'October' elif monthNo==11: return 'November' elif monthNo==12: return 'December' filename = "/Users/budi/Desktop/from_ecmwf/glofas_arealist_for_IMMAP_in_Afghanistan_2017041900.nc" nc = Dataset(filename, 'r', Format='NETCDF4') # get coordinates variables lats = nc.variables['lat'][:] lons = nc.variables['lon'][:] times= nc.variables['time'][:] lat_idx = np.where(lats==43.85)[0] lon_idx = np.where(lons==77.95)[0] coord_idx = list(set(lat_idx) & set(lon_idx))[0] d = np.array(nc.variables['dis']) rl2= nc.variables['rl2'][:] rl5= nc.variables['rl5'][:] rl20= nc.variables['rl20'][:] units = nc.variables['time'].units dates = num2date (times[:], units=units, calendar='365_day') date_arr = [] median = [] mean75 = [] mean25 = [] rl2_arr = [] rl5_arr = [] rl20_arr = [] maximum = [] date_number = [] month_name = [] for i in dates: date_number.append(i.day) month_name.append(i.month) for i in range(len(date_number)): date_arr.append(i) # get median line median.append(np.mean(list(d[i,:,coord_idx]))) maximum.append(np.max(list(d[i,:,coord_idx]))) mean75.append(np.percentile(list(d[i,:,coord_idx]),75)) mean25.append(np.percentile(list(d[i,:,coord_idx]),25)) rl2_arr.append(rl2[coord_idx]) rl5_arr.append(rl5[coord_idx]) rl20_arr.append(rl20[coord_idx]) plt.fill_between(date_arr, rl2_arr, rl5_arr, color='#fff68f', alpha=1, label="2 years return period") plt.fill_between(date_arr, rl5_arr, rl20_arr, color='#ffaeb9', alpha=1, label="5 years return period") plt.fill_between(date_arr, rl20_arr, np.max(maximum)+100, color='#ffbbff', alpha=1, label="20 years return period") plt.plot(date_arr, median, c='black', alpha=1, linestyle='solid', label="EPS mean") plt.plot(date_arr, mean75, color='black', alpha=1, linestyle='dashed', label="25% - 75%") plt.plot(date_arr, mean25, color='black', alpha=1, linestyle='dashed') for i in range(51): plt.fill_between(date_arr, median, list(d[:,i,coord_idx]), color='#178bff', alpha=0.05) plt.margins(x=0,y=0,tight=True) plt.xticks(date_arr, date_number, rotation=45) plt.ylabel('discharge (m$^3$/s)') if max(month_name)==min(month_name): plt.xlabel('Period of '+get_month_name(max(month_name))) else: plt.xlabel('Period of '+get_month_name(min(month_name))+' - '+get_month_name(max(month_name))) plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.2) plt.grid(True, 'major', 'x', ls='--', lw=.5, c='k', alpha=.2) leg = plt.legend(prop={'size':6}) leg.get_frame().set_alpha(0) plt.show()
gpl-3.0
Toukibi/ToSAddon
BetterPickQueue/src/betterpickqueue.lua
63402
local addonName = "BetterPickQueue"; local verText = "1.18"; local autherName = "TOUKIBI"; local addonNameLower = string.lower(addonName); local SlashCommandList = {"/pickq", "/pickqueue"} -- {"/コマンド1", "/コマンド2", .......}; local CommandParamList = { reset = {jp = "計測リセット", en = "Reset Session."}, resetpos = {jp = "位置をリセット", en = "Reset Position."}, resetsetting = {jp = "設定リセット", en = "Reset the all settings."}, update = {jp = "表示を更新", en = "Update display."} }; local SettingFileName = "setting.json" _G['ADDONS'] = _G['ADDONS'] or {}; _G['ADDONS'][autherName] = _G['ADDONS'][autherName] or {}; _G['ADDONS'][autherName][addonName] = _G['ADDONS'][autherName][addonName] or {}; local Me = _G['ADDONS'][autherName][addonName]; pickq = Me; local DebugMode = false; -- テキストリソース local ResText = { jp = { Menu = { Title = "{#006666}=== BetterPickQueueの設定 ==={/}" , SecondaryInfo = "{nl}{s4} {/}{nl}{s12}{b}{#66AA99}Shift+右クリックで{#AAAA66}{ol}第2設定画面{/}{/}を表示{/}{/}{/}" , SecondaryTitle = "{nl}{#66AA99}第2設定画面{/}" , ResetSession = "{#FFFF88}計測をリセット{/}" , UpdateNow = "表示を更新" , DisplayItems = "表示項目" , SortedBy = "並び順" , AllwaysDisplay = "常に表示するもの" , AutoReset = "オートリセット" , BackGround = "背景の濃さ" , LockPosition = "位置を固定する" , ResetPosition = "位置をリセット" , useSimpleMenu = "かんたん表示切り替え" , HideOriginalQueue = "標準機能のアイテム獲得の{nl}{img channel_mark_empty 24 24} 表示を消す" , ExpandTo_Vertical = "表示が伸びる方向(垂直方向)" , ExpandTo_Up = "上へ" , ExpandTo_Down = "下へ" , ExpandTo_Horizonal = "表示が伸びる方向(水平方向)" , ExpandTo_Left = "左へ" , ExpandTo_Right = "右へ" , Close = "{#666666}閉じる{/}" }, Display = { CurrentCount = "所持数" , GuessCount = "1時間あたりの取得量" , SimpleLog = "簡易ログ" , Silver = "シルバー" , MercenaryBadge = "傭兵団コイン" , WeeklyMercenaryBadgeCount = "傭兵団コイン週間獲得量" , WeightData = "所持重量" , OldItem = "拾って時間の経った物" , ElapsedTime = "経過時間" }, Order = { byName = "名前順" , byCount = "取得数順" , byGetTime = "拾った順" }, AutoReset = { byMap = "マップ移動時" , byChannel = "チャンネル変更時" }, SimpleMenuSelect = { Title = "表示モード選択" , Normal = "標準モード" , Counter = "カウンターモード" , Detail = "獲得履歴モード" }, BackGround = { Deep = "濃い" , Thin = "薄い" , None = "なし" }, Log = { ResetSession = "計測をリセットしました。" }, Other = { Multiple = "×" , Percent = "%" , WeeklyMercenaryBadgeCount = "傭兵団コイン週間獲得量{nl} " , WeightTitle = "所持重量:" , LogSpacer = " " , TotalTitle = "{s4} {/}/{s4} {/}" , GuessFormat = "約{#FFFF33}%s{/}個/h" , GuessFormatLong = "{#FFFF33}%s{/}ほどで入手" , ElapsedTimeFormat = "{#FFFF33}%s{/}経過" , Day = "日" , Hour = "時間" , Minutes = "分" , Second = "秒" , Ago = "前" }, System = { ErrorToUseDefaults = "設定の読み込みでエラーが発生したのでデフォルトの設定を使用します。" , CompleteLoadDefault = "デフォルトの設定の読み込みが完了しました。" , CompleteLoadSettings = "設定の読み込みが完了しました" , ExecuteCommands = "コマンド '{#333366}%s{/}' が呼び出されました" , ResetSettings = "設定をリセットしました。" , InvalidCommand = "無効なコマンドが呼び出されました" , AnnounceCommandList = "コマンド一覧を見るには[ %s ? ]を用いてください" } }, en = { Menu = { Title = "{#006666}=== BetterPickQueue setting ==={/}" , SecondaryInfo = "{nl}{s4} {/}{nl}{s12}{b}{#66AA99}Shift + Right-Click to display{nl}the {#AAAA66}{ol}2nd setting menu{/}{/}{/}{/}{/}" , SecondaryTitle = "{nl}{#66AA99}Secondary Setting menu{/}" , ResetSession = "{#FFFF88}Reset Session{/}" , UpdateNow = "Update now!" , DisplayItems = "Display Items" , SortedBy = "Sorted by" , AllwaysDisplay = "Always display" , AutoReset = "Auto reset function" , BackGround = "Background" , LockPosition = "Lock position" , ResetPosition = "Reset position" , useSimpleMenu = "Use Simple menu" , HideOriginalQueue = "Hide default{nl}{img channel_mark_empty 24 24} item-obtention display" , ExpandTo_Vertical = "Vertical display extension" , ExpandTo_Up = "Upward" , ExpandTo_Down = "Downward" , ExpandTo_Horizonal = "Horizonal display extension" , ExpandTo_Left = "To the Left" , ExpandTo_Right = "To the Right" , Close = "{#666666}Close{/}" }, Display = { CurrentCount = "Total Obtained Count" , GuessCount = "pcs/Hr" , SimpleLog = "Simple log" , Silver = "Silver" , MercenaryBadge = "Mercenary Badge" , WeeklyMercenaryBadgeCount = "Weekly Mercenary Badge" , WeightData = "Weight Info." , OldItem = "Items picked up long ago" , ElapsedTime = "Elapsed time" }, Order = { byName = "by Name" , byCount = "by Count" , byGetTime = "In order of acquisition" }, AutoReset = { byMap = "When changing the map" , byChannel = "When changing channel" }, SimpleMenuSelect = { Title = "Select mode" , Normal = "Normal mode" , Counter = "Obtained counter mode" , Detail = "Obtained history mode" }, BackGround = { Deep = "Deep" , Thin = "Thin" , None = "None" }, Log = { ResetSession = "Session resetted." }, Other = { Multiple = " x " , Percent = "%" , WeeklyMercenaryBadgeCount = "Weekly Mercenary Badge{nl} " , WeightTitle = "Weight : " , LogSpacer = " " , TotalTitle = " /" , GuessFormat = "{#FFFF33}%s{/}/Hr" , GuessFormatLong = "{#FFFF33}%s{/} to get." , ElapsedTimeFormat = "{#FFFF33}%s{/} elapsed." , Day = "day" , Hour = "hour" , Minutes = "min." , Second = "sec." , Ago = "ago" }, System = { ErrorToUseDefaults = "Using default settings because an error occurred while loading the settings." , CompleteLoadDefault = "Default settings loaded." , CompleteLoadSettings = "Settings loaded!" , ExecuteCommands = "Command '{#333366}%s{/}' was called." , ResetSettings = "Settings resetted." , InvalidCommand = "Invalid command called." , AnnounceCommandList = "Please use [ %s ? ] to see the command list." } } }; Me.ResText = ResText; -- コモンモジュール(の代わり) local Toukibi = { CommonResText = { jp = { System = { NoSaveFileName = "設定の保存ファイル名が指定されていません" , HasErrorOnSaveSettings = "設定の保存でエラーが発生しました" , CompleteSaveSettings = "設定の保存が完了しました" , ErrorToUseDefaults = "設定の読み込みでエラーが発生したのでデフォルトの設定を使用します。" , CompleteLoadDefault = "デフォルトの設定の読み込みが完了しました。" , CompleteLoadSettings = "設定の読み込みが完了しました" }, Command = { ExecuteCommands = "コマンド '{#333366}%s{/}' が呼び出されました" , ResetSettings = "設定をリセットしました。" , InvalidCommand = "無効なコマンドが呼び出されました" , AnnounceCommandList = "コマンド一覧を見るには[ %s ? ]を用いてください" }, Help = { Title = string.format("{#333333}%sのパラメータ説明{/}", addonName) , Description = string.format("{#92D2A0}%sは次のパラメータで設定を呼び出してください。{/}", addonName) , ParamDummy = "[パラメータ]" , OrText = "または" , EnableTitle = "使用可能なコマンド" } }, en = { System = { InitMsg = "[Add-ons]" .. addonName .. verText .. " loaded!" , NoSaveFileName = "Save settings filename is not specified." , HasErrorOnSaveSettings = "An error occurred while saving the settings." , CompleteSaveSettings = "Settings saved." , ErrorToUseDefaults = "Using default settings because an error occurred while loading the settings." , CompleteLoadDefault = "Default settings loaded." , CompleteLoadSettings = "Settings loaded!" }, Command = { ExecuteCommands = "Command '{#333366}%s{/}' was called" , ResetSettings = "Settings have been reset." , InvalidCommand = "Invalid command called." , AnnounceCommandList = "Please use [ %s ? ] to see the command list." }, Help = { Title = string.format("{#333333}Help for %s commands.{/}", addonName) , Description = string.format("{#92D2A0}To change settings of '%s', please call the following command.{/}", addonName) , ParamDummy = "[paramaters]" , OrText = "or" , EnableTitle = "Commands available" } }, kr = { System = { NoSaveFileName = "설정의 저장파일명이 지정되지 않았습니다" , HasErrorOnSaveSettings = "설정 저장중 에러가 발생했습니다" , CompleteSaveSettings = "설정 저장이 완료되었습니다" , ErrorToUseDefaults = "설정 불러오기에 에러가 발생했으므로 기본 설정을 사용합니다" , CompleteLoadDefault = "기본 설정 불러오기가 완료되었습니다" , CompleteLoadSettings = "설정을 불러들였습니다" }, Command = { ExecuteCommands = "명령 '{#333366}%s{/}' 를 불러왔습니다" , ResetSettings = "설정을 초기화하였습니다" , InvalidCommand = "무효한 명령을 불러왔습니다" , AnnounceCommandList = "명령일람을 보려면[ %s ? ]를 사용해주세요" }, Help = { Title = string.format("{#333333}%s의 패러미터 설명{/}", addonName) , Description = string.format("{#92D2A0}%s는 다음 패러미터로 설정을 불러와주세요{/}", addonName) , ParamDummy = "[패러미터]" , OrText = "또는" , EnableTitle = "사용가능한 명령" } } }, Log = function(self, Caption) if Caption == nil then Caption = "Test Printing" end Caption = tostring(Caption) or "Test Printing"; CHAT_SYSTEM(tostring(Caption)); end, GetDefaultLangCode = function(self) if option.GetCurrentCountry() == "Japanese" then return "jp"; elseif option.GetCurrentCountry() == "Korean" then return "kr"; else return "en"; end end, GetTableLen = function(self, tbl) local n = 0; for _ in pairs(tbl) do n = n + 1; end return n; end, Split = function(self, str, delim) local ReturnValue = {}; for match in string.gmatch(str, "[^" .. delim .. "]+") do table.insert(ReturnValue, match); end return ReturnValue; end, GetValue = function(self, obj, Key) if obj == nil then return nil end if Key == nil or Key == "" then return obj end local KeyList = self:Split(Key, "."); for i = 1, #KeyList do local index = KeyList[i] obj = obj[index]; if obj == nil then return nil end end return obj; end, GetResData = function(self, TargetRes, Lang, Key) if TargetRes == nil then return nil end --CHAT_SYSTEM(string.format("TargetLang : %s", self:GetValue(TargetRes[Lang], Key))) --CHAT_SYSTEM(string.format("En : %s", self:GetValue(TargetRes["en"], Key))) --CHAT_SYSTEM(string.format("Jp : %s", self:GetValue(TargetRes["jp"], Key))) local CurrentRes = self:GetValue(TargetRes[Lang], Key) or self:GetValue(TargetRes["en"], Key) or self:GetValue(TargetRes["jp"], Key); return CurrentRes; end, GetResText = function(self, TargetRes, Lang, Key) local ReturnValue = self:GetResData(TargetRes, Lang, Key); if ReturnValue == nil then return "<No Data!!>" end if type(ReturnValue) == "string" then return ReturnValue end return tostring("tostring ==>" .. ReturnValue); end, -- ***** ログ表示関連 ***** GetStyledText = function(self, Value, Styles) -- ValueにStylesで与えたスタイルタグを付加した文字列を返します local ReturnValue; if Styles == nil or #Styles == 0 then -- スタイル指定なし ReturnValue = Value; else local TagHeader = "" for i, StyleTag in ipairs(Styles) do TagHeader = TagHeader .. string.format( "{%s}", StyleTag); end ReturnValue = string.format( "%s%s%s", TagHeader, Value, string.rep("{/}", #Styles)); end return ReturnValue; end, AddLog = function(self, Message, Mode, DisplayAddonName, OnlyDebugMode) if Message == nil then return end Mode = Mode or "Info"; if (not DebugMode) and Mode == "Info" then return end if (not DebugMode) and OnlyDebugMode then return end local HeaderText = ""; if DisplayAddonName then HeaderText = string.format("[%s]", addonName); end local MsgText = HeaderText .. Message; if Mode == "Info" then MsgText = self:GetStyledText(MsgText, {"#333333"}); elseif Mode == "Warning" then MsgText = self:GetStyledText(MsgText, {"#331111"}); elseif Mode == "Caution" then MsgText = self:GetStyledText(MsgText, {"#666622"}); elseif Mode == "Notice" then MsgText = self:GetStyledText(MsgText, {"#333366"}); else -- 何もしない end CHAT_SYSTEM(MsgText); end, -- 言語切替 ChangeLanguage = function(self, Lang) local msg; if self.CommonResText[Lang] == nil then msg = string.format("Sorry, '%s' does not implement '%s' mode.{nl}Language mode has not been changed from '%s'.", addonName, Lang, Me.Settings.Lang); self:AddLog(msg, "Warning", true, false) return; end Me.Settings.Lang = Lang; self:SaveTable(Me.SettingFilePathName, Me.Settings); if Me.Settings.Lang == "jp" then msg = "日本語モードに切り替わりました"; else msg = string.format("Language mode has been changed to '%s'.", Lang); end self:AddLog(msg, "Notice", true, false); end, -- ヘルプテキストを自動生成する ShowHelpText = function(self) local ParamDummyText = ""; if SlashCommandList ~= nil and SlashCommandList[1] ~= nil then ParamDummyText = ParamDummyText .. "{#333333}"; ParamDummyText = ParamDummyText .. string.format("'%s %s'", SlashCommandList[1], self:GetResText(self.CommonResText, Me.Settings.Lang, "Help.ParamDummy")); if SlashCommandList[2] ~= nil then ParamDummyText = ParamDummyText .. string.format(" %s '%s %s'", self:GetResText(self.CommonResText, Me.Settings.Lang, "Help.OrText"), SlashCommandList[2], self:GetResText(self.CommonResText, Me.Settings.Lang, "Help.ParamDummy")); end ParamDummyText = ParamDummyText .. "{/}{nl}"; end local CommandHelpText = ""; if CommandParamList ~= nil and self:GetTableLen(CommandParamList) > 0 then CommandHelpText = CommandHelpText .. string.format("{#333333}%s: ", self:GetResText(self.CommonResText, Me.Settings.Lang, "Help.EnableTitle")); for ParamName, DescriptionKey in pairs(CommandParamList) do local SpaceCount = 10 - string.len(ParamName); local SpaceText = "" if SpaceCount > 0 then SpaceText = string.rep(" ", SpaceCount) end CommandHelpText = CommandHelpText .. string.format("{nl}%s %s%s:%s", SlashCommandList[1], ParamName, SpaceText, self:GetResText(DescriptionKey, Me.Settings.Lang)); end CommandHelpText = CommandHelpText .. "{/}{nl} " end self:AddLog(string.format("%s{nl}%s{nl}%s%s" , self:GetResText(self.CommonResText, Me.Settings.Lang, "Help.Title") , self:GetResText(self.CommonResText, Me.Settings.Lang, "Help.Description") , ParamDummyText , CommandHelpText ) , "None", false, false); end, -- ***** 設定読み書き関連 ***** SaveTable = function(self, FilePathName, objTable) if FilePathName == nil then self:AddLog(self:GetResText(self.CommonResText, Me.Settings.Lang, "System.NoSaveFileName"), "Warning", true, false); end local objFile, objError = io.open(FilePathName, "w") if objError then self:AddLog(string.format("%s:{nl}%s" , self:GetResText(self.CommonResText, Me.Settings.Lang, "System.HasErrorOnSaveSettings") , tostring(objError)), "Warning", true, false); else local json = require('json'); objFile:write(json.encode(objTable)); objFile:close(); self:AddLog(self:GetResText(self.CommonResText, Me.Settings.Lang, "System.CompleteSaveSettings"), "Info", true, true); end end, LoadTable = function(self, FilePathName) local acutil = require("acutil"); local objReadValue, objError = acutil.loadJSON(FilePathName); return objReadValue, objError; end, -- 既存の値がない場合にデフォルト値をマージする GetValueOrDefault = function(self, Value, DefaultValue, Force) Force = Force or false; if Force or Value == nil then return DefaultValue; else return Value; end end, -- ***** コンテキストメニュー関連 ***** -- セパレータを挿入 MakeCMenuSeparator = function(self, parent, width, text, style, index) width = width or 300; text = text or ""; style = style or {"ol", "b", "s12", "#AAFFAA"}; index = index or 0; local strTemp = string.format("{img fullgray %s 1}", width); if text ~= "" then strTemp = strTemp .. "{s4} {/}{nl}" .. self:GetStyledText(text, style); elseif index > 0 then strTemp = strTemp .. string.format("{nl}{img fullblack %s 1}", index); end ui.AddContextMenuItem(parent, string.format(strTemp, width), "None"); end, -- 子を持つメニュー項目を作成 MakeCMenuParentItem = function(self, parent, text, child) ui.AddContextMenuItem(parent, text .. " {img white_right_arrow 8 16}", "", nil, 0, 1, child); end, -- コンテキストメニュー項目を作成 MakeCMenuItem = function(self, parent, text, eventscp, icon, checked) local CheckIcon = ""; local ImageIcon = ""; local eventscp = eventscp or "None"; if checked == nil then CheckIcon = ""; elseif checked == true then CheckIcon = "{img socket_slot_check 24 24} "; elseif checked == false then CheckIcon = "{img channel_mark_empty 24 24} "; end if icon == nil then ImageIcon = ""; else ImageIcon = string.format("{img %s 24 24} ", icon); end ui.AddContextMenuItem(parent, string.format("%s%s%s", CheckIcon, ImageIcon, text), eventscp); end, -- コンテキストメニュー項目を作成(中間にチェックがあるタイプ) MakeCMenuItemHasCheckInTheMiddle = function(self, parent, textBefore, textAfter, eventscp, icon, checked) textBefore = textBefore or ""; textAfter = textAfter or ""; local CheckIcon = ""; local ImageIcon = ""; local eventscp = eventscp or "None"; if checked == nil then CheckIcon = ""; elseif checked == true then CheckIcon = "{img socket_slot_check 24 24}"; elseif checked == false then CheckIcon = "{img channel_mark_empty 24 24}"; end if icon == nil then ImageIcon = ""; else ImageIcon = string.format("{img %s 24 24} ", icon); end ui.AddContextMenuItem(parent, string.format("%s%s%s%s", ImageIcon, textBefore, CheckIcon, textAfter), eventscp); end, -- イベントの飛び先を変更するためのプロシージャ SetHook = function(self, hookedFunctionStr, newFunction) if Me.HoockedOrigProc[hookedFunctionStr] == nil then Me.HoockedOrigProc[hookedFunctionStr] = _G[hookedFunctionStr]; _G[hookedFunctionStr] = newFunction; else _G[hookedFunctionStr] = newFunction; end end }; Me.ComLib = Toukibi; local function log(value) Toukibi:Log(value); end local function view(objValue) local frame = ui.GetFrame("developerconsole"); if frame == nil then return end --DEVELOPERCONSOLE_PRINT_TEXT("{#444444}type of {#005500}" .. objName .. "{/} is {#005500}" .. type(objValue) .. "{/}{/}", "white_16_ol"); DEVELOPERCONSOLE_PRINT_TEXT("{nl} "); DEVELOPERCONSOLE_PRINT_VALUE(frame, "", objValue, "", nil, true); end local function try(f, ...) local status, error = pcall(f, ...) if not status then return tostring(error); else return "OK"; end end local function FunctionExists(func) if func == nil then return false; else return true; end end local function ShowInitializeMessage() local CurrentLang = "en" if Me.Settings == nil then CurrentLang = Toukibi:GetDefaultLangCode() or CurrentLang; else CurrentLang = Me.Settings.Lang or CurrentLang; end CHAT_SYSTEM(string.format("{#333333}%s{/}", Toukibi:GetResText(Toukibi.CommonResText, CurrentLang, "System.InitMsg"))) -- CHAT_SYSTEM(string.format("{#333366}[%s]%s{/}", addonName, Toukibi:GetResText(ResText, CurrentLang, "Log.InitMsg"))) end ShowInitializeMessage() -- ***** 変数の宣言と設定 ***** Me.SettingFilePathName = string.format("../addons/%s/%s", addonNameLower, SettingFileName); Me.Loaded = false; Me.Data = Me.Data or {}; Me.Data.Pick = Me.Data.Pick or {}; Me.Data.StartTime = Me.Data.StartTime or nil Me.Data.BeforeMap = Me.Data.BeforeMap or nil; -- 設定書き込み local function SaveSetting() Toukibi:SaveTable(Me.SettingFilePathName, Me.Settings); end -- デフォルト設定(ForceがTrueでない場合は、既存の値はそのまま引き継ぐ) local function MargeDefaultSetting(Force, DoSave) DoSave = Toukibi:GetValueOrDefault(DoSave, true); Me.Settings = Me.Settings or {}; Me.Settings.DoNothing = Toukibi:GetValueOrDefault(Me.Settings.DoNothing , false, Force); Me.Settings.Lang = Toukibi:GetValueOrDefault(Me.Settings.Lang , Toukibi:GetDefaultLangCode(), Force); Me.Settings.Movable = Toukibi:GetValueOrDefault(Me.Settings.Movable , true, Force); Me.Settings.Visible = Toukibi:GetValueOrDefault(Me.Settings.Visible , true, Force); Me.Settings.PosX = Toukibi:GetValueOrDefault(Me.Settings.PosX , 0, Force); Me.Settings.PosY = Toukibi:GetValueOrDefault(Me.Settings.PosY , 250, Force); Me.Settings.MarginBottom = Toukibi:GetValueOrDefault(Me.Settings.MarginBottom , 90, Force); Me.Settings.MarginRight = Toukibi:GetValueOrDefault(Me.Settings.MarginRight , 20, Force); Me.Settings.useSimpleMenu = Toukibi:GetValueOrDefault(Me.Settings.useSimpleMenu , true, Force); Me.Settings.CurrentMode = Toukibi:GetValueOrDefault(Me.Settings.CurrentMode , "Normal", Force); -- Normal/Counter/Detail Me.Settings.ShowElapsedTime = Toukibi:GetValueOrDefault(Me.Settings.ShowElapsedTime , false, Force); Me.Settings.ShowCurrent = Toukibi:GetValueOrDefault(Me.Settings.ShowCurrent , true, Force); Me.Settings.ShowGuess = Toukibi:GetValueOrDefault(Me.Settings.ShowGuess , false, Force); Me.Settings.ShowLog = Toukibi:GetValueOrDefault(Me.Settings.ShowLog , true, Force); Me.Settings.OrderBy = Toukibi:GetValueOrDefault(Me.Settings.OrderBy , "byGetTime", Force); -- byName/byCount/byGetTime Me.Settings.AutoResetByMap = Toukibi:GetValueOrDefault(Me.Settings.AutoResetByMap , true, Force); Me.Settings.AutoResetByCh = Toukibi:GetValueOrDefault(Me.Settings.AutoResetByCh , false, Force); Me.Settings.ShowVis = Toukibi:GetValueOrDefault(Me.Settings.ShowVis , true, Force); Me.Settings.ShowMercenaryBadge = Toukibi:GetValueOrDefault(Me.Settings.ShowMercenaryBadge , true, Force); Me.Settings.ShowMBadgeGauge = Toukibi:GetValueOrDefault(Me.Settings.ShowMBadgeGauge , false, Force); Me.Settings.ShowWeight = Toukibi:GetValueOrDefault(Me.Settings.ShowWeight , true, Force); Me.Settings.ShowOldItem = Toukibi:GetValueOrDefault(Me.Settings.ShowOldItem , false, Force); Me.Settings.DueDateDisplay = Toukibi:GetValueOrDefault(Me.Settings.DueDateDisplay , 10, Force); Me.Settings.SkinName = Toukibi:GetValueOrDefault(Me.Settings.SkinName , "None", Force); --None/chat_window/systemmenu_vertical Me.Settings.HideOriginalQueue = Toukibi:GetValueOrDefault(Me.Settings.HideOriginalQueue , false, Force); Me.Settings.ExpandTo_Up = Toukibi:GetValueOrDefault(Me.Settings.ExpandTo_Up , true, Force); Me.Settings.ExpandTo_Left = Toukibi:GetValueOrDefault(Me.Settings.ExpandTo_Left , true, Force); if Force then Toukibi:AddLog(Toukibi:GetResText(ResText, Me.Settings.Lang, "System.CompleteLoadDefault"), "Info", true, false); end if DoSave then SaveSetting() end end -- 設定読み込み local function LoadSetting() local objReadValue, objError = Toukibi:LoadTable(Me.SettingFilePathName); if objError then local CurrentLang = "en" if Me.Settings == nil then CurrentLang = Toukibi:GetDefaultLangCode() or CurrentLang; else CurrentLang = Me.Settings.Lang or CurrentLang; end Toukibi:AddLog(string.format("%s{nl}{#331111}%s{/}", Toukibi:GetResText(ResText, CurrentLang, "System.ErrorToUseDefaults"), tostring(objError)), "Caution", true, false); MargeDefaultSetting(true, false); else Me.Settings = objReadValue; MargeDefaultSetting(false, false); end Toukibi:AddLog(Toukibi:GetResText(ResText, Me.Settings.Lang, "System.CompleteLoadSettings"), "Info", true, false); end -- ===== アドオンの内容ここから ===== local function GetCommaedTextEx(value, MaxTextLen, AfterTheDecimalPointLen, usePlusMark, AddSpaceAfterSign) local lMaxTextLen = MaxTextLen or 0; local lAfterTheDecimalPointLen = AfterTheDecimalPointLen or 0; local lusePlusMark = usePlusMark or false; local lAddSpaceAfterSign = AddSpaceAfterSign or lusePlusMark; if lAfterTheDecimalPointLen < 0 then lAfterTheDecimalPointLen = 0 end local IsNegative = (value < 0); local SourceValue = math.floor(math.abs(value) * math.pow(10, lAfterTheDecimalPointLen) + 0.5); local IntegerPartValue = math.floor(SourceValue * math.pow(10, -1 *lAfterTheDecimalPointLen)); local DecimalPartValue = SourceValue - IntegerPartValue * math.pow(10, lAfterTheDecimalPointLen); local IntegerPartText = GetCommaedText(IntegerPartValue); local DecimalPartText = tostring(DecimalPartValue); -- 記号をつける local SignMark = ""; if IsNegative then -- 負の数の場合は頭にマイナスをつける SignMark = "-"; else -- 正の数の場合はusePlusMarkがTrueの場合のみ付加する if lusePlusMark then if Me.Settings.Lang == "jp" and IntegerPartValue == 0 and DecimalPartValue == 0 then -- 日本語の場合はゼロぴったり時に±を実装 SignMark = "±"; else SignMark = "+"; end end end if lAddSpaceAfterSign and string.len(SignMark) > 0 then SignMark = SignMark .. "{s4} {/}"; end -- 整数部を成形 local RoughFinish = SignMark .. IntegerPartText; -- 小数部を成形 if DecimalPartValue > 0 or lAfterTheDecimalPointLen > 0 then RoughFinish = RoughFinish .. string.format(string.format(".%%0%dd", lAfterTheDecimalPointLen), DecimalPartValue); end -- 長さに合わせて整形する -- すでに文字長オーバーの場合はそのまま返す if string.len(RoughFinish) >= lMaxTextLen then return RoughFinish end -- 挿入する空白を作成する local PaddingText = string.rep(" ", lMaxTextLen - string.len(RoughFinish)); return PaddingText .. RoughFinish; end local function GetItemGrade(itemObj) local grade = itemObj.ItemGrade; if (itemObj.ItemType == "Recipe") then local recipeGrade = tonumber(itemObj.Icon:match("misc(%d)")) - 1; if (recipeGrade <= 0) then recipeGrade = 1 end; grade = recipeGrade; end return grade; end local function GetItemRarityColor(itemObj) local itemProp = geItemTable.GetProp(itemObj.ClassID); local grade = GetItemGrade(itemObj); if (itemProp.setInfo ~= nil) then return "00FF00"; -- set piece elseif (grade == 0) then return "FFBF33"; -- premium elseif (grade == 1) then return "FFFFFF"; -- common elseif (grade == 2) then return "108CFF"; -- rare elseif (grade == 3) then return "9F30FF"; -- epic elseif (grade == 4) then return "FF4F00"; -- orange elseif (grade == 5) then return "FFFF53"; -- legendary else return "E1E1E1"; -- no grade (non-equipment items) end end local function GetTimeText(value, length) length = length or 1; local tmpValue = value; local strResult, strSplitter = "", " "; local index = 1; if value >= 3600 * 24 then if strResult ~= "" then strResult = strResult .. strSplitter end strResult = strResult .. string.format("%d%s", math.floor(tmpValue / 3600 / 24), Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Day")); index = index + 1; end if index > length then return strResult end tmpValue = (tmpValue % (24 * 3600)); if value >= 3600 then if strResult ~= "" then strResult = strResult .. strSplitter end strResult = strResult .. string.format("%d%s", math.floor(tmpValue / 3600), Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Hour")); index = index + 1; end if index > length then return strResult end tmpValue = tmpValue % 3600; if value >= 60 then if strResult ~= "" then strResult = strResult .. strSplitter end strResult = strResult .. string.format("%d%s", math.floor(tmpValue / 60), Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Minutes")); index = index + 1; end if index > length then return strResult end tmpValue = tmpValue % 60; if strResult ~= "" then strResult = strResult .. strSplitter end strResult = strResult .. string.format("%d%s", math.ceil(tmpValue), Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Second")); return strResult; end -- 状態判定 local function GetState_ShowElapsedTime() if Me.Settings.useSimpleMenu then -- かんたんモード使用中 --if Me.Settings.CurrentMode == "Normal" then return Me.Settings.ShowElapsedTime; --else -- return true; --end else return Me.Settings.ShowElapsedTime; end end local function GetState_ShowCurrent() if Me.Settings.useSimpleMenu then return true; else return Me.Settings.ShowCurrent; end end local function GetState_ShowGuess() if Me.Settings.useSimpleMenu then return false; else return Me.Settings.ShowGuess; end end local function GetState_ShowLog() if Me.Settings.useSimpleMenu then return true; else return Me.Settings.ShowLog; end end local function GetState_OrderBy() if Me.Settings.useSimpleMenu then -- かんたんモード使用中 if Me.Settings.CurrentMode == "Normal" then return "byGetTime"; else return "byCount"; end else return Me.Settings.OrderBy; end end local function GetState_ShowOldItem() if Me.Settings.useSimpleMenu then -- かんたんモード使用中 if Me.Settings.CurrentMode == "Counter" or Me.Settings.CurrentMode == "Detail" then return true; else return false; end else return Me.Settings.ShowOldItem; end end local function GetState_ShowOldItemInLog() if Me.Settings.useSimpleMenu then -- かんたんモード使用中 if Me.Settings.CurrentMode == "Detail" then return true; else return false; end else return Me.Settings.ShowOldItem; end end -- 個数取得 local function GetEquipInvCount(itemClsName) if itemClsName == nil or itemClsName == "" or itemClsName == "None" then return 0; end local invItemList = session.GetInvItemList(); local retTable = {Value = 0}; FOR_EACH_INVENTORY(invItemList, function(invItemList, invItem, retTable, itemClsName) if invItem ~= nil then local objItem = GetIES(invItem:GetObject()); if objItem.ClassName == itemClsName then retTable.Value = retTable.Value + 1; end end end, false, retTable, itemClsName); return retTable.Value; end function Me.Test(itemClsName) return GetEquipInvCount(itemClsName) end local function GetCurrentCount(itemClsName) if itemClsName == nil or itemClsName == "" or itemClsName == "None" then return 0; end local PickData = Me.Data.Pick[itemClsName]; if PickData.ItemType == nil then PickData.ItemType = GetClass("Item", itemClsName).ItemType; end if PickData.ItemType == "Equip" then return GetEquipInvCount(itemClsName) elseif session.GetInvItemByName(itemClsName) == nil then return 0; else return session.GetInvItemByName(itemClsName).count; end end local function GetDiffCount(itemClsName) if itemClsName == nil or itemClsName == "" or itemClsName == "None" then return 0; end local PickData = Me.Data.Pick[itemClsName]; local CurrentNum = GetCurrentCount(itemClsName) or 0 local StartNum = PickData.StartNum or 0; return CurrentNum - StartNum; end -- バッファー初期化 local function InitPickData(itemClsName, pickedCount) Me.Data.Pick[itemClsName] = {}; Me.Data.Pick[itemClsName].ClassName = itemClsName; Me.Data.Pick[itemClsName].Name = dictionary.ReplaceDicIDInCompStr(GetClass("Item", itemClsName).Name); Me.Data.Pick[itemClsName].StartNum = GetCurrentCount(itemClsName) - pickedCount; Me.Data.Pick[itemClsName].Log = {}; end function Me.UpdateItemPickData(itemType, itemCount) -- 開始時間がない場合は開始時間を登録する if Me.Data.StartTime == nil then Me.Data.StartTime = os.clock(); end -- バッファー領域がない場合は作成する if Me.Data.Pick == nil then Me.Data.Pick = {}; end local itemCls = GetClassByType("Item", tonumber(itemType)); if itemCls == nil then return end local itemClsName = itemCls.ClassName -- データが無い場合は新規に作成する if Me.Data.Pick[itemClsName] == nil then InitPickData(itemClsName, itemCount) end Me.Data.LastTime = os.clock(); Me.Data.Pick[itemClsName].LastTime = os.clock(); Me.Data.Pick[itemClsName].CurrentNum = GetCurrentCount(itemClsName); local PickLog = Me.Data.Pick[itemClsName].Log; -- データを登録する table.insert(PickLog, { time = os.clock() , count = itemCount }) if Toukibi:GetTableLen(PickLog) > 5 then table.remove(PickLog, 1) end Me.Data.Pick[itemClsName].DiffCount = GetDiffCount(itemClsName); Me.UpdateFrame() end local function MakeItemText(itemClsName) local styleTitle = {"#AAFFAA", "s12", "ol", "b"} local styleValue = {"#EEEEEE", "s16", "ol", "b"} if itemClsName == nil or itemClsName == "" or itemClsName == "None" then return nil end local strResult = ""; local PickData = Me.Data.Pick[itemClsName]; -- メインの表示 local itemCls = GetClass("Item", itemClsName); strResult = string.format("{img %s 24 24} {#%s}%s{/} {#33FFFF}( %s ){/}" , itemCls.Icon , GetItemRarityColor(itemCls) , dictionary.ReplaceDicIDInCompStr(itemCls.Name) -- .. ":" .. itemClsName , GetCommaedTextEx(GetDiffCount(itemClsName), 0, 0, true, false) ) if GetState_ShowCurrent() then -- 現在数の表示 strResult = strResult .. Toukibi:GetStyledText( string.format("%s%s" , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.TotalTitle") , GetCommaedTextEx(GetCurrentCount(itemClsName)) ) , {"s12", "#CCFFFF"} ) end local logLength = Toukibi:GetTableLen(PickData.Log); local NowIndex, MaxIndex = logLength, logLength; local StartTime = Me.Data.StartTime; if MaxIndex >= 3 then MaxIndex = 3; StartTime = PickData.Log[logLength - 2].time; end if GetState_ShowGuess() and logLength > 0 then -- 予測取得数の表示 local sumCount = 0; for i = 1, MaxIndex do sumCount = sumCount + PickData.Log[i].count end local ElapsedTime = os.clock() - StartTime; local GuessNum = sumCount / ElapsedTime * 3600; local strGuess = "" if GuessNum >= 10 then strGuess = string.format(Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.GuessFormat"), GetCommaedTextEx(GuessNum)); elseif GuessNum >= 5 then strGuess = string.format(Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.GuessFormat"), GetCommaedTextEx(GuessNum, 0, 1)); else GuessNum = ElapsedTime / sumCount; strGuess = string.format(Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.GuessFormatLong"), GetTimeText(GuessNum)) end if GetState_ShowOldItem() or (os.clock() - PickData.LastTime) <= Me.Settings.DueDateDisplay then strResult = strResult .. string.format("{nl}{s13}%s%s{#CCCC88}%s{/}{/}" , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.LogSpacer") , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.LogSpacer") , strGuess ) end end if GetState_ShowLog() then -- 簡易ログの表示 NowIndex = logLength; for i = 1, MaxIndex do if GetState_ShowOldItemInLog() or PickData.Log[NowIndex].time ~= nil and (os.clock() - PickData.Log[NowIndex].time) <= Me.Settings.DueDateDisplay then strResult = strResult .. string.format("{nl}{s12}%s{s%s}{#FFCCAA}%s{/} {#AAAA88}%s{/}{#666644}%s{/}{/}{/}" , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.LogSpacer") , 12 - i , GetCommaedTextEx(PickData.Log[NowIndex].count, 0, 0, true, false) , GetTimeText(os.clock() - PickData.Log[NowIndex].time) , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Ago") ) end NowIndex = NowIndex - 1 end end return strResult end local function GetMyWeightText() local GaugeWidth = 160; local RedZone = 90; local pc = GetMyPCObject(); local NowWeight, MaxWeight = pc.NowWeight, pc.MaxWeight; local textColor = "FFFFFF"; local WeightRate = 0; if MaxWeight > 0 then WeightRate = NowWeight * 100 / MaxWeight; end if MaxWeight < NowWeight then textColor = "FF1111"; elseif WeightRate >= 95 then textColor = "FF3333"; elseif WeightRate >= RedZone then textColor = "FF9999"; end local strResult = string.format("%s%s/%s {s12}(%d%s){/}" , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.WeightTitle") , Toukibi:GetStyledText(string.format("%.1f", NowWeight), {"#" .. textColor}) , MaxWeight , WeightRate , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Percent") ); local widthYellow, widthRed, widthBack = 0, 0, GaugeWidth; widthYellow = math.floor(NowWeight * GaugeWidth / MaxWeight); if widthYellow > GaugeWidth then widthYellow = GaugeWidth; end widthBack = GaugeWidth - widthYellow; if widthYellow * 100 > GaugeWidth * RedZone then local tmpValue = GaugeWidth * RedZone / 100; widthRed = widthYellow - tmpValue; widthYellow = tmpValue; end strResult = strResult .. "{nl}{s6} {/}"; if widthYellow > 0 then strResult = strResult .. string.format("{img fullyellow %d 2}", widthYellow); end if widthRed > 0 then strResult = strResult .. string.format("{img fullred %d 2}", widthRed); end if widthBack > 0 then strResult = strResult .. string.format("{img fullblack %d 2}", widthBack); end return strResult; end local function GetMercenaryBadgeGaugeText() local GaugeWidth = 160; local RedZone = 90; local acc = GetMyAccountObj(); if acc == nil then return end local NowCount = TryGetProp(acc, 'WEEKLY_PVP_MINE_COUNT', 0); local MaxCount = tonumber(MAX_WEEKLY_PVP_MINE_COUNT); local isTokenState = session.loginInfo.IsPremiumState(ITEM_TOKEN); if isTokenState == true then local bonusValue = tonumber(WEEKLY_PVP_MINE_COUNT_TOKEN_BONUS); MaxCount = MaxCount + bonusValue; end local textColor = "FFFFFF"; local WeeklyRate = 0; if MaxCount > 0 then WeeklyRate = NowCount * 100 / MaxCount; end if MaxCount < NowCount then textColor = "FF1111"; elseif WeeklyRate >= 95 then textColor = "FF3333"; elseif WeeklyRate >= RedZone then textColor = "FF9999"; end local strResult = string.format("%s%s/%s {s12}(%d%s){/}" , Toukibi:GetStyledText(Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.WeeklyMercenaryBadgeCount"), {"s14", "#cccccc"}) , Toukibi:GetStyledText(GetCommaedTextEx(NowCount), {"#" .. textColor}) , GetCommaedTextEx(MaxCount) , WeeklyRate , Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.Percent") ); local widthYellow, widthRed, widthBack = 0, 0, GaugeWidth; widthYellow = math.floor(NowCount * GaugeWidth / MaxCount); if widthYellow > GaugeWidth then widthYellow = GaugeWidth; end widthBack = GaugeWidth - widthYellow; if widthYellow * 100 > GaugeWidth * RedZone then local tmpValue = GaugeWidth * RedZone / 100; widthRed = widthYellow - tmpValue; widthYellow = tmpValue; end strResult = strResult .. "{nl}{s6} {/}"; if widthYellow > 0 then strResult = strResult .. string.format("{img fullyellow %d 2}", widthYellow); end if widthRed > 0 then strResult = strResult .. string.format("{img fullred %d 2}", widthRed); end if widthBack > 0 then strResult = strResult .. string.format("{img fullblack %d 2}", widthBack); end return strResult; end local function AddLabel(parent, ctrlName, text, left, top, style) if parent == nil then return end if ctrlName == nil or ctrlName == "" then return end left = left or 0; top = top or 0; style = style or {}; local objLabel = tolua.cast(parent:CreateOrGetControl("richtext", ctrlName, left, top, 10, 4), "ui::CRichText"); objLabel:SetGravity(ui.LEFT, ui.TOP); objLabel:EnableHitTest(0); objLabel:SetText(Toukibi:GetStyledText(text, style)); objLabel:ShowWindow(1); return objLabel; end local function SortByName(a, b) if a.ClassName == "misc_pvp_mine2" then -- 傭兵団コインであるか return false elseif b.ClassName == "misc_pvp_mine2" then return true end if a.ClassName == "Vis" then -- お金であるか return false elseif b.ClassName == "Vis" then return true end return a.Name < b.Name end local function SortByCount(a, b) if a.ClassName == "misc_pvp_mine2" then -- 傭兵団コインであるか return false elseif b.ClassName == "misc_pvp_mine2" then return true end if a.ClassName == "Vis" then -- お金であるか return false elseif b.ClassName == "Vis" then return true end if a.DiffCount ~= b.DiffCount then return a.DiffCount > b.DiffCount end return a.Name < b.Name end local function SortByGetTime(a, b) if a.ClassName == "misc_pvp_mine2" then -- 傭兵団コインであるか return false elseif b.ClassName == "misc_pvp_mine2" then return true end if a.ClassName == "Vis" then -- お金であるか return false elseif b.ClassName == "Vis" then return true end if a.LastTime ~= b.LastTime then return a.LastTime > b.LastTime end return a.Name < b.Name end function Me.UpdateFrame() local objFrame = ui.GetFrame(addonNameLower); if objFrame == nil then return end if Me.Settings.ShowVis and Me.Data.Pick.Vis == nil then -- シルバー情報がない場合は追加する InitPickData("Vis", 0) end if Me.Settings.ShowMercenaryBadge and Me.Data.Pick.misc_pvp_mine2 == nil then -- 傭兵団コイン情報がない場合は追加する InitPickData("misc_pvp_mine2", 0) end -- 並べ替えの準備を行う local tmpTable = {}; for _, value in pairs(Me.Data.Pick) do -- 表示の条件に見合うものだけを並べ替えの対象にする if GetState_ShowOldItem() or (value.ClassName == "Vis" and Me.Settings.ShowVis) or (value.ClassName == "misc_pvp_mine2" and Me.Settings.ShowMercenaryBadge) or (os.clock() - (value.LastTime or 0)) <= Me.Settings.DueDateDisplay then table.insert(tmpTable, value); else -- 表示の対象にならなかったコントロールは削除する local TargetLabelName = "lbl" .. value.ClassName; local lblTarget = objFrame:GetChild(TargetLabelName); if lblTarget ~= nil then objFrame:RemoveChild(TargetLabelName); end end end -- 並べ替えを行う local currentOrderBy = GetState_OrderBy() if currentOrderBy == "byGetTime" then table.sort(tmpTable, SortByGetTime); elseif currentOrderBy == "byName" then table.sort(tmpTable, SortByName); else table.sort(tmpTable, SortByCount); end -- 結果の表示を行う local cPosY = 2; local MarginBottom = 0; local MaxWeight = 0; local strResult, TargetLabelName = ""; local hasDisplayData = false; -- 経過時間 TargetLabelName = "lblElapsedTime"; if GetState_ShowElapsedTime() and Me.Data.StartTime ~= nil then strResult = Toukibi:GetStyledText(string.format(Toukibi:GetResText(ResText, Me.Settings.Lang, "Other.ElapsedTimeFormat"), GetTimeText(os.clock() - Me.Data.StartTime, 2)),{"#EEEEEE", "s12", "ol", "b"}); local lblResult = AddLabel(objFrame, TargetLabelName, strResult, 2, cPosY) cPosY = cPosY + lblResult:GetHeight() + MarginBottom; if lblResult:GetWidth() > MaxWeight then MaxWeight = lblResult:GetWidth() end hasDisplayData = true; else local lblTarget = objFrame:GetChild(TargetLabelName); if lblTarget ~= nil then objFrame:RemoveChild(TargetLabelName); end end for _, value in ipairs(tmpTable) do local itemClsName = value.ClassName TargetLabelName = "lbl" .. itemClsName; local strTemp = MakeItemText(itemClsName); if strTemp ~= nil and strTemp ~= "" then local lblResult = AddLabel(objFrame, TargetLabelName, strTemp, 2, cPosY, {"#EEEEEE", "s16", "ol", "b"}) cPosY = cPosY + lblResult:GetHeight() + MarginBottom; if lblResult:GetWidth() > MaxWeight then MaxWeight = lblResult:GetWidth() end hasDisplayData = true; else local lblTarget = objFrame:GetChild(TargetLabelName); if lblTarget ~= nil then objFrame:RemoveChild(TargetLabelName); end end end TargetLabelName = "lblFooter"; strResult = ""; if Me.Settings.ShowWeight or Me.Settings.ShowMBadgeGauge then if Me.Settings.ShowMBadgeGauge then if strResult ~= "" then strResult = strResult .. "{nl}{s6} {/}{nl}" end strResult = strResult .. GetMercenaryBadgeGaugeText(); end if Me.Settings.ShowWeight then if strResult ~= "" then strResult = strResult .. "{nl}{s6} {/}{nl}" end strResult = strResult .. GetMyWeightText(); end cPosY = cPosY + 6; elseif not hasDisplayData then strResult = Toukibi:GetStyledText("Better Pick Queue ver. " .. verText, {"#666666", "s12"}); end if strResult ~= "" then local lblFooter = AddLabel(objFrame, TargetLabelName, strResult, 2, cPosY, {"#EEEEEE", "s16", "ol", "b"}); cPosY = cPosY + lblFooter:GetHeight() + 2; if lblFooter:GetWidth() > MaxWeight then MaxWeight = lblFooter:GetWidth() end else local lblTarget = objFrame:GetChild(TargetLabelName); if lblTarget ~= nil then objFrame:RemoveChild(TargetLabelName); end end if Me.Settings.SkinName ~= nil then objFrame:SetSkinName(Me.Settings.SkinName); end objFrame:Resize(MaxWeight + 4, cPosY); end function Me.UpdatePos() local objFrame = ui.GetFrame(addonNameLower) if objFrame == nil then return end if Me.Settings.ExpandTo_Up then if Me.Settings.ExpandTo_Left then if Me.Settings ~= nil and Me.Settings.MarginRight ~= nil and Me.Settings.MarginBottom ~= nil then objFrame:SetGravity(ui.RIGHT, ui.BOTTOM); objFrame:SetMargin(0, 0, Me.Settings.MarginRight, Me.Settings.MarginBottom); end else if Me.Settings ~= nil and Me.Settings.PosX ~= nil and Me.Settings.MarginBottom ~= nil then objFrame:SetGravity(ui.LEFT, ui.BOTTOM); objFrame:SetMargin(Me.Settings.PosX, 0, 0, Me.Settings.MarginBottom); end end else if Me.Settings.ExpandTo_Left then if Me.Settings ~= nil and Me.Settings.MarginBottom ~= nil and Me.Settings.PosY ~= nil then objFrame:SetGravity(ui.RIGHT, ui.TOP); objFrame:SetMargin(0, Me.Settings.PosY, Me.Settings.MarginRight, 0); end else if Me.Settings ~= nil and Me.Settings.PosX ~= nil and Me.Settings.PosY ~= nil then objFrame:SetGravity(ui.LEFT, ui.TOP); objFrame:SetMargin(Me.Settings.PosX, Me.Settings.PosY, 0, 0); end end end end function Me.ResetPos() Me.Settings.PosX = 0; Me.Settings.PosY = 250; Me.Settings.MarginBottom = 90; Me.Settings.MarginRight = 20; Me.UpdatePos(); end -- =========================== -- イベント受け取り -- =========================== function Me.ITEMMSG_SHOW_GET_ITEM_HOOKED(frame, itemType, count) -- log("ITEMMSG_SHOW_GET_ITEM_HOOKED実行"); if not Me.Settings.HideOriginalQueue then Me.HoockedOrigProc["ITEMMSG_SHOW_GET_ITEM"](frame, itemType, count); end end function TOUKIBI_BETTERPICKQUEUE_ON_ITEM_PICK(frame, msg, itemType, itemCount) Me.UpdateItemPickData(itemType, itemCount); end function TOUKIBI_BETTERPICKQUEUE_START_DRAG() Me.IsDragging = true; end function TOUKIBI_BETTERPICKQUEUE_END_DRAG() Me.IsDragging = false; if not Me.Settings.Movable then return end local objFrame = ui.GetFrame(addonNameLower) if objFrame == nil then return end Me.Settings.PosX = objFrame:GetX(); Me.Settings.PosY = objFrame:GetY(); Me.Settings.MarginBottom = ui.GetClientInitialHeight() - Me.Settings.PosY - objFrame:GetHeight(); Me.Settings.MarginRight = ui.GetClientInitialWidth() - Me.Settings.PosX - objFrame:GetWidth(); SaveSetting(); end function TOUKIBI_BETTERPICKQUEUE_UPDATE() Me.UpdateFrame(); end function TOUKIBI_BETTERPICKQUEUE_RESET_DATA() Me.Data = {}; Me.Data.Pick = {}; local objFrame = ui.GetFrame(addonNameLower); if objFrame ~= nil then objFrame:RemoveAllChild(); end Toukibi:AddLog(Toukibi:GetResText(ResText, Me.Settings.Lang, "Log.ResetSession"), "Notice", true, false); Me.UpdateFrame(); end function TOUKIBI_BETTERPICKQUEUE_RESET_POSITION() Me.ResetPos(); SaveSetting(); end function TOUKIBI_BETTERPICKQUEUE_CHANGE_MOVABLE() if Me.Settings == nil then return end Me.Settings.Movable = not Me.Settings.Movable; local objFrame = ui.GetFrame(addonNameLower) if objFrame ~= nil then objFrame:EnableMove(Me.Settings.Movable and 1 or 0); SaveSetting(); end end function TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE(propName, value) ui.CloseAllContextMenu(); if Me.Settings == nil then return end Me.Settings[propName] = (value == 1); SaveSetting(); Me.UpdateFrame(); if propName == "ExpandTo_Up" or propName == "ExpandTo_Left" then Me.UpdatePos() end end function TOUKIBI_BETTERPICKQUEUE_SETVALUE(propName, value) ui.CloseAllContextMenu(); if Me.Settings == nil then return end Me.Settings[propName] = value; SaveSetting(); Me.UpdateFrame(); end function TOUKIBI_BETTERPICKQUEUE_CONTEXT_MENU(frame, ctrl) local titleText = Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.Title"); local cmenuWidth = 270; local CallSubMenu = false; if FunctionExists(keyboard.IsPressed) then -- 2018/06/27パッチ前 CallSubMenu = (keyboard.IsPressed(KEY_SHIFT) == 1); elseif FunctionExists(keyboard.IsKeyPressed) then -- 2018/06/27パッチ後 CallSubMenu = (keyboard.IsKeyPressed("LSHIFT") == 1 or keyboard.IsKeyPressed("RSHIFT") == 1); else -- どっちの関数もなかった場合 CallSubMenu = false; end if not CallSubMenu then titleText = titleText .. Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.SecondaryInfo"); else titleText = titleText .. Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.SecondaryTitle"); CallSubMenu = true; end local context = ui.CreateContextMenu("BETTERPICKQUEUE_MAIN_RBTN", titleText, 0, 0, cmenuWidth - 10, 0); if not CallSubMenu then -- 通常メニュー Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.useSimpleMenu"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "useSimpleMenu", not Me.Settings.useSimpleMenu and 1 or 0), nil, Me.Settings.useSimpleMenu); if Me.Settings.useSimpleMenu then -- 簡単メニュー Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "SimpleMenuSelect.Title")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "SimpleMenuSelect.Normal"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "CurrentMode", "Normal"), nil, (Me.Settings.CurrentMode == "Normal")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "SimpleMenuSelect.Counter"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "CurrentMode", "Counter"), nil, (Me.Settings.CurrentMode == "Counter")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "SimpleMenuSelect.Detail"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "CurrentMode", "Detail"), nil, (Me.Settings.CurrentMode == "Detail")); else -- カスタム設定 Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.DisplayItems")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.CurrentCount"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowCurrent", not Me.Settings.ShowCurrent and 1 or 0), nil, Me.Settings.ShowCurrent); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.GuessCount"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowGuess", not Me.Settings.ShowGuess and 1 or 0), nil, Me.Settings.ShowGuess); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.SimpleLog"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowLog", not Me.Settings.ShowLog and 1 or 0), nil, Me.Settings.ShowLog); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.ElapsedTime"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowElapsedTime", not Me.Settings.ShowElapsedTime and 1 or 0), nil, Me.Settings.ShowElapsedTime); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.SortedBy")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Order.byName"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "OrderBy", "byName"), nil, (Me.Settings.OrderBy == "byName")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Order.byCount"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "OrderBy", "byCount"), nil, (Me.Settings.OrderBy == "byCount")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Order.byGetTime"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "OrderBy", "byGetTime"), nil, (Me.Settings.OrderBy == "byGetTime")); end Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.AllwaysDisplay")); if Me.Settings.useSimpleMenu then -- かんたんメニューときだけ表示 Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.ElapsedTime"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowElapsedTime", not Me.Settings.ShowElapsedTime and 1 or 0), nil, Me.Settings.ShowElapsedTime); end Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.Silver"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowVis", not Me.Settings.ShowVis and 1 or 0), nil, Me.Settings.ShowVis); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.MercenaryBadge"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowMercenaryBadge", not Me.Settings.ShowMercenaryBadge and 1 or 0), nil, Me.Settings.ShowMercenaryBadge); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.WeeklyMercenaryBadgeCount"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowMBadgeGauge", not Me.Settings.ShowMBadgeGauge and 1 or 0), nil, Me.Settings.ShowMBadgeGauge); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.WeightData"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowWeight", not Me.Settings.ShowWeight and 1 or 0), nil, Me.Settings.ShowWeight); if not Me.Settings.useSimpleMenu then -- カスタムメニューのときだけ表示 Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Display.OldItem"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ShowOldItem", not Me.Settings.ShowOldItem and 1 or 0), nil, Me.Settings.ShowOldItem); end Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, nil, nil, 1); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.LockPosition"), "TOUKIBI_BETTERPICKQUEUE_CHANGE_MOVABLE()", nil, not Me.Settings.Movable); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, nil, nil, 2); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ResetSession"), "TOUKIBI_BETTERPICKQUEUE_RESET_DATA()"); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, nil, nil, 3); else cmenuWidth = 270 --第2メニュー Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.HideOriginalQueue"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "HideOriginalQueue", not Me.Settings.HideOriginalQueue and 1 or 0), nil, Me.Settings.HideOriginalQueue); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.AutoReset")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "AutoReset.byMap"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "AutoResetByMap", not Me.Settings.AutoResetByMap and 1 or 0), nil, Me.Settings.AutoResetByMap); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "AutoReset.byChannel"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "AutoResetByCh", not Me.Settings.AutoResetByCh and 1 or 0), nil, Me.Settings.AutoResetByCh); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.BackGround")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "BackGround.Deep"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "SkinName", "systemmenu_vertical"), nil, (Me.Settings.SkinName == "systemmenu_vertical")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "BackGround.Thin"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "SkinName", "chat_window"), nil, (Me.Settings.SkinName == "chat_window")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "BackGround.None"), string.format("TOUKIBI_BETTERPICKQUEUE_SETVALUE('%s', '%s')", "SkinName", "None"), nil, (Me.Settings.SkinName == "None")); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ExpandTo_Horizonal")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ExpandTo_Left"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ExpandTo_Left", 1), nil, Me.Settings.ExpandTo_Left); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ExpandTo_Right"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ExpandTo_Left", 0), nil, not Me.Settings.ExpandTo_Left); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ExpandTo_Vertical")); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ExpandTo_Up"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ExpandTo_Up", 1), nil, Me.Settings.ExpandTo_Up); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ExpandTo_Down"), string.format("TOUKIBI_BETTERPICKQUEUE_TOGGLE_VALUE('%s', %s)", "ExpandTo_Up", 0), nil, not Me.Settings.ExpandTo_Up); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, nil, nil, 1); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.ResetPosition"), "TOUKIBI_BETTERPICKQUEUE_RESET_POSITION()"); Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.UpdateNow"), "TOUKIBI_BETTERPICKQUEUE_UPDATE()"); Toukibi:MakeCMenuSeparator(context, cmenuWidth - 30, nil, nil, 2); end Toukibi:MakeCMenuItem(context, Toukibi:GetResText(ResText, Me.Settings.Lang, "Menu.Close")); context:Resize(cmenuWidth, context:GetHeight()); ui.OpenContextMenu(context); return context; end function TOUKIBI_BETTERPICKQUEUE_ON_GAME_START() local NowMapClassName = session.GetMapName(); local isMapChanged = (Me.Data.BeforeMap ~= NowMapClassName) if Me.Settings.AutoResetByCh or (Me.Settings.AutoResetByMap and isMapChanged) then TOUKIBI_BETTERPICKQUEUE_RESET_DATA(); end Me.Data.BeforeMap = NowMapClassName; Me.UpdateFrame(); end -- ===== アドオンの内容ここまで ===== -- ===== ここから先またお決まり文句 ===== -- スラッシュコマンド受取 function TOUKIBI_BETTERPICKQUEUE_PROCESS_COMMAND(command) Toukibi:AddLog(string.format(Toukibi:GetResText(ResText, Me.Settings.Lang, "System.ExecuteCommands"), SlashCommandList[1] .. " " .. table.concat(command, " ")), "Info", true, true); local cmd = ""; if #command > 0 then -- パラメータが存在した場合はパラメータの1個めを抜き出してみる cmd = table.remove(command, 1); else -- パラメータなしでコマンドが呼ばれた場合 ui.ToggleFrame(addonNameLower) return; end if cmd == "reset" then -- 計測をリセット TOUKIBI_BETTERPICKQUEUE_RESET_DATA(); return; elseif cmd == "resetpos" then -- 位置をリセット Me.ResetPos(); return; elseif cmd == "resetsetting" then -- 設定をリセット MargeDefaultSetting(true, true); Toukibi:AddLog(Toukibi:GetResText(ResText, Me.Settings.Lang, "System.ResetSettings"), "Notice", true, false); Me.UpdatePos(); TOUKIBI_BETTERPICKQUEUE_UPDATE(); return; elseif cmd == "update" then -- Updateの処理をここに書く TOUKIBI_BETTERPICKQUEUE_UPDATE(); return; elseif cmd == "jp" or cmd == "en" or string.len(cmd) == 2 then -- 言語モードと勘違いした? if cmd == "ja" then cmd = "jp" end Me.ComLib:ChangeLanguage(cmd); -- 何か更新したければ更新処理をここに書く return; elseif cmd ~= nil and cmd ~= "?" and cmd ~= "" then local strError = Toukibi:GetResText(ResText, Me.Settings.Lang, "System.InvalidCommand"); if #SlashCommandList > 0 then strError = strError .. string.format("{nl}" .. Toukibi:GetResText(ResText, Me.Settings.Lang, "System.AnnounceCommandList"), SlashCommandList[1]); end Toukibi:AddLog(strError, "Warning", true, false); end Me.ComLib:ShowHelpText() end Me.HoockedOrigProc = Me.HoockedOrigProc or {}; function BETTERPICKQUEUE_ON_INIT(addon, frame) -- 設定を読み込む if not Me.Loaded then Me.Loaded = true; LoadSetting(); end if Me.Settings.DoNothing then return end -- イベントを登録する frame:SetEventScript(ui.LBUTTONDOWN, "TOUKIBI_BETTERPICKQUEUE_START_DRAG"); frame:SetEventScript(ui.LBUTTONUP, "TOUKIBI_BETTERPICKQUEUE_END_DRAG"); frame:SetEventScript(ui.RBUTTONDOWN, "TOUKIBI_BETTERPICKQUEUE_CONTEXT_MENU"); addon:RegisterMsg('ITEM_PICK', 'TOUKIBI_BETTERPICKQUEUE_ON_ITEM_PICK'); addon:RegisterMsg('GAME_START', 'TOUKIBI_BETTERPICKQUEUE_ON_GAME_START'); addon:RegisterMsg("FPS_UPDATE", "TOUKIBI_BETTERPICKQUEUE_UPDATE"); -- フックしたいイベントを記述 Toukibi:SetHook("ITEMMSG_SHOW_GET_ITEM", Me.ITEMMSG_SHOW_GET_ITEM_HOOKED); Me.IsDragging = false; ui.GetFrame(addonNameLower):EnableMove(Me.Settings.Movable and 1 or 0); Me.UpdatePos() -- スラッシュコマンドを登録する local acutil = require("acutil"); for i = 1, #SlashCommandList do acutil.slashCommand(SlashCommandList[i], TOUKIBI_BETTERPICKQUEUE_PROCESS_COMMAND); end end
gpl-3.0
NideXTC/formations
PHP/Exercices/login/connect.php
745
<?php error_reporting(E_ALL); ini_set("display_errors", 1); /* * DOC : pdo.__construct() * Connexion à la BDD * Wrap try/catch * Jeter des exceptions */ try { $db = new PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8', 'root', 'root'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch (PDOException $pe) { echo $pe->getMessage(); } function pdo_query($req, $data = [], $fetch = true) { $stmt = $db->prepare($req); $stmt->execute($data); return ($fetch) ? $stmt->fetchAll() : true; } function pdo_exec($req, $data = []) { $stmt = $db->prepare($req); $stmt->execute($data); }
gpl-3.0
sosilent/euca
clc/modules/www/src/main/java/com/eucalyptus/webui/client/service/AwsServiceAsync.java
4494
package com.eucalyptus.webui.client.service; import java.util.ArrayList; import java.util.List; import com.eucalyptus.webui.client.session.Session; import com.eucalyptus.webui.shared.aws.ImageType; import com.google.gwt.user.client.rpc.AsyncCallback; public interface AwsServiceAsync { void lookupInstance(Session session, int userID, String search, SearchRange range, AsyncCallback<SearchResult> callback); void startInstances(Session session, int userID, List<String> ids, AsyncCallback<ArrayList<String>> callback); void stopInstances(Session session, int userID, List<String> ids, AsyncCallback<ArrayList<String>> callback); void terminateInstances(Session session, int userID, List<String> ids, AsyncCallback<ArrayList<String>> callback); void lookupImage(Session session, int userID, String search, SearchRange range, AsyncCallback<SearchResult> callback); void runInstance(Session session, int userID, String image, String key, AsyncCallback<String> callback); void lookupKeypair(Session session, int userID, String search, SearchRange range, AsyncCallback<SearchResult> callback); void addKeypair(Session session, int userID, String name, AsyncCallback<String> callback); void importKeypair(Session session, int userID, String name, String key, AsyncCallback<Void> callback); void deleteKeypairs(Session session, int userID, List<String> keys, AsyncCallback<Void> callback); void createSecurityGroup(Session session, int userID, String name, String desc, AsyncCallback<String> callback); void lookupSecurityGroup(Session session, int userID, String search, SearchRange range, AsyncCallback<SearchResult> callback); void deleteSecurityGroups(Session session, int userID, List<String> names, AsyncCallback<Void> callback); void lookupSecurityRule(Session session, int userID, String search, SearchRange range, AsyncCallback<SearchResult> callback); void addSecurityRule(Session session, int userID, String group, String fromPort, String toPort, String proto, String ipRange, AsyncCallback<Void> callback); void delSecurityRules(Session session, int userID, List<String> groups, List<String> fromPorts, List<String> toPorts, List<String> protos, List<String> ipRanges, AsyncCallback<Void> callback); void bindImage(Session session, int userID, String id, String sysName, String sysVer, AsyncCallback<Void> callback); void unbindImages(Session session, int userID, List<String> ids, AsyncCallback<Void> callback); void lookupNodeCtrl(Session session, String search, SearchRange range, AsyncCallback<SearchResult> callback); void lookupWalrusCtrl(Session session, String search, SearchRange range, AsyncCallback<SearchResult> callback); void lookupStorageCtrl(Session session, String search, SearchRange range, AsyncCallback<SearchResult> callback); void lookupClusterCtrl(Session session, String search, SearchRange range, AsyncCallback<SearchResult> callback); void uploadImage(Session session, int userID, String file, ImageType type, String bucket, String name, String kernel, String ramdisk, AsyncCallback<String> callback); void runInstance(Session session, int userID, String image, String keypair, String vmtype, String group, AsyncCallback<String> callback); void registerCluster(Session session, String part, String host, String name, AsyncCallback<Void> callback); void deregisterCluster(Session session, String part, String name, AsyncCallback<Void> callback); void deregisterNode(Session session, String host, AsyncCallback<Void> callback); void registerWalrus(Session session, String host, String name, AsyncCallback<Void> callback); void registerStorage(Session session, String part, String host, String name, AsyncCallback<Void> callback); void deregisterWalrus(Session session, String name, AsyncCallback<Void> callback); void registerNode(Session session, String host, AsyncCallback<Void> callback); void deregisterStorage(Session session, String part, String name, AsyncCallback<Void> callback); void lookupAvailablityZones(Session session, AsyncCallback<ArrayList<String>> callback); void associateAddress(Session session, int userID, String ip, String instanceID, AsyncCallback<Void> callback); void lookupOwnAddress(Session session, int userID, AsyncCallback<List<String>> callback); }
gpl-3.0
jobbrIO/jobbr-execution-forked
source/Jobbr.Server.ForkedExecution/Execution/ServiceMessaging/ProgressServiceMessage.cs
340
namespace Jobbr.Server.ForkedExecution.Execution.ServiceMessaging { /// <summary> /// The progress service message. /// </summary> public class ProgressServiceMessage : ServiceMessage { /// <summary> /// Gets or sets the percent. /// </summary> public double Percent { get; set; } } }
gpl-3.0
Warren-GH/emgucv
Emgu.CV.Cuda/CudaImage.cs
15359
//---------------------------------------------------------------------------- // Copyright (C) 2004-2015 by EMGU Corporation. All rights reserved. //---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using Emgu.CV; using Emgu.CV.Structure; using Emgu.CV.Util; #if ANDROID using Bitmap = Android.Graphics.Bitmap; #endif namespace Emgu.CV.Cuda { /// <summary> /// An CudaImage is very similar to the Emgu.CV.Image except that it is being used for GPU processing /// </summary> /// <typeparam name="TColor">Color type of this image (either Gray, Bgr, Bgra, Hsv, Hls, Lab, Luv, Xyz, Ycc, Rgb or Rbga)</typeparam> /// <typeparam name="TDepth">Depth of this image (either Byte, SByte, Single, double, UInt16, Int16 or Int32)</typeparam> public class CudaImage<TColor, TDepth> : GpuMat<TDepth>, IImage where TColor : struct, IColor where TDepth : new() { #region constructors /// <summary> /// Create an empty CudaImage /// </summary> public CudaImage() : base() { } /// <summary> /// Create the CudaImage from the unmanaged pointer. /// </summary> /// <param name="ptr">The unmanaged pointer to the GpuMat. It is the user's responsibility that the Color type and depth matches between the managed class and unmanaged pointer.</param> internal CudaImage(IntPtr ptr, bool needDispose) : base(ptr, needDispose) { } /// <summary> /// Create a GPU image from a regular image /// </summary> /// <param name="img">The image to be converted to GPU image</param> public CudaImage(IInputArray img) : base(img) { } /// <summary> /// Create a CudaImage of the specific size /// </summary> /// <param name="rows">The number of rows (height)</param> /// <param name="cols">The number of columns (width)</param> /// <param name="continuous">Indicates if the data should be continuous</param> public CudaImage(int rows, int cols, bool continuous) : base(rows, cols, new TColor().Dimension, continuous) { } /// <summary> /// Create a CudaImage of the specific size /// </summary> /// <param name="rows">The number of rows (height)</param> /// <param name="cols">The number of columns (width)</param> public CudaImage(int rows, int cols) : base(rows, cols, new TColor().Dimension) { } /// <summary> /// Create a CudaImage of the specific size /// </summary> /// <param name="size">The size of the image</param> public CudaImage(Size size) : this(size.Height, size.Width) { } /// <summary> /// Create a CudaImage from the specific region of <paramref name="image"/>. The data is shared between the two CudaImage /// </summary> /// <param name="image">The CudaImage where the region is extracted from</param> /// <param name="colRange">The column range. Use MCvSlice.WholeSeq for all columns.</param> /// <param name="rowRange">The row range. Use MCvSlice.WholeSeq for all rows.</param> public CudaImage(CudaImage<TColor, TDepth> image, MCvSlice rowRange, MCvSlice colRange) :this(CudaInvoke.GetRegion(image, ref rowRange, ref colRange), true) { } #endregion /// <summary> /// Convert the current CudaImage to a regular Image. /// </summary> /// <returns>A regular image</returns> public Image<TColor, TDepth> ToImage() { Image<TColor, TDepth> img = new Image<TColor, TDepth>(Size); Download(img); return img; } ///<summary> Convert the current CudaImage to the specific color and depth </summary> ///<typeparam name="TOtherColor"> The type of color to be converted to </typeparam> ///<typeparam name="TOtherDepth"> The type of pixel depth to be converted to </typeparam> ///<returns>CudaImage of the specific color and depth </returns> public CudaImage<TOtherColor, TOtherDepth> Convert<TOtherColor, TOtherDepth>() where TOtherColor : struct, IColor where TOtherDepth : new() { CudaImage<TOtherColor, TOtherDepth> res = new CudaImage<TOtherColor, TOtherDepth>(Size); res.ConvertFrom(this); return res; } /// <summary> /// Convert the source image to the current image, if the size are different, the current image will be a resized version of the srcImage. /// </summary> /// <typeparam name="TSrcColor">The color type of the source image</typeparam> /// <typeparam name="TSrcDepth">The color depth of the source image</typeparam> /// <param name="srcImage">The sourceImage</param> public void ConvertFrom<TSrcColor, TSrcDepth>(CudaImage<TSrcColor, TSrcDepth> srcImage) where TSrcColor : struct, IColor where TSrcDepth : new() { if (!Size.Equals(srcImage.Size)) { //if the size of the source image do not match the size of the current image using (CudaImage<TSrcColor, TSrcDepth> tmp = srcImage.Resize(Size, Emgu.CV.CvEnum.Inter.Linear, null)) { ConvertFrom(tmp); return; } } if (typeof(TColor) == typeof(TSrcColor)) { #region same color if (typeof(TDepth) == typeof(TSrcDepth)) //same depth { srcImage.CopyTo(this); } else //different depth { if (typeof(TDepth) == typeof(Byte) && typeof(TSrcDepth) != typeof(Byte)) { double[] minVal, maxVal; Point[] minLoc, maxLoc; srcImage.MinMax(out minVal, out maxVal, out minLoc, out maxLoc); double min = minVal[0]; double max = maxVal[0]; for (int i = 1; i < minVal.Length; i++) { min = Math.Min(min, minVal[i]); max = Math.Max(max, maxVal[i]); } double scale = 1.0, shift = 0.0; if (max > 255.0 || min < 0) { scale = (max == min) ? 0.0 : 255.0 / (max - min); shift = (scale == 0) ? min : -min * scale; } srcImage.ConvertTo(this, CvInvoke.GetDepthType(typeof(TDepth)), scale, shift, null); } else { srcImage.ConvertTo(this, CvInvoke.GetDepthType(typeof(TDepth)), 1.0, 0.0, null); //CudaInvoke.ConvertTo(srcImage.Ptr, Ptr, 1.0, 0.0, IntPtr.Zero); } } #endregion } else { #region different color if (typeof(TDepth) == typeof(TSrcDepth)) { //same depth ConvertColor(srcImage, this, typeof(TSrcColor), typeof(TColor), NumberOfChannels, Size, null); } else { //different depth using (CudaImage<TSrcColor, TDepth> tmp = srcImage.Convert<TSrcColor, TDepth>()) //convert depth ConvertColor(tmp, this, typeof(TSrcColor), typeof(TColor), NumberOfChannels, Size, null); } #endregion } } private static void ConvertColor(IInputArray src, IOutputArray dest, Type srcColor, Type destColor, int dcn, Size size, Stream stream) { try { // if the direct conversion exist, apply the conversion CudaInvoke.CvtColor(src, dest, CvToolbox.GetColorCvtCode(srcColor, destColor), dcn, stream); } catch { try { //if a direct conversion doesn't exist, apply a two step conversion //in this case, needs to wait for the completion of the stream because a temporary local image buffer is used //we don't want the tmp image to be released before the operation is completed. using (CudaImage<Bgr, TDepth> tmp = new CudaImage<Bgr, TDepth>(size)) { CudaInvoke.CvtColor(src, tmp, CvToolbox.GetColorCvtCode(srcColor, typeof(Bgr)), 3, stream); CudaInvoke.CvtColor(tmp, dest, CvToolbox.GetColorCvtCode(typeof(Bgr), destColor), dcn, stream); stream.WaitForCompletion(); } } catch (Exception excpt) { throw new NotSupportedException(String.Format( "Conversion from CudaImage<{0}, {1}> to CudaImage<{2}, {3}> is not supported by OpenCV: {4}", srcColor.ToString(), typeof(TDepth).ToString(), destColor.ToString(), typeof(TDepth).ToString(), excpt.Message)); } } } /// <summary> /// Create a clone of this CudaImage /// </summary> /// <param name="stream">Use a Stream to call the function asynchronously (non-blocking) or null to call the function synchronously (blocking).</param> /// <returns>A clone of this CudaImage</returns> public CudaImage<TColor, TDepth> Clone(Stream stream) { CudaImage<TColor, TDepth> result = new CudaImage<TColor, TDepth>(Size); CopyTo(result, null, stream); return result; } /// <summary> /// Resize the CudaImage. The calling GpuMat be GpuMat%lt;Byte&gt;. If stream is specified, it has to be either 1 or 4 channels. /// </summary> /// <param name="size">The new size</param> /// <param name="interpolationType">The interpolation type</param> /// <param name="stream">Use a Stream to call the function asynchronously (non-blocking) or null to call the function synchronously (blocking).</param> /// <returns>A CudaImage of the new size</returns> public CudaImage<TColor, TDepth> Resize(Size size, CvEnum.Inter interpolationType, Stream stream = null) { CudaImage<TColor, TDepth> result = new CudaImage<TColor, TDepth>(size); CudaInvoke.Resize(this, result, size, 0, 0, interpolationType, stream); return result; } /// <summary> /// Returns a CudaImage corresponding to a specified rectangle of the current CudaImage. The data is shared with the current matrix. In other words, it allows the user to treat a rectangular part of input array as a stand-alone array. /// </summary> /// <param name="region">Zero-based coordinates of the rectangle of interest.</param> /// <returns>A CudaImage that represent the region of the current CudaImage.</returns> /// <remarks>The parent CudaImage should never be released before the returned CudaImage that represent the subregion</remarks> public new CudaImage<TColor, TDepth> GetSubRect(Rectangle region) { return new CudaImage<TColor, TDepth>(CudaInvoke.GetSubRect(this, ref region), true); } /// <summary> /// Returns a CudaImage corresponding to the ith row of the CudaImage. The data is shared with the current Image. /// </summary> /// <param name="i">The row to be extracted</param> /// <returns>The ith row of the CudaImage</returns> /// <remarks>The parent CudaImage should never be released before the returned CudaImage that represent the subregion</remarks> public new CudaImage<TColor, TDepth> Row(int i) { return RowRange(i, i + 1); } /// <summary> /// Returns a CudaImage corresponding to the [<paramref name="start"/> <paramref name="end"/>) rows of the CudaImage. The data is shared with the current Image. /// </summary> /// <param name="start">The inclusive stating row to be extracted</param> /// <param name="end">The exclusive ending row to be extracted</param> /// <returns>The [<paramref name="start"/> <paramref name="end"/>) rows of the CudaImage</returns> /// <remarks>The parent CudaImage should never be released before the returned CudaImage that represent the subregion</remarks> public new CudaImage<TColor, TDepth> RowRange(int start, int end) { return new CudaImage<TColor, TDepth>(this, new MCvSlice(start, end), MCvSlice.WholeSeq); } /// <summary> /// Returns a CudaImage corresponding to the ith column of the CudaImage. The data is shared with the current Image. /// </summary> /// <param name="i">The column to be extracted</param> /// <returns>The ith column of the CudaImage</returns> /// <remarks>The parent CudaImage should never be released before the returned CudaImage that represent the subregion</remarks> public new CudaImage<TColor, TDepth> Col(int i) { return ColRange(i, i + 1); } /// <summary> /// Returns a CudaImage corresponding to the [<paramref name="start"/> <paramref name="end"/>) columns of the CudaImage. The data is shared with the current Image. /// </summary> /// <param name="start">The inclusive stating column to be extracted</param> /// <param name="end">The exclusive ending column to be extracted</param> /// <returns>The [<paramref name="start"/> <paramref name="end"/>) columns of the CudaImage</returns> /// <remarks>The parent CudaImage should never be released before the returned CudaImage that represent the subregion</remarks> public new CudaImage<TColor, TDepth> ColRange(int start, int end) { return new CudaImage<TColor, TDepth>(this, MCvSlice.WholeSeq, new MCvSlice(start, end)); } #region IImage Members #if IOS public MonoTouch.UIKit.UIImage ToUIImage() { throw new NotImplementedException(); } #elif !(NETFX_CORE || UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE || UNITY_METRO ) /// <summary> /// convert the current CudaImage to its equivalent Bitmap representation /// </summary> /// public Bitmap Bitmap { get { #if !ANDROID if (typeof(TColor) == typeof(Bgr) && typeof(TDepth) == typeof(Byte)) { Size s = Size; Bitmap result = new Bitmap(s.Width, s.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Imaging.BitmapData data = result.LockBits(new Rectangle(Point.Empty, result.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, result.PixelFormat); using (Image<TColor, TDepth> tmp = new Image<TColor, TDepth>(s.Width, s.Height, data.Stride, data.Scan0)) { Download(tmp); } result.UnlockBits(data); return result; } else #endif using (Image<TColor, TDepth> tmp = ToImage()) { return tmp.ToBitmap(); } } } #endif #endregion #region ICloneable Members object ICloneable.Clone() { return Clone(null); } #endregion } }
gpl-3.0
7starsea/libqxt-for-qt5
libqxt/src/core/qxtfilelock_win.cpp
2878
/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtCore module of the Qxt library. ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the Common Public License, version 1.0, as published ** by IBM, and/or under the terms of the GNU Lesser General Public License, ** version 2.1, as published by the Free Software Foundation. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL and the LGPL along with this ** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files ** included with the source distribution for more information. ** If you did not receive a copy of the licenses, contact the Qxt Foundation. ** ** <http://libqxt.org> <[email protected]> ** ****************************************************************************/ #include "qxtfilelock.h" #include "qxtfilelock_p.h" #include <windows.h> #include <io.h> bool QxtFileLock::unlock() { if (file() && file()->isOpen() && isActive()) { HANDLE w32FileHandle; OVERLAPPED ov1; w32FileHandle = (HANDLE)_get_osfhandle(file()->handle()); if (w32FileHandle == INVALID_HANDLE_VALUE) return false; memset(&ov1, 0, sizeof(ov1)); ov1.Offset = qxt_d().offset; if (UnlockFileEx(w32FileHandle, 0, qxt_d().length, 0, &ov1)) { qxt_d().isLocked = false; return true; } } return false; } bool QxtFileLock::lock() { if (file() && file()->isOpen() && !isActive()) { HANDLE w32FileHandle; OVERLAPPED ov1; DWORD dwflags; w32FileHandle = (HANDLE)_get_osfhandle(file()->handle()); if (w32FileHandle == INVALID_HANDLE_VALUE) return false; switch (qxt_d().mode) { case ReadLock: dwflags = LOCKFILE_FAIL_IMMEDIATELY; break; case ReadLockWait: dwflags = 0; break; case WriteLock: dwflags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY; break; case WriteLockWait: dwflags = LOCKFILE_EXCLUSIVE_LOCK; break; default: return (false); } memset(&ov1, 0, sizeof(ov1)); ov1.Offset = qxt_d().offset; if (LockFileEx(w32FileHandle, dwflags, 0, qxt_d().length, 0, &ov1)) { qxt_d().isLocked = true; return true; } } return false; }
gpl-3.0
papedaniel/oioioi
oioioi/scoresreveal/migrations/0001_initial.py
1584
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('contests', '0001_initial'), ('problems', '0001_initial'), ] operations = [ migrations.CreateModel( name='ScoreReveal', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('submission', models.OneToOneField(related_name='revealed', verbose_name='submission', to='contests.Submission')), ], options={ 'verbose_name': 'score reveal', 'verbose_name_plural': 'score reveals', }, bases=(models.Model,), ), migrations.CreateModel( name='ScoreRevealConfig', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('reveal_limit', models.IntegerField(verbose_name='reveal limit')), ('disable_time', models.IntegerField(null=True, verbose_name='disable for last minutes of the round', blank=True)), ('problem', models.OneToOneField(related_name='scores_reveal_config', verbose_name='problem', to='problems.Problem')), ], options={ 'verbose_name': 'score reveal config', 'verbose_name_plural': 'score reveal configs', }, bases=(models.Model,), ), ]
gpl-3.0
s20121035/rk3288_android5.1_repo
external/proguard/src/proguard/ant/ProGuardTask.java
9417
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2013 Eric Lafortune ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.ant; import org.apache.tools.ant.BuildException; import proguard.*; import proguard.classfile.util.ClassUtil; import java.io.*; import java.util.*; /** * This Task allows to configure and run ProGuard from Ant. * * @author Eric Lafortune */ public class ProGuardTask extends ConfigurationTask { // Ant task attributes. public void setConfiguration(File configurationFile) throws BuildException { try { // Get the combined system properties and Ant properties, for // replacing ProGuard-style properties ('<...>'). Properties properties = new Properties(); properties.putAll(getProject().getProperties()); ConfigurationParser parser = new ConfigurationParser(configurationFile, properties); try { parser.parse(configuration); } catch (ParseException ex) { throw new BuildException(ex.getMessage()); } finally { parser.close(); } } catch (IOException ex) { throw new BuildException(ex.getMessage()); } } /** * @deprecated Use the nested outjar element instead. */ public void setOutjar(String parameters) { throw new BuildException("Use the <outjar> nested element instead of the 'outjar' attribute"); } public void setSkipnonpubliclibraryclasses(boolean skipNonPublicLibraryClasses) { configuration.skipNonPublicLibraryClasses = skipNonPublicLibraryClasses; } public void setSkipnonpubliclibraryclassmembers(boolean skipNonPublicLibraryClassMembers) { configuration.skipNonPublicLibraryClassMembers = skipNonPublicLibraryClassMembers; } public void setTarget(String target) { configuration.targetClassVersion = ClassUtil.internalClassVersion(target); if (configuration.targetClassVersion == 0) { throw new BuildException("Unsupported target '"+target+"'"); } } public void setForceprocessing(boolean forceProcessing) { configuration.lastModified = forceProcessing ? Long.MAX_VALUE : 0; } public void setPrintseeds(File printSeeds) { configuration.printSeeds = optionalFile(printSeeds); } public void setShrink(boolean shrink) { configuration.shrink = shrink; } public void setPrintusage(File printUsage) { configuration.printUsage = optionalFile(printUsage); } public void setOptimize(boolean optimize) { configuration.optimize = optimize; } public void setOptimizationpasses(int optimizationPasses) { configuration.optimizationPasses = optimizationPasses; } public void setAllowaccessmodification(boolean allowAccessModification) { configuration.allowAccessModification = allowAccessModification; } public void setMergeinterfacesaggressively(boolean mergeinterfacesaggressively) { configuration.mergeInterfacesAggressively = mergeinterfacesaggressively; } public void setObfuscate(boolean obfuscate) { configuration.obfuscate = obfuscate; } public void setPrintmapping(File printMapping) { configuration.printMapping = optionalFile(printMapping); } public void setApplymapping(File applyMapping) { configuration.applyMapping = resolvedFile(applyMapping); } public void setObfuscationdictionary(File obfuscationDictionary) { configuration.obfuscationDictionary = resolvedFile(obfuscationDictionary); } public void setClassobfuscationdictionary(File classObfuscationDictionary) { configuration.classObfuscationDictionary = resolvedFile(classObfuscationDictionary); } public void setPackageobfuscationdictionary(File packageObfuscationDictionary) { configuration.packageObfuscationDictionary = resolvedFile(packageObfuscationDictionary); } public void setOverloadaggressively(boolean overloadAggressively) { configuration.overloadAggressively = overloadAggressively; } public void setUseuniqueclassmembernames(boolean useUniqueClassMemberNames) { configuration.useUniqueClassMemberNames = useUniqueClassMemberNames; } public void setUsemixedcaseclassnames(boolean useMixedCaseClassNames) { configuration.useMixedCaseClassNames = useMixedCaseClassNames; } public void setFlattenpackagehierarchy(String flattenPackageHierarchy) { configuration.flattenPackageHierarchy = ClassUtil.internalClassName(flattenPackageHierarchy); } public void setRepackageclasses(String repackageClasses) { configuration.repackageClasses = ClassUtil.internalClassName(repackageClasses); } /** * @deprecated Use the repackageclasses attribute instead. */ public void setDefaultpackage(String defaultPackage) { configuration.repackageClasses = ClassUtil.internalClassName(defaultPackage); } public void setKeepparameternames(boolean keepParameterNames) { configuration.keepParameterNames = keepParameterNames; } public void setRenamesourcefileattribute(String newSourceFileAttribute) { configuration.newSourceFileAttribute = newSourceFileAttribute; } public void setPreverify(boolean preverify) { configuration.preverify = preverify; } public void setMicroedition(boolean microEdition) { configuration.microEdition = microEdition; } public void setVerbose(boolean verbose) { configuration.verbose = verbose; } public void setNote(boolean note) { if (note) { // Switch on notes if they were completely disabled. if (configuration.note != null && configuration.note.isEmpty()) { configuration.note = null; } } else { // Switch off notes. configuration.note = new ArrayList(); } } public void setWarn(boolean warn) { if (warn) { // Switch on warnings if they were completely disabled. if (configuration.warn != null && configuration.warn.isEmpty()) { configuration.warn = null; } } else { // Switch off warnings. configuration.warn = new ArrayList(); } } public void setIgnorewarnings(boolean ignoreWarnings) { configuration.ignoreWarnings = ignoreWarnings; } public void setPrintconfiguration(File printConfiguration) { configuration.printConfiguration = optionalFile(printConfiguration); } public void setDump(File dump) { configuration.dump = optionalFile(dump); } // Implementations for Task. public void execute() throws BuildException { try { ProGuard proGuard = new ProGuard(configuration); proGuard.execute(); } catch (IOException ex) { throw new BuildException(ex.getMessage()); } } // Small utility methods. /** * Returns a file that is properly resolved with respect to the project * directory, or <code>null</code> or empty if its name is actually a * boolean flag. */ private File optionalFile(File file) { String fileName = file.getName(); return fileName.equalsIgnoreCase("false") || fileName.equalsIgnoreCase("no") || fileName.equalsIgnoreCase("off") ? null : fileName.equalsIgnoreCase("true") || fileName.equalsIgnoreCase("yes") || fileName.equalsIgnoreCase("on") ? Configuration.STD_OUT : resolvedFile(file); } /** * Returns a file that is properly resolved with respect to the project * directory. */ private File resolvedFile(File file) { return file.isAbsolute() ? file : new File(getProject().getBaseDir(), file.getName()); } }
gpl-3.0
stephaneeybert/learnintouch
index.php
1150
<?php /* This file is part of LearnInTouch. LearnInTouch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LearnInTouch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with LearnInTouch. If not, see <http://www.gnu.org/licenses/>. */ require_once("website.php"); $phone = LibEnv::getEnvHttpGET("phone"); if ($templateUtils->detectUserAgent() || $phone) { $templateModelId = $templateUtils->getPhoneEntry(); $templateUtils->setCurrentModel($templateModelId); $templateUtils->setPhoneClient(); require_once($gTemplatePath . "display.php"); } else { $templateModelId = $templateUtils->getComputerDefault(); $templateUtils->setCurrentModel($templateModelId); require_once($gFlashPath . "display.php"); } ?>
gpl-3.0
yp/ZRHCstar
include/expr_tree.hpp
2535
/** * * ZRHC-* * Zero-Recombinant Haplotype Configuration with missing genotypes * * Copyright (C) 2010 Yuri Pirola <yuri.pirola(-at-)gmail.com> * * Distributed under the terms of the GNU General Public License (GPL) * * * This file is part of ZRHC-* (ZRHCstar). * * ZRHC-* is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZRHC-* is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZRHC-*. If not, see <http://www.gnu.org/licenses/>. * **/ /** * * expr_tree.hpp * * Representation of a generic expression tree * **/ #ifndef __EXPR_TREE_HPP__ #define __EXPR_TREE_HPP__ #include "utility.hpp" #include <boost/ptr_container/ptr_list.hpp> #include <ostream> class expr_tree_node { protected: expr_tree_node() {}; private: virtual expr_tree_node* clone_impl() const = 0; public: virtual ~expr_tree_node() {}; expr_tree_node* clone() const { return clone_impl(); }; }; expr_tree_node* new_clone(const expr_tree_node& n); typedef enum { EXPR_OP_XOR= 0, EXPR_OP_NOT= 1, EXPR_OP_AND= 2, } expr_operator_enum; class expr_operator_t: public expr_tree_node { public: typedef boost::ptr_list<expr_tree_node> children_t; expr_operator_enum kind; children_t children; expr_operator_t(const expr_operator_enum _kind) :kind(_kind) {}; private: expr_operator_t(const expr_operator_enum _kind, const children_t& _children) :kind(_kind), children(_children) {}; virtual expr_operator_t* clone_impl() const { return new expr_operator_t(kind, children); }; }; class expr_variable_t: public expr_tree_node { public: int variable; expr_variable_t(const int _variable) :variable(_variable) {}; private: virtual expr_variable_t* clone_impl() const { return new expr_variable_t(variable); }; }; std::ostream& operator<< (std::ostream& out, const expr_tree_node& node); std::ostream& operator<< (std::ostream& out, const expr_operator_t& op); std::ostream& operator<< (std::ostream& out, const expr_variable_t& var); #endif // __EXPR_TREE_HPP__
gpl-3.0
r0balo/pelisalacarta
python/main-classic/channels/pornhub.py
4557
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para pornhub # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re import urlparse from core import config from core import logger from core import scrapertools from core.item import Item DEBUG = config.get_setting("debug") def mainlist(item): logger.info("[pornhub.py] mainlist") itemlist = [] itemlist.append( Item(channel=item.channel, action="peliculas", title="Novedades", fanart=item.fanart, url = "http://es.pornhub.com/video?o=cm")) itemlist.append( Item(channel=item.channel, action="categorias", title="Categorias", fanart=item.fanart, url = "http://es.pornhub.com/categories?o=al")) itemlist.append( Item(channel=item.channel, action="search", title="Buscar", fanart=item.fanart, url = "http://es.pornhub.com/video/search?search=%s&o=mr")) return itemlist def search(item,texto): logger.info("[pornhub.py] search") texto = texto.replace(" ", "+") item.url = item.url % texto try: return peliculas(item) # Se captura la excepción, para no interrumpir al buscador global si un canal falla except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) return [] def categorias(item): logger.info("[pornhub.py] categorias") itemlist = [] # Descarga la página data = scrapertools.downloadpage(item.url) data = scrapertools.find_single_match(data,'<div id="categoriesStraightImages">(.*?)</ul>') # Extrae las categorias patron = '<li class="cat_pic" data-category=".*?' patron += '<a href="([^"]+)".*?' patron += '<img src="([^"]+)".*?' patron += 'alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) for scrapedurl,scrapedthumbnail,scrapedtitle in matches: if "?" in scrapedurl: url = urlparse.urljoin(item.url,scrapedurl + "&o=cm" ) else: url = urlparse.urljoin(item.url,scrapedurl + "?o=cm") itemlist.append( Item(channel=item.channel, action="peliculas", title=scrapedtitle, url=url, fanart=item.fanart, thumbnail=scrapedthumbnail)) itemlist.sort(key=lambda x: x.title) return itemlist def peliculas(item): logger.info("[pornhub.py] peliculas") itemlist = [] # Descarga la página data = scrapertools.downloadpage(item.url) #videodata = scrapertools.find_single_match(data,'<ul class="nf-videos videos search-video-thumbs">(.*?)<div class="reset"></div>') videodata = scrapertools.find_single_match(data,'videos search-video-thumbs">(.*?)<div class="reset"></div>') # Extrae las peliculas patron = '<div class="phimage">.*?' patron += '<a href="([^"]+)" title="([^"]+).*?' patron += '<var class="duration">([^<]+)</var>(.*?)</div>.*?' patron += 'data-mediumthumb="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(videodata) for url,scrapedtitle,duration,scrapedhd,thumbnail in matches: title=scrapedtitle.replace("&amp;amp;", "&amp;") +" ("+duration+")" scrapedhd = scrapertools.find_single_match(scrapedhd,'<span class="hd-thumbnail">(.*?)</span>') if (scrapedhd == 'HD') : title += ' [HD]' url= urlparse.urljoin(item.url,url) itemlist.append( Item(channel=item.channel, action="play", title=title, url=url ,fanart=item.fanart, thumbnail=thumbnail, folder = False) ) if itemlist: # Paginador patron = '<li class="page_next"><a href="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if matches: url=urlparse.urljoin(item.url,matches[0].replace('&amp;','&')) itemlist.append(Item(channel=item.channel, action="peliculas", title=">> Página siguiente" ,fanart=item.fanart, url=url)) return itemlist def play(item): logger.info("[pornhub.py] play") itemlist=[] # Descarga la página data = scrapertools.downloadpage(item.url) patron = "var player_quality_([\d]+)p = '([^']+)'" matches = re.compile(patron,re.DOTALL).findall(data) for calidad, url in matches: itemlist.append( Item(channel=item.channel, action="play", title=calidad, fulltitle=item.title, url=url ,fanart=item.fanart, thumbnail=item.thumbnail, folder = False) ) itemlist.sort(key=lambda x: x.title, reverse= True) return itemlist
gpl-3.0
4FortyTwo2/sources
javascript/core/src/state/modules/credits.js
124
const credits = { state: { count: 0, info: '' }, actions: { }, mutations: { } };
gpl-3.0
kelsos/mra-net-sharp
mraSharp/Forms/UrlEditorWindow.Designer.cs
3640
namespace mraNet.Forms { partial class UrlEditorWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.urlBox = new System.Windows.Forms.TextBox(); this.saveButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // urlBox // this.urlBox.Location = new System.Drawing.Point(8, 6); this.urlBox.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.urlBox.Name = "urlBox"; this.urlBox.Size = new System.Drawing.Size(256, 20); this.urlBox.TabIndex = 0; // // saveButton // this.saveButton.Location = new System.Drawing.Point(8, 26); this.saveButton.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.saveButton.Name = "saveButton"; this.saveButton.Size = new System.Drawing.Size(75, 19); this.saveButton.TabIndex = 1; this.saveButton.Text = "Save\r\n"; this.saveButton.UseVisualStyleBackColor = true; this.saveButton.Click += new System.EventHandler(this.HandleSaveButtonClick); // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(88, 26); this.cancelButton.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 19); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.HandleCancelButtonClick); // // UrlEditorWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(270, 55); this.ControlBox = false; this.Controls.Add(this.cancelButton); this.Controls.Add(this.saveButton); this.Controls.Add(this.urlBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Name = "UrlEditorWindow"; this.Text = "Reader Url Editor"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox urlBox; private System.Windows.Forms.Button saveButton; private System.Windows.Forms.Button cancelButton; } }
gpl-3.0
Bombe/Sone
src/main/java/net/pterodactylus/sone/freenet/wot/OwnIdentity.java
1216
/* * Sone - OwnIdentity.java - Copyright © 2010–2020 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.freenet.wot; /** * Defines a local identity, an own identity. */ public interface OwnIdentity extends Identity { /** * Returns the insert URI of the identity. * * @return The insert URI of the identity */ public String getInsertUri(); public OwnIdentity addContext(String context); public OwnIdentity removeContext(String context); public OwnIdentity setProperty(String name, String value); public OwnIdentity removeProperty(String name); }
gpl-3.0
TecMunky/xDrip
app/src/main/java/com/eveningoutpost/dexdrip/Models/Sensor.java
10196
package com.eveningoutpost.dexdrip.Models; import android.provider.BaseColumns; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Select; import com.eveningoutpost.dexdrip.GcmActivity; import com.eveningoutpost.dexdrip.Home; import com.eveningoutpost.dexdrip.Models.UserError.Log; import com.eveningoutpost.dexdrip.UtilityModels.Constants; import com.eveningoutpost.dexdrip.UtilityModels.SensorSendQueue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.internal.bind.DateTypeAdapter; import org.json.JSONException; import org.json.JSONObject; import java.util.Date; import java.util.List; import java.util.UUID; /** * Created by Emma Black on 10/29/14. */ @Table(name = "Sensors", id = BaseColumns._ID) public class Sensor extends Model { private final static String TAG = Sensor.class.getSimpleName(); @Expose @Column(name = "started_at", index = true) public long started_at; @Expose @Column(name = "stopped_at") public long stopped_at; @Expose //latest minimal battery level @Column(name = "latest_battery_level") public int latest_battery_level; @Expose @Column(name = "uuid", index = true) public String uuid; @Expose @Column(name = "sensor_location") public String sensor_location; public static Sensor create(long started_at) { Sensor sensor = new Sensor(); sensor.started_at = started_at; sensor.uuid = UUID.randomUUID().toString(); sensor.save(); SensorSendQueue.addToQueue(sensor); Log.d("SENSOR MODEL:", sensor.toString()); return sensor; } public static Sensor create(long started_at, String uuid) {//KS Sensor sensor = new Sensor(); sensor.started_at = started_at; sensor.uuid = uuid; sensor.save(); SensorSendQueue.addToQueue(sensor); Log.d("SENSOR MODEL:", sensor.toString()); return sensor; } public static Sensor createDefaultIfMissing() { final Sensor sensor = currentSensor(); if (sensor == null) { Sensor.create(JoH.tsl()); } return currentSensor(); } // Used by xDripViewer public static void createUpdate(long started_at, long stopped_at, int latest_battery_level, String uuid) { Sensor sensor = getByTimestamp(started_at); if (sensor != null) { Log.d("SENSOR", "updatinga an existing sensor"); } else { Log.d("SENSOR", "creating a new sensor"); sensor = new Sensor(); } sensor.started_at = started_at; sensor.stopped_at = stopped_at; sensor.latest_battery_level = latest_battery_level; sensor.uuid = uuid; sensor.save(); } public synchronized static void stopSensor() { final Sensor sensor = currentSensor(); if (sensor == null) { return; } sensor.stopped_at = JoH.tsl(); UserError.Log.ueh("SENSOR", "Sensor stopped at " + JoH.dateTimeText(sensor.stopped_at)); sensor.save(); if (currentSensor() != null) { UserError.Log.wtf(TAG, "Failed to update sensor stop in database"); } SensorSendQueue.addToQueue(sensor); JoH.clearCache(); } public String toS() {//KS Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(Date.class, new DateTypeAdapter()) .serializeSpecialFloatingPointValues() .create(); Log.d("SENSOR", "Sensor toS uuid=" + this.uuid + " started_at=" + this.started_at + " active=" + this.isActive() + " battery=" + this.latest_battery_level + " location=" + this.sensor_location + " stopped_at=" + this.stopped_at); return gson.toJson(this); } public static Sensor lastStopped() { Sensor sensor = new Select() .from(Sensor.class) .where("started_at != 0") .where("stopped_at != 0") .orderBy("_ID desc") .limit(1) .executeSingle(); return sensor; } public static boolean stoppedRecently() { final Sensor last = lastStopped(); return last != null && last.stopped_at < JoH.tsl() && (JoH.msSince(last.stopped_at) < (Constants.HOUR_IN_MS * 2)); } public static Sensor currentSensor() { Sensor sensor = new Select() .from(Sensor.class) .where("started_at != 0") .where("stopped_at = 0") .orderBy("_ID desc") .limit(1) .executeSingle(); return sensor; } public static boolean isActive() { Sensor sensor = new Select() .from(Sensor.class) .where("started_at != 0") .where("stopped_at = 0") .orderBy("_ID desc") .limit(1) .executeSingle(); if(sensor == null) { return false; } else { return true; } } public static Sensor getByTimestamp(double started_at) { return new Select() .from(Sensor.class) .where("started_at = ?", started_at) .executeSingle(); } public static Sensor getByUuid(String xDrip_sensor_uuid) { if(xDrip_sensor_uuid == null) { Log.e("SENSOR", "xDrip_sensor_uuid is null"); return null; } Log.d("SENSOR", "xDrip_sensor_uuid is " + xDrip_sensor_uuid); return new Select() .from(Sensor.class) .where("uuid = ?", xDrip_sensor_uuid) .executeSingle(); } public static void updateBatteryLevel(int sensorBatteryLevel, boolean from_sync) { Sensor sensor = Sensor.currentSensor(); if (sensor == null) { Log.d("Sensor","Cant sync battery level from master as sensor data is null"); return; } updateBatteryLevel(sensor, sensorBatteryLevel, from_sync); } public static void updateBatteryLevel(Sensor sensor, int sensorBatteryLevel) { updateBatteryLevel(sensor, sensorBatteryLevel, false); } public static void updateBatteryLevel(Sensor sensor, int sensorBatteryLevel, boolean from_sync) { if (sensorBatteryLevel < 120) { // This must be a wrong battery level. Some transmitter send those every couple of readings // even if the battery is ok. return; } int startBatteryLevel = sensor.latest_battery_level; // if(sensor.latest_battery_level == 0) { // allow sensor battery level to go up and down sensor.latest_battery_level = sensorBatteryLevel; // } else { // sensor.latest_battery_level = Math.min(sensor.latest_battery_level, sensorBatteryLevel); // } if (startBatteryLevel == sensor.latest_battery_level) { // no need to update anything if nothing has changed. return; } sensor.save(); SensorSendQueue.addToQueue(sensor); if ((!from_sync) && (Home.get_master())) { GcmActivity.sendSensorBattery(sensor.latest_battery_level); } } public static void updateSensorLocation(String sensor_location) { Sensor sensor = currentSensor(); if (sensor == null) { Log.e("SENSOR MODEL:", "updateSensorLocation called but sensor is null"); return; } sensor.sensor_location = sensor_location; sensor.save(); } public static void upsertFromMaster(Sensor jsonSensor) { if (jsonSensor == null) { Log.wtf(TAG,"Got null sensor from json"); return; } try { Sensor existingSensor = getByUuid(jsonSensor.uuid); if (existingSensor == null) { Log.d(TAG, "saving new sensor record."); jsonSensor.save(); } else { Log.d(TAG, "updating existing sensor record."); existingSensor.started_at = jsonSensor.started_at; existingSensor.stopped_at = jsonSensor.stopped_at; existingSensor.latest_battery_level = jsonSensor.latest_battery_level; existingSensor.sensor_location = jsonSensor.sensor_location; existingSensor.save(); } } catch (Exception e) { Log.e(TAG, "Could not save Sensor: " + e.toString()); } } public String toJSON() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("started_at", started_at); jsonObject.put("stopped_at", stopped_at); jsonObject.put("latest_battery_level", latest_battery_level); jsonObject.put("uuid", uuid); jsonObject.put("sensor_location", sensor_location); return jsonObject.toString(); } catch (JSONException e) { Log.e(TAG,"Got JSONException handeling sensor", e); return ""; } } public static Sensor fromJSON(String json) { if (json.length()==0) { Log.d(TAG,"Empty json received in Sensor fromJson"); return null; } try { Log.d(TAG, "Processing incoming json: " + json); return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,Sensor.class); } catch (Exception e) { Log.d(TAG, "Got exception parsing Sensor json: " + e.toString()); Home.toaststaticnext("Error on Sensor sync."); return null; } } public static void shutdownAllSensors() { final List<Sensor> l = new Select().from(Sensor.class).execute(); for (final Sensor s : l) { s.stopped_at = s.started_at; s.save(); System.out.println(s.toJSON()); } } }
gpl-3.0
timebath/storybook
templates/single-thumbnail.php
2937
<?php /** * Template Name: Single Thumbnail Section * Description: Used as a page template to show page contents, followed by a loop through a CPT archive */ ?> <?php ///////////////////// # Post Thumbnail ///////////////////// # Grab the thumbnail src if(!isset($thumbnail_src)){ if( is_home() || is_front_page() ){ $thumbnail_src = get_theme_option('home_bg'); } elseif( is_author() ) { # Verify user $user_id = get_the_author_ID(); # Grab the profile image $thumbnail_src = get_user_meta($user_id, 'profile_image', true); } else { $id = get_the_ID(); $thumbnail_id = get_post_meta($id, '_thumbnail_id', true); if(empty($thumbnail_id)) $thumbnail_id = $id; $thumbnail = wp_get_attachment_image_src($thumbnail_id, $size = 'wallpaper', $icon = false); // $size = 'full'; $thumbnail_src = $thumbnail[0]; } } # Grab the author's avatar instead /* if(is_author()){ global $post; $user_info = get_userdata( $post->post_author ); $avatar = get_avatar($user_info->user_email, 1500); $thumbnail_src = preg_replace('/\<(.*?)src=("|\')(.*?)("|\')(.*?)\>/', '$3', $avatar); } */ # Set the thumnbnail width $width = (isset($width)) ? $width : '100%'; $width = (is_numeric($width)) ? $width.'px' : $width; # Set the thumnbnail height $height = (isset($height)) ? $height : 360; $height = (is_numeric($height)) ? $height.'px' : $height; # Set additional parameters $background_position = (isset($background_position)) ? $background_position : 'center center'; $opacity = (isset($opacity)) ? $opacity : '0.55'; # Set the parallax amount $parallax_amount = (isset($parallax_amount)) ? $parallax_amount : 0.35; $no_invert = (isset($no_invert)) ? '' : 'data-invert="1"'; # Grab the background color $background_color = get_theme_option('secondary_color'); $background_color = (empty($background_color)) ? '#333' : $background_color; ?> <?php // if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <?php if (!empty($thumbnail_src)) : ?> <?php // ob_start(); ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php // the_post_thumbnail('full'); // Declare pixel size you need inside the array ?> <div class="img post-thumbnail" style="background-image: url('<?php echo $thumbnail_src; ?>'); width: <?php echo $width; ?>; min-height: <?php echo $height; ?>; background-position: <?php echo $background_position; ?>; background-color: <?php echo $background_color; ?>; opacity: <?php echo $opacity; ?>;" data-parallax="1" data-amount="<?php echo $parallax_amount; ?>" <?php echo $no_invert; ?> data-blur="5" data-blur-alpha="rgba(0, 0, 0, 0.2)"></div> </a> <?php // echo apply_filters('the_content', ob_get_clean()); ?> <?php else: ?> <div style="position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; background-color: <?php echo $background_color; ?>;"></div> <?php endif; ?>
gpl-3.0
pinky39/grove
source/Grove/Core/AI/CombatRules/CombatRules.cs
1153
namespace Grove.AI.CombatRules { using System; using System.Collections.Generic; using Infrastructure; public class CombatRules : GameObject, ICopyContributor { private readonly CardBase _cardBase; private readonly Characteristic<List<CombatRule>> _rules; private CombatRules() {} public CombatRules(CardBase cardBase) { _cardBase = cardBase; _rules = new Characteristic<List<CombatRule>>(_cardBase.Value.CombatRules); } public void AfterMemberCopy(object original) { _cardBase.Changed += OnCardBaseChanged; } public CombatAbilities GetAbilities() { var abilities = new CombatAbilities(); foreach (var combatRule in _rules.Value) { combatRule.Apply(abilities); } return abilities; } public void Initialize(Card card, Game game) { Game = game; _rules.Initialize(game, card); _cardBase.Changed += OnCardBaseChanged; } private void OnCardBaseChanged() { _rules.ChangeBaseValue(_cardBase.Value.CombatRules); } } }
gpl-3.0
DISID/disid-proofs
spring-mvc-restful/src/main/java/com/disid/restful/repository/CustomerOrderRepository.java
1087
package com.disid.restful.repository; import com.disid.restful.model.Customer; import com.disid.restful.model.CustomerOrder; import com.disid.restful.model.OrderDetail; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository @Transactional(readOnly = true) public interface CustomerOrderRepository extends JpaRepository<CustomerOrder, Long>, CustomerOrderRepositoryCustom { /** * Retrieves a {@link CustomerOrder} by its id, with the related * {@link OrderDetail} data through a join. * * @param id must not be {@literal null}. * @return the CustomerOrder with the given id or {@literal null} if none found * @throws IllegalArgumentException if {@code id} is {@literal null} */ @Query("select c from CustomerOrder c left join fetch c.details left join fetch c.customer where c.id = ?1") CustomerOrder findOne(Long id); Long countByCustomer(Customer customer); }
gpl-3.0
GeographicaGS/Erosion
www/application/config/constants.php
3465
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | File and Directory Modes |-------------------------------------------------------------------------- | | These prefs are used when checking and setting modes when working | with the file system. The defaults are fine on servers with proper | security, but you may wish (or even need) to change the values in | certain environments (Apache running a separate process for each | user, PHP under CGI with Apache suEXEC, etc.). Octal values should | always be used to set the mode correctly. | */ define('FILE_READ_MODE', 0644); define('FILE_WRITE_MODE', 0666); define('DIR_READ_MODE', 0755); define('DIR_WRITE_MODE', 0777); /* |-------------------------------------------------------------------------- | File Stream Modes |-------------------------------------------------------------------------- | | These modes are used when working with fopen()/popen() | */ define('FOPEN_READ', 'rb'); define('FOPEN_READ_WRITE', 'r+b'); define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care define('FOPEN_WRITE_CREATE', 'ab'); define('FOPEN_READ_WRITE_CREATE', 'a+b'); define('FOPEN_WRITE_CREATE_STRICT', 'xb'); define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b'); /*Language */ define("LANGUAGE_ENGLISH","english"); define("LANGUAGE_SPANISH","spanish"); define("LANGUAGE_FRENCH","french"); /* End of file constants.php */ /* Location: ./application/config/constants.php */ /* Section constants */ define("SEC_GES",1); define("SEC_EXP",2); define("SEC_ADM",3); /* Incidents */ define("INC_O",1); define("INC_P",2); /* Logging */ define("LOGGED_STATUS_IN",1); /* Users */ define("GRP_GESTOR_USUARIOS",1); define("GRP_EDITOR_L1",2); define("GRP_EDITOR_L2",3); define("GRP_VIS",4); define("GRP_VIS_TAR",5); define("GRP_VIS_ECO",6); define("GRP_EDITOR_ECO",7); define("GRP_EDITOR_IYC",8); /* Menu */ define('MENU_GESTION',"gestion"); define('MENU_CRM',"crm"); define('MENU_ADMIN',"admin"); define("MENU_PERSONAL","personal"); define('MENU_GESTION_EJES_EST',1); define('MENU_GESTION_ACT_ACC',2); define('MENU_GESTION_INFORMES',3); define("MENU_ADMIN_USERS",300); define("MENU_PERSONAL_PERFIL",400); define("MENU_PERSONAL_TAREAS",401); /*Date format*/ define("PG_DATE_FORMAT","Y-m-d H:i:s"); define("PG_SHORT_DATE_FORMAT", 'd-m-Y'); define("PG_DATEMIN_FORMAT","Y-m-d"); define("DATE_FORMAT","d/m/Y"); define("TIME_FORMAT","H:i"); define("DATE_TIME_FORMAT","d/m/Y – H:i"); define("LINEAL_DATE_FORMAT","dmY"); define("LINEAL_DATE_FORMAT_ISO","YmdHis"); define("LINEAL_DATE_FORMAT_ISO_MIN","ymd"); /* ERRNO */ /* Bad paramenters */ define("ERRNO_BADPAR", -1 ); /* FORM ACTIONS */ define('FORM_ACTION_NEW',1); define('FORM_ACTION_EDIT',2); /* Character limiter*/ define("CL_G3",20); define("CL_G6",35); define("CL_G7",37); define("CL_G8",40); define("CL_G10",45); define("CL_G10U",30); define("CL_G12",70); define("CL_G12B",60); /* Pagination block sizes */ define("DEF_BKSIZE",16); define("MAX_ALL_ELEMENTS",1000000); define("N_DECIMALS",2); define("ST_ENABLE",1); define("ST_DISABLE",2); define("PAG_ACT","n_list_acts"); define("TAREA_IMP_BAJA",3); define("TAREA_IMP_MEDIA",2); define("TAREA_IMP_ALTA",1); define("LIMIT_AUTOCOMPLETE",10);
gpl-3.0
arielk/elementor
core/app/assets/js/ui/molecules/inline-link.js
1825
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ baseClassName, colorClassName, underlineClassName, italicClassName, props.className, ], className = arrayToClassName( classes ), getRouterLink = () => ( <LocationProvider history={ router.appHistory }> <Link to={ props.url } className={ className } > { props.children } </Link> </LocationProvider> ), getExternalLink = () => ( <a href={ props.url } target={ props.target } rel={ props.rel } className={ className } > { props.children } </a> ), getActionLink = () => ( <button className={ className } onClick={ props.onClick }> { props.children } </button> ); if ( ! props.url ) { return getActionLink(); } return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink(); } InlineLink.propTypes = { className: PropTypes.string, children: PropTypes.string, url: PropTypes.string, target: PropTypes.string, rel: PropTypes.string, text: PropTypes.string, color: PropTypes.oneOf( [ 'primary', 'secondary', 'cta', 'link', 'disabled' ] ), underline: PropTypes.oneOf( [ 'none', 'hover', 'always' ] ), italic: PropTypes.bool, }; InlineLink.defaultProps = { className: '', color: 'link', underline: 'always', target: '_blank', rel: 'noopener noreferrer', };
gpl-3.0
edwardwkrohne/satcolors
test/gridtest.cpp
3020
// -*- Mode: C++ -*- //////////////////////////////////////////////////////////////////////////// // // satcolors -- for writably and readably building problems for SAT-solving // Copyright (C) 2014 Edward W. Krohne III // // The research that led to this product was partially supported by the // U.S. NSF grants DMS-0943870 and DMS-1201290. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////// #include <string> #include <sstream> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <stdexcept> #include "mocksolver.h" #include "testglue.h" #include "../src/grid.h" using namespace std; class GridTest : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE(GridTest); CPPUNIT_TEST(testConstruction2d); CPPUNIT_TEST(testConstructionFailure); CPPUNIT_TEST_SUITE_END(); protected: void testConstruction2d(void); void testConstructionFailure(void); }; CPPUNIT_TEST_SUITE_REGISTRATION( GridTest ); namespace { function<Cardinal(int, int)> getBuilder(Solver* solver) { auto builder2d = [=](int row, int col) { return Cardinal(solver, row, row+2*col+1); }; return builder2d; } } // namespace void GridTest::testConstruction2d(void) { MockSolver solver; auto builder2d = getBuilder(&solver); auto list = makeList(3, 4, builder2d); // Just hit it with a battery of checks. CPPUNIT_ASSERT_EQUAL(3u, list.height()); CPPUNIT_ASSERT_EQUAL(4u, list.width()); CPPUNIT_ASSERT_EQUAL(0, list[0][0].min()); CPPUNIT_ASSERT_EQUAL(1, list[0][0].max()); CPPUNIT_ASSERT_EQUAL(2, list[2][0].min()); CPPUNIT_ASSERT_EQUAL(3, list[2][0].max()); CPPUNIT_ASSERT_EQUAL(1, list[1][3].min()); CPPUNIT_ASSERT_EQUAL(8, list[1][3].max()); CPPUNIT_ASSERT_EQUAL(list.data().numLiterals(), list.numLiterals()); CPPUNIT_ASSERT_THROW(list[-1], out_of_range); CPPUNIT_ASSERT_THROW(list[3], out_of_range); CPPUNIT_ASSERT_THROW(list[1][-1], out_of_range); CPPUNIT_ASSERT_THROW(list[1][4], out_of_range); } void GridTest::testConstructionFailure(void) { MockSolver solver; auto builder2d = getBuilder(&solver); CPPUNIT_ASSERT_THROW(auto list = makeList(4, -1, builder2d), invalid_argument); CPPUNIT_ASSERT_THROW(auto list = makeList(-1, 4, builder2d), invalid_argument); CPPUNIT_ASSERT_THROW(auto list = makeList(-1, -1, builder2d), invalid_argument); }
gpl-3.0
viridian1138/SimpleAlgebra_V2
src/simplealgebra/symbolic/SymbolicElem.java
11377
//$$strtCprt /** * Simple Algebra * * Copyright (C) 2014 Thornton Green * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, * see <http://www.gnu.org/licenses>. * Additional permission under GNU GPL version 3 section 7 * */ //$$endCprt package simplealgebra.symbolic; import java.io.PrintStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import simplealgebra.Elem; import simplealgebra.ElemFactory; import simplealgebra.NotInvertibleException; import simplealgebra.PrimitiveRandom; /** * A symbolic elem. * * This documentation should be viewed using Firefox version 33.1.1 or above. * * @author thorngreen * * @param <R> The enclosed type. * @param <S> The factory for the enclosed type. */ public abstract class SymbolicElem<R extends Elem<R,?>, S extends ElemFactory<R,S>> extends Elem<SymbolicElem<R,S>, SymbolicElemFactory<R,S>> { /** * Evaluates the symbolic expression. * * @param implicitSpace The implicit space over which to evaluate the expression. * @return The result of the evaluation. * @throws NotInvertibleException * @throws MultiplicativeDistributionRequiredException */ abstract public R eval( HashMap<? extends Elem<?,?>,? extends Elem<?,?>> implicitSpace ) throws NotInvertibleException, MultiplicativeDistributionRequiredException; /** * Evaluates the symbolic expression. * * @param implicitSpace The implicit space over which to evaluate the expression. * @param cache The evaluation cache. * @return The result of the evaluation. * @throws NotInvertibleException * @throws MultiplicativeDistributionRequiredException */ abstract public R evalCached( HashMap<? extends Elem<?,?>,? extends Elem<?,?>> implicitSpace, HashMap<SCacheKey<R,S>,R> cache ) throws NotInvertibleException, MultiplicativeDistributionRequiredException; /** * Evaluates the partial derivative of the symbolic expression. * * @param withRespectTo The variable over which to evaluate the derivative. * @param implicitSpace The implicit space over which to evaluate the expression. * @return The result of the evaluation. * @throws NotInvertibleException * @throws MultiplicativeDistributionRequiredException */ abstract public R evalPartialDerivative( ArrayList<? extends Elem<?,?>> withRespectTo , HashMap<? extends Elem<?,?>,? extends Elem<?,?>> implicitSpace ) throws NotInvertibleException, MultiplicativeDistributionRequiredException; /** * Evaluates the partial derivative of the symbolic expression. * * @param withRespectTo The variable over which to evaluate the derivative. * @param implicitSpace The implicit space over which to evaluate the expression. * @param cache The evaluation cache. * @return The result of the evaluation. * @throws NotInvertibleException * @throws MultiplicativeDistributionRequiredException */ abstract public R evalPartialDerivativeCached( ArrayList<? extends Elem<?,?>> withRespectTo , HashMap<? extends Elem<?,?>,? extends Elem<?,?>> implicitSpace , HashMap<SCacheKey<R,S>,R> cache ) throws NotInvertibleException, MultiplicativeDistributionRequiredException; /** * Constructs the elem. * * @param _fac The factory for the enclosed type. */ public SymbolicElem( S _fac ) { fac = _fac; } @Override public SymbolicElem<R, S> add(SymbolicElem<R, S> b) { // This simplification has a parallel implementation in the "Add Zero B" rules in // distributeSimplify.drl and distributeSimplify2.drl return( b.isSymbolicZero() ? this : new SymbolicAdd<R,S>( this , b , fac ) ); } @Override public SymbolicElem<R, S> mult(SymbolicElem<R, S> b) { // This simplification has a parallel implementation in the "MultRightMutatorType Zero B" rules in // distributeSimplify.drl and distributeSimplify2.drl return( b.isSymbolicZero() ? b : new SymbolicMult<R,S>( this , b , fac ) ); } @Override public SymbolicElem<R, S> negate() { return( new SymbolicNegate<R,S>( this , fac ) ); } @Override public SymbolicElem<R, S> invertLeft() throws NotInvertibleException { return( new SymbolicInvertLeft<R,S>( this , fac ) ); } @Override public SymbolicElem<R, S> invertRight() throws NotInvertibleException { return( new SymbolicInvertRight<R,S>( this , fac ) ); } @Override public SymbolicElem<R, S> divideBy(BigInteger val) { return( new SymbolicDivideBy<R,S>( this , fac , val ) ); } @Override public SymbolicElem<R, S> exp( int numIter ) { return( new SymbolicExponential<R,S>( this , fac , numIter ) ); } @Override public SymbolicElem<R, S> sin( int numIter ) { return( new SymbolicSine<R,S>( this , fac , numIter ) ); } @Override public SymbolicElem<R, S> cos( int numIter ) { return( new SymbolicCosine<R,S>( this , fac , numIter ) ); } @Override public SymbolicElem<R, S> random( PrimitiveRandom in ) { return( new SymbolicRandom<R,S>( this , fac , in ) ); } @Override public Elem<?,?> totalMagnitude() { throw( new RuntimeException( "Not Supported" ) ); } /** * Expands the exponential function <math display="inline"> * <mrow> * <msup> * <mo>e</mo> * <mi>x</mi> * </msup> * </mrow> * </math> * * @param numIter The number of iterations to use in the calculation. * @return The exponent of the elem. */ public SymbolicElem<R,S> expandExp( int numIter ) { return( super.exp(numIter) ); } /** * Expands the sine function in units of radians. * * @param numIter The number of iterations to use in the calculation. * @return The sine of the argument. */ public SymbolicElem<R,S> expandSin( int numIter ) { return( super.sin(numIter) ); } /** * Expands the cosine function in units of radians. * * @param numIter The number of iterations to use in the calculation. * @return The cosine of the argument. */ public SymbolicElem<R,S> expandCos( int numIter ) { return( super.cos(numIter) ); } /** * Inserts the elem into a Drools ( <A href="http://drools.org">http://drools.org</A> ) session. * @param ds The session. * @return This elem. */ public SymbolicElem<R,S> insSym( DroolsSession ds ) { ds.insert( this ); return( this ); } @Override public SymbolicElemFactory<R, S> getFac() { return( new SymbolicElemFactory<R,S>( fac ) ); } /** * Returns true iff. the elem is a symbolic zero. * * @return True iff. the elem is a symbolic zero. */ public boolean isSymbolicZero() { return( false ); } /** * Returns true iff. the elem is a symbolic identity. * * @return True iff. the elem is a symbolic identity. */ public boolean isSymbolicIdentity() { return( false ); } /** * Returns true if the elem exposes derivatives to elems by which it is multiplied. * * @return True if the elem exposes derivatives to elems by which it is multiplied. */ public boolean exposesDerivatives() { return( false ); } /** * Returns whether the partial derivative of the elem is zero. * * @return True if the partial derivative of the elem is zero. */ public boolean isPartialDerivativeZero() { return( false ); } @Override public SymbolicElem<R, S> handleOptionalOp( Object id , ArrayList<SymbolicElem<R, S>> args ) throws NotInvertibleException { final ArrayList<SymbolicElem<R, S>> args2 = new ArrayList<SymbolicElem<R, S>>(); args2.add( this ); if( args != null ) { for( final SymbolicElem<R, S> ii : args ) { args2.add( ii ); } } return( getFac().getFac().handleSymbolicOptionalOp(id, args2) ); } /** * Mode determining the extent to which the elem will be reduced to determine if it is a constant. * * @author thorngreen * */ public static enum EVAL_MODE{ APPROX , SIMPLIFY , SIMPLIFY2 }; /** * Returns approximately whether the elem can be determined to be a symbolic constant. * * @param mode Mode determining the extent to which the elem will be reduced to determine if it is a constant. * @return True if the elem can be determined to be a symbolic constant. * @throws NotInvertibleException */ public boolean evalSymbolicConstant( EVAL_MODE mode ) { switch( mode ) { case APPROX: { return( evalSymbolicConstantApprox() ); } case SIMPLIFY: { //try { return( distributeSimplify().evalSymbolicConstantApprox() ); } //catch( NotInvertibleException ex ) //{ // return( false ); //} } case SIMPLIFY2: { // try { return( this.distributeSimplify2().evalSymbolicConstantApprox() ); } // catch( NotInvertibleException ex ) //{ // return( false ); //} } } throw( new RuntimeException( "Not Supported" ) ); } @Override public boolean evalSymbolicZeroApprox( EVAL_MODE mode ) { switch( mode ) { case APPROX: { return( isSymbolicZero() ); } case SIMPLIFY: { return( distributeSimplify().isSymbolicZero() ); } case SIMPLIFY2: { return( this.distributeSimplify2().isSymbolicZero() ); } } throw( new RuntimeException( "Not Supported" ) ); } @Override public boolean evalSymbolicIdentityApprox( EVAL_MODE mode ) { switch( mode ) { case APPROX: { return( isSymbolicIdentity() ); } case SIMPLIFY: { return( distributeSimplify().isSymbolicIdentity() ); } case SIMPLIFY2: { return( this.distributeSimplify2().isSymbolicIdentity() ); } } throw( new RuntimeException( "Not Supported" ) ); } /** * Returns approximately whether the elem can be determined to be a symbolic constant. * * @return True if the elem can be determined to be a symbolic constant. */ public boolean evalSymbolicConstantApprox() { return( false ); } /** * Returns whether this expression is equal to the one in the parameter, simplifying both sides first. * * @param b The expression to be compared. * @return True if the expressions are found to be equal, false otherwise. */ public boolean extSymbolicEquals( SymbolicElem<R, S> b ) throws NotInvertibleException { SymbolicElem<R, S> aa = this.distributeSimplify(); SymbolicElem<R, S> bb = b.distributeSimplify(); boolean ret = aa.symbolicEquals( bb ); if( ret ) { // System.out.println( "AAAAA" ); } return( ret ); } /** * Returns whether this expression is equal to the one in the parameter. * * @param b The expression to be compared. * @return True if the expressions are found to be equal, false otherwise. */ public boolean symbolicEquals( SymbolicElem<R, S> b ) { throw( new RuntimeException( "Not Supported " + this ) ); } /** * The factory for the enclosed type. */ protected S fac; }
gpl-3.0
CARTAvis/carta
carta/cpp/core/Shape/ShapePolygon.cpp
4454
#include "ShapePolygon.h" #include "ControlPointEditable.h" #include "CartaLib/VectorGraphics/VGList.h" #include "CartaLib/Regions/IRegion.h" namespace Carta { namespace Shape { ShapePolygon::ShapePolygon( ): m_polygonRegion( new Carta::Lib::Regions::Polygon() ){ } void ShapePolygon::_controlPointCB( int index, bool final ){ auto & poly = m_shadowPolygon; if ( index >= 0 && index < poly.size() ) { poly[index] = m_controlPoints[index]-> getCenter(); } if ( final ) { m_polygonRegion->setqpolyf( m_shadowPolygon ); } } void ShapePolygon::_editShadow( const QPointF& pt ){ _moveShadow( pt ); _syncShadowToCPs(); } QPointF ShapePolygon::getCenter() const { QRectF box = m_polygonRegion->outlineBox(); return box.center(); } QSizeF ShapePolygon::getSize() const { return m_polygonRegion->outlineBox().size(); } Carta::Lib::VectorGraphics::VGList ShapePolygon::getVGList() const { Carta::Lib::VectorGraphics::VGComposer comp; QPen pen = shadowPen; pen.setCosmetic(true); pen.setColor(m_color); QPen rectPen = outlinePen; rectPen.setCosmetic(true); QBrush brush = Qt::NoBrush; //Draw the basic polygon comp.append < vge::SetPen > ( pen ); comp.append < vge::SetBrush > ( brush ); comp.append < vge::DrawPolygon > ( m_shadowPolygon ); //If there is only one point, in the polygon, it will not draw so //we draw a square for the point. if ( m_shadowPolygon.size() == 1 ){ ControlPointEditable cpe( nullptr ); cpe.setPosition( m_shadowPolygon.value( 0 ) ); Carta::Lib::VectorGraphics::VGList pointVGList = cpe.getVGList(); comp.appendList( pointVGList ); } //Only draw the rest if we are not creating the region. if ( !isEditMode() ){ //Draw the outline box; use a different style if it is selected. if ( isSelected() ){ comp.append < vge::SetPen > ( rectPen ); QRectF shadowRect = m_shadowPolygon.boundingRect(); comp.append < vge::DrawRect > ( shadowRect ); comp.append < vge::SetPen > ( pen ); } //Draw the control points if ( isSelected()){ int cornerCount = m_controlPoints.size(); for ( int i = 0; i < cornerCount; i++ ){ comp.appendList( m_controlPoints[i]->getVGList() ); } } } return comp.vgList(); } void ShapePolygon::handleDragDone( const QPointF & pt ){ int controlPointCount = m_controlPoints.size(); if ( m_dragControlIndex >= 0 && m_dragControlIndex < controlPointCount ){ m_controlPoints[m_dragControlIndex]->handleDragDone( pt ); m_dragControlIndex = -1; } else { _moveShadow( pt ); _syncShadowToCPs(); // exit drag mode m_dragMode = false; // update the region m_polygonRegion-> setqpolyf( m_shadowPolygon ); } emit shapeChanged( m_polygonRegion->toJson() ); } bool ShapePolygon::isClosed() const { QPolygonF poly = m_polygonRegion->qpolyf(); return poly.isClosed(); } bool ShapePolygon::isCorner( const QPointF& pt ) const { return m_shadowPolygon.contains( pt ); } bool ShapePolygon::isPointInside( const QPointF & pt ) const { bool pointInside = m_polygonRegion-> isPointInside( {pt} ); int cornerCount = m_controlPoints.size(); bool onControlPoint = false; for ( int i = 0; i < cornerCount; i++ ){ onControlPoint = m_controlPoints[i]->isPointInside( {pt} ); if (onControlPoint){ break; } } return (pointInside|onControlPoint); } void ShapePolygon::_moveShadow( const QPointF& pt ){ // calculate offset to move the shadow polygon to match the un-edited shape QPointF offset = m_polygonRegion->qpolyf().at( 0 ) - m_shadowPolygon.at( 0 ); // now move it by the amount of drag offset += pt - m_dragStart; // apply the offset to the shadow m_shadowPolygon.translate( offset ); } void ShapePolygon::setModel( const QJsonObject& json ){ m_polygonRegion->initFromJson( json ); m_shadowPolygon = m_polygonRegion->qpolyf(); _syncShadowToCPs(); } void ShapePolygon::_syncShadowToCPs(){ // make missing control points if necessary while ( int ( m_controlPoints.size() ) < m_shadowPolygon.size() ) { int index = m_controlPoints.size(); auto cb = [this, index] ( bool final ) { _controlPointCB( index, final ); }; auto cp = std::make_shared < ControlPointEditable > ( cb ); cp-> setActive( false ); m_controlPoints.push_back( cp ); } CARTA_ASSERT( m_shadowPolygon.size() == int ( m_controlPoints.size() ) ); for ( int index = 0 ; index < m_shadowPolygon.size() ; index++ ) { m_controlPoints[index]->setPosition( m_shadowPolygon[index] ); } } } }
gpl-3.0
hlin09/renjin
tools/gcc-bridge/src/main/java/org/renjin/gcc/gimple/type/GimpleFunctionType.java
922
package org.renjin.gcc.gimple.type; import java.util.List; import com.google.common.collect.Lists; import org.renjin.gcc.translate.type.ImPrimitiveType; public class GimpleFunctionType extends AbstractGimpleType { private GimpleType returnType; private int size; private List<GimpleType> argumentTypes = Lists.newArrayList(); private boolean variableArguments; public int getSize() { return size; } public void setSize(int size) { this.size = size; } public GimpleType getReturnType() { return returnType; } public void setReturnType(GimpleType returnType) { this.returnType = returnType; } public List<GimpleType> getArgumentTypes() { return argumentTypes; } public boolean isVariableArguments() { return variableArguments; } public void setVariableArguments(boolean variableArguments) { this.variableArguments = variableArguments; } }
gpl-3.0
CIFASIS/qss-solver
src/mmoc/util/compile_flags.cpp
4259
/***************************************************************************** This file is part of QSS Solver. QSS Solver is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QSS Solver is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QSS Solver. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "compile_flags.h" #include <utility> #include "util.h" namespace MicroModelica { namespace Util { CompileFlags::CompileFlags() : _store(true), _parallel(false), _externalStructureFiles(false), _output(true), _debug(0), _outputFile(), _path(), _libraryPaths(), _objects(), _optimizeQSS(false), _incidenceMatrices(false), _externalFunctions(false), _lps(0), _debugOptions(), _graph(false) { _debugOptions["SD_DBG_VarChanges"] = 1 << 0; _debugOptions["SD_DBG_InitValues"] = 1 << 1; _debugOptions["SD_DBG_StepInfo"] = 1 << 2; _debugOptions["SD_DBG_Weights"] = 1 << 3; _debugOptions["SD_DBG_Memory"] = 1 << 4; _debugOptions["SD_DBG_ExternalEvent"] = 1 << 5; _debugOptions["SD_DBG_Synchronize"] = 1 << 6; _debugOptions["SD_DBG_WaitFor"] = 1 << 7; _debugOptions["SD_DBG_Dt"] = 1 << 8; } bool CompileFlags::store() { return _store; } void CompileFlags::setStore(bool s) { _store = s; } void CompileFlags::setIncidenceMatrices(bool im) { _incidenceMatrices = im; } void CompileFlags::setOptimizeQSS(bool s) { _optimizeQSS = s; } bool CompileFlags::incidenceMatrices() { return _incidenceMatrices; } bool CompileFlags::parallel() { return _parallel; } void CompileFlags::setParallel(bool s) { _parallel = s; setGraph(true); } bool CompileFlags::output() { return _output; } void CompileFlags::setOutput(bool s) { _output = s; } bool CompileFlags::externalFunctions() { return _externalFunctions; } void CompileFlags::setExternalFunctions(bool s) { _externalFunctions = s; } int CompileFlags::debug() { return _debug; } void CompileFlags::setDebug(int s) { _debug |= s; } void CompileFlags::setOutputFile(string outputFile) { _outputFile = outputFile; } string CompileFlags::outputFileName() { return Utils::instance().getFileName(_outputFile); } string CompileFlags::outputFilePath() { return Utils::instance().getFilePath(_outputFile); } string CompileFlags::outputFile() { return _outputFile; } bool CompileFlags::hasOutputFile() { return !_outputFile.empty(); } void CompileFlags::setPath(string p) { _path = p; } string CompileFlags::path() { return _path; } list<string> CompileFlags::libraryPaths() { return _libraryPaths; } void CompileFlags::addLibraryPath(string l) { _libraryPaths.push_back(l); } void CompileFlags::addObject(string o) { _objects.insert(pair<string, string>(o, o)); } list<string> CompileFlags::objects() { list<string> ret; for (map<string, string>::iterator it = _objects.begin(); it != _objects.end(); it++) { ret.push_back(it->second); } return ret; } bool CompileFlags::optimizeQSS() { return _optimizeQSS; } bool CompileFlags::hasObjects() { return !_objects.empty(); } bool CompileFlags::externalStructureFile() { return _externalStructureFiles; } void CompileFlags::setExternalStructureFile(bool s) { _externalStructureFiles = s; } void CompileFlags::setDebug(string s) { if (_debugOptions.find(s) != _debugOptions.end()) { _debug |= _debugOptions[s]; if (!s.compare("SD_DBG_Weights")) { setGraph(true); _debug |= _debugOptions["SD_DBG_VarChanges"]; } } } void CompileFlags::setGraph(bool g) { _graph = g; } bool CompileFlags::graph() { return _graph; } void CompileFlags::setTesting(bool testing) { _testing = testing; } bool CompileFlags::testing() { return _testing; } } // namespace Util } // namespace MicroModelica
gpl-3.0
do-android/do_Album
doExt_do_Album/src/doext/implement/ConstantValue.java
129
package doext.implement; public class ConstantValue { public static int MAX_COUNT = 0; public static boolean ISCUT = false; }
gpl-3.0
lligen/rgbdslam_v2_2kinect
src/graph_mgr_io.cpp
49821
/* This file is part of RGBDSLAM. * * RGBDSLAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RGBDSLAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RGBDSLAM. If not, see <http://www.gnu.org/licenses/>. */ /** This file contains the methods of GraphManager concerned with transfering * data via ROS, to the screen (visualization) or to disk. They are declared in graph_manager.h */ #include <sys/time.h> #include "scoped_timer.h" #include "graph_manager.h" #include "misc.h" #include "pcl_ros/transforms.h" #include "pcl/io/pcd_io.h" //#include <sensor_msgs/PointCloud2.h> #include <opencv2/features2d/features2d.hpp> #include <qtconcurrentrun.h> #include <QFile> #include <utility> #include <fstream> #include <boost/foreach.hpp> #include <rosbag/bag.h> #include "g2o/types/slam3d/se3quat.h" //#include "g2o/types/slam3d/edge_se3_quat.h" #include "g2o/types/slam3d/edge_se3.h" #include "g2o/core/optimizable_graph.h" #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> // If QT Concurrent is available, run the saving in a seperate thread void GraphManager::sendAllClouds(bool threaded){ if (ParameterServer::instance()->get<bool>("concurrent_io") && threaded) { QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::sendAllCloudsImpl); //f1.waitForFinished(); } else {// Otherwise just call it without threading sendAllCloudsImpl(); } } tf::StampedTransform GraphManager::computeFixedToBaseTransform(Node* node, bool invert) { g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); if(!v){ ROS_FATAL("Nullpointer in graph at position %i!", node->vertex_id_); throw std::exception(); } tf::Transform computed_motion = eigenTransf2TF(v->estimate());//get pose of point cloud w.r.t. first frame's pc tf::Transform base2points = node->getBase2PointsTransform();//get pose of base w.r.t current pc at capture time // printTransform("base2points", base2points); // printTransform("computed_motion", computed_motion); // printTransform("init_base_pose_", init_base_pose_); tf::Transform world2base = init_base_pose_*base2points*computed_motion*base2points.inverse(); tf::Transform gt_world2base = node->getGroundTruthTransform();//get mocap pose of base in map tf::Transform err = gt_world2base.inverseTimes(world2base); //makes sure things have a corresponding timestamp //also avoids problems with tflistener cache size if mapping took long. Must be synchronized with tf broadcasting ros::Time now = ros::Time::now(); // printTransform("World->Base", world2base); std::string fixed_frame = ParameterServer::instance()->get<std::string>("fixed_frame_name"); std::string base_frame = ParameterServer::instance()->get<std::string>("base_frame_name"); if(base_frame.empty()) { //if there is no base frame defined, use frame of sensor data base_frame = graph_.begin()->second->header_.frame_id; } if(invert){ return tf::StampedTransform(world2base.inverse(), now, base_frame, fixed_frame); } else { return tf::StampedTransform(world2base, now, fixed_frame, base_frame); } } // If QT Concurrent is available, run the saving in a seperate thread void GraphManager::saveBagfileAsync(QString filename){ if (ParameterServer::instance()->get<bool>("concurrent_io")) { QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::saveBagfile, filename); //f1.waitForFinished(); } else {// Otherwise just call it without threading saveBagfile(filename); } } void GraphManager::saveBagfile(QString filename) { ScopedTimer s(__FUNCTION__); if(filename.isEmpty()){ ROS_ERROR("Filename empty. Cannot save to bagfile."); return; } Q_EMIT iamBusy(0, "Saving Bagfile", graph_.size()); rosbag::Bag bag; bag.open(qPrintable(filename), rosbag::bagmode::Write); if(ParameterServer::instance()->get<bool>("compress_output_bagfile")) { bag.setCompression(rosbag::compression::BZ2); } geometry_msgs::TransformStamped geom_msg; for (graph_it it = graph_.begin(); it != graph_.end(); ++it) { Node* node = it->second; if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); continue; } tf::tfMessage tfmsg; tf::StampedTransform base_to_fixed = this->computeFixedToBaseTransform(node, true); base_to_fixed.stamp_ = node->header_.stamp; tf::transformStampedTFToMsg(base_to_fixed, geom_msg); tfmsg.transforms.push_back(geom_msg); tf::StampedTransform base_to_points = node->getBase2PointsTransform(); base_to_points.stamp_ = node->header_.stamp; tf::transformStampedTFToMsg(base_to_points, geom_msg); tfmsg.transforms.push_back(geom_msg); //tfmsg.set_transforms_size(2); bag.write("/tf", node->header_.stamp, tfmsg); bag.write("/rgbdslam/batch_clouds", node->header_.stamp, node->pc_col); Q_EMIT progress(0, "Saving Bagfile", it->first+1); QString message; Q_EMIT setGUIInfo(message.sprintf("Writing pointcloud and map transform (%i/%i) to bagfile %s", it->first, (int)graph_.size(), qPrintable(filename))); } Q_EMIT progress(0, "Finished Saving Bagfile", 1e6); bag.close(); } void GraphManager::sendAllCloudsImpl() { ScopedTimer s(__FUNCTION__); if (batch_cloud_pub_.getNumSubscribers() == 0){ ROS_WARN("No Subscribers: Sending of clouds cancelled"); return; } ROS_INFO("Sending out all clouds"); batch_processing_runs_ = true; ros::Rate r(ParameterServer::instance()->get<double>("send_clouds_rate")); //slow down a bit, to allow for transmitting to and processing in other nodes double delay_seconds = ParameterServer::instance()->get<double>("send_clouds_delay"); for (graph_it it = graph_.begin(); it != graph_.end(); ++it) { Node* node = it->second; if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); continue; } while(node->header_.stamp.toSec() > (ros::Time::now().toSec() - delay_seconds)){ ROS_INFO("Waiting for node becoming %f seconds old", delay_seconds); r.sleep(); } tf::StampedTransform base_to_fixed = this->computeFixedToBaseTransform(node, true); br_.sendTransform(base_to_fixed); publishCloud(node, base_to_fixed.stamp_, batch_cloud_pub_); QString message; Q_EMIT setGUIInfo(message.sprintf("Sending pointcloud and map transform (%i/%i) on topics %s and /tf", it->first, (int)graph_.size(), ParameterServer::instance()->get<std::string>("individual_cloud_out_topic").c_str()) ); r.sleep(); } batch_processing_runs_ = false; Q_EMIT sendFinished(); } // If QT Concurrent is available, run the saving in a seperate thread void GraphManager::saveAllClouds(QString filename, bool threaded){ if (ParameterServer::instance()->get<bool>("concurrent_io") && threaded) { QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::saveAllCloudsToFile, filename); //f1.waitForFinished(); } else {// Otherwise just call it without threading saveAllCloudsToFile(filename); } } void GraphManager::saveIndividualClouds(QString filename, bool threaded){ if (ParameterServer::instance()->get<bool>("concurrent_io") && threaded) { QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::saveIndividualCloudsToFile, filename); //f1.waitForFinished(); } else { saveIndividualCloudsToFile(filename); } } void GraphManager::save_A_Clouds(QString filename, bool threaded){ if (ParameterServer::instance()->get<bool>("concurrent_io") && threaded) { QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::save_A_CloudsToFile, filename); //f1.waitForFinished(); } else { save_A_CloudsToFile(filename); } } ///Write current pose estimate to pcl cloud header ///Returns false if node has no valid estimate or is empty bool GraphManager::updateCloudOrigin(Node* node) { if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); return false; } g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); if(!v){ ROS_ERROR("Nullpointer in graph at position %i!", node->id_); return false; } if(node->pc_col->size() == 0){ ROS_INFO("Skipping Node %i, point cloud data is empty!", node->id_); return false; } // Update the sensor pose stored in the point clouds node->pc_col->sensor_origin_.head<3>() = v->estimate().translation().cast<float>(); node->pc_col->sensor_orientation_ = v->estimate().rotation().cast<float>(); //node->header_.frame_id = ParameterServer::instance()->get<std::string>("fixed_frame_name"); } void GraphManager::saveOctomap(QString filename, bool threaded){ if (ParameterServer::instance()->get<bool>("octomap_online_creation")) { this->writeOctomap(filename); } else{ //if not online creation, create now if (ParameterServer::instance()->get<bool>("concurrent_io") && threaded) { //saveOctomapImpl(filename); QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::saveOctomapImpl, filename); //f1.waitForFinished(); } else { saveOctomapImpl(filename); } } } void GraphManager::saveOctomapImpl(QString filename) { ScopedTimer s(__FUNCTION__); batch_processing_runs_ = true; Q_EMIT iamBusy(1, "Saving Octomap", 0); std::list<Node*> nodes_for_octomapping; unsigned int points_to_render = 0; { //Get the transformations from the optimizer and store them in the node's point cloud header QMutexLocker locker(&optimizer_mutex_); for (graph_it it = graph_.begin(); it != graph_.end(); ++it){ Node* node = it->second; if(this->updateCloudOrigin(node)){ nodes_for_octomapping.push_back(node); points_to_render += node->pc_col->size(); } } } // Now (this takes long) render the clouds into the octomap int counter = 0; co_server_.reset(); Q_EMIT iamBusy(1, "Saving Octomap", nodes_for_octomapping.size()); unsigned int rendered_points = 0; double delay_seconds = ParameterServer::instance()->get<double>("save_octomap_delay"); BOOST_FOREACH(Node* node, nodes_for_octomapping) { /* double data_stamp = node->pc_col->header.stamp.toSec(); while(data_stamp > ros::Time::now().toSec() - delay_seconds){ ROS_INFO("Waiting for node becoming %f seconds old before rendering to octomap", delay_seconds); ros::Duration((ros::Time::now().toSec() - delay_seconds) - data_stamp).sleep(); } */ QString message; Q_EMIT setGUIStatus(message.sprintf("Inserting Node %i/%i into octomap", ++counter, (int)nodes_for_octomapping.size())); this->renderToOctomap(node); rendered_points += node->pc_col->size(); ROS_INFO("Rendered %u points of %u", rendered_points, points_to_render); Q_EMIT progress(1, "Saving Octomap", counter); if(counter % ParameterServer::instance()->get<int>("octomap_autosave_step") == 0){ Q_EMIT setGUIStatus(QString("Autosaving preliminary octomap to ") + filename); this->writeOctomap(filename); } } Q_EMIT setGUIStatus(QString("Saving final octomap to ") + filename); co_server_.save(qPrintable(filename)); Q_EMIT progress(1, "Finished Saving Octomap", 1e6); ROS_INFO ("Saved Octomap to %s", qPrintable(filename)); if(ParameterServer::instance()->get<bool>("octomap_clear_after_save")){ co_server_.reset(); ROS_INFO ("Reset Octomap to free memory"); } Q_EMIT renderableOctomap(&co_server_); batch_processing_runs_ = false; } void GraphManager::writeOctomap(QString filename) const { ScopedTimer s(__FUNCTION__); co_server_.save(qPrintable(filename)); } void GraphManager::renderToOctomap(Node* node) { ScopedTimer s(__FUNCTION__); ROS_INFO("Rendering Node %i with frame %s", node->id_, node->header_.frame_id.c_str()); if(updateCloudOrigin(node)){//Only render if transformation estimate is valid co_server_.insertCloudCallback(node->pc_col, ParameterServer::instance()->get<double>("maximum_depth")); // Will be transformed according to sensor pose set previously } if(ParameterServer::instance()->get<bool>("octomap_clear_raycasted_clouds")){ node->clearPointCloud(); ROS_INFO("Cleared pointcloud of Node %i", node->id_); } } void GraphManager::saveIndividualCloudsToFile(QString file_basename) { ScopedTimer s(__FUNCTION__); ROS_INFO("Saving all clouds to %s_xxxx.pcd", qPrintable(file_basename)); std::string gt = ParameterServer::instance()->get<std::string>("ground_truth_frame_name"); ROS_INFO_COND(!gt.empty(), "Saving all clouds with ground truth sensor position to gt_%sxxxx.pcd", qPrintable(file_basename)); batch_processing_runs_ = true; tf::Transform world2base; QString message, filename; std::string fixed_frame_id = ParameterServer::instance()->get<std::string>("fixed_frame_name"); for (graph_it it = graph_.begin(); it != graph_.end(); ++it){ Node* node = it->second; if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); continue; } g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); if(!v){ ROS_ERROR("Nullpointer in graph at position %i!", it->first); continue; } if(node->pc_col->size() == 0){ ROS_INFO("Skipping Node %i, point cloud data is empty!", it->first); continue; } /*/TODO: is all this correct? tf::Transform transform = eigenTransf2TF(v->estimate()); tf::Transform cam2rgb; cam2rgb.setRotation(tf::createQuaternionFromRPY(-1.57,0,-1.57)); cam2rgb.setOrigin(tf::Point(0,-0.04,0)); world2base = cam2rgb*transform; */ if(ParameterServer::instance()->get<bool>("transform_individual_clouds")){ Eigen::Matrix4f m = v->estimate().matrix().cast<float>(); pcl::transformPointCloud(*(node->pc_col), *(node->pc_col), m); Eigen::Vector4f sensor_origin(0,0,0,0); Eigen::Quaternionf sensor_orientation(0,0,0,1); node->pc_col->sensor_origin_ = sensor_origin; node->pc_col->sensor_orientation_ = sensor_orientation; node->header_.frame_id = fixed_frame_id; } else { tf::Transform pose = eigenTransf2TF(v->estimate()); tf::StampedTransform base2points = node->getBase2PointsTransform();//get pose of base w.r.t current pc at capture time world2base = this->computeFixedToBaseTransform(node, false); tf::Transform world2points = world2base*base2points; Eigen::Vector4f sensor_origin(world2points.getOrigin().x(),world2points.getOrigin().y(),world2points.getOrigin().z(),world2points.getOrigin().w()); Eigen::Quaternionf sensor_orientation(world2points.getRotation().w(),world2points.getRotation().x(),world2points.getRotation().y(),world2points.getRotation().z()); node->pc_col->sensor_origin_ = sensor_origin; node->pc_col->sensor_orientation_ = sensor_orientation; node->header_.frame_id = fixed_frame_id; } filename.sprintf("%s_%04d.pcd", qPrintable(file_basename), it->first); ROS_INFO("Saving %s", qPrintable(filename)); Q_EMIT setGUIStatus(message.sprintf("Saving to %s: Transformed Node %i/%i", qPrintable(filename), it->first, (int)camera_vertices.size())); pcl::io::savePCDFile(qPrintable(filename), *(node->pc_col), true); //Last arg: true is binary mode. ASCII mode drops color bits if(!gt.empty()){ tf::StampedTransform gt_world2base = node->getGroundTruthTransform();//get mocap pose of base in map if( gt_world2base.frame_id_ == "/missing_ground_truth" ){ ROS_WARN_STREAM("Skipping ground truth: " << gt_world2base.child_frame_id_ << " child/parent " << gt_world2base.frame_id_); continue; } Eigen::Vector4f sensor_origin(gt_world2base.getOrigin().x(),gt_world2base.getOrigin().y(),gt_world2base.getOrigin().z(),gt_world2base.getOrigin().w()); Eigen::Quaternionf sensor_orientation(gt_world2base.getRotation().w(),gt_world2base.getRotation().x(),gt_world2base.getRotation().y(),gt_world2base.getRotation().z()); node->pc_col->sensor_origin_ = sensor_origin; node->pc_col->sensor_orientation_ = sensor_orientation; node->header_.frame_id = fixed_frame_id; filename.sprintf("%s_%04d_gt.pcd", qPrintable(file_basename), it->first); Q_EMIT setGUIStatus(message.sprintf("Saving to %s: Transformed Node %i/%i", qPrintable(filename), it->first, (int)camera_vertices.size())); pcl::io::savePCDFile(qPrintable(filename), *(node->pc_col), true); //Last arg: true is binary mode. ASCII mode drops color bits } } Q_EMIT setGUIStatus("Saved all point clouds"); ROS_INFO ("Saved all points clouds to %sxxxx.pcd", qPrintable(file_basename)); batch_processing_runs_ = false; } void GraphManager::save_A_CloudsToFile(QString file_basename) { ScopedTimer s(__FUNCTION__); ROS_INFO("Saving A clouds to %s.pcd", qPrintable(file_basename)); batch_processing_runs_ = true; tf::Transform world2base; QString message, filename; std::string fixed_frame_id = ParameterServer::instance()->get<std::string>("fixed_frame_name"); int it = graph_.size(); Node* node = graph_[it-1]; g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); if(node->pc_col->size() == 0){ ROS_INFO("Skipping Node %i, point cloud data is empty!", it); } if(ParameterServer::instance()->get<bool>("transform_individual_clouds")){ Eigen::Matrix4f m = v->estimate().matrix().cast<float>(); pcl::transformPointCloud(*(node->pc_col), *(node->pc_col), m); Eigen::Vector4f sensor_origin(0,0,0,0); Eigen::Quaternionf sensor_orientation(0,0,0,1); node->pc_col->sensor_origin_ = sensor_origin; node->pc_col->sensor_orientation_ = sensor_orientation; node->header_.frame_id = fixed_frame_id; } else { tf::Transform pose = eigenTransf2TF(v->estimate()); tf::StampedTransform base2points = node->getBase2PointsTransform();//get pose of base w.r.t current pc at capture time world2base = this->computeFixedToBaseTransform(node, false); tf::Transform world2points = world2base*base2points; Eigen::Vector4f sensor_origin(world2points.getOrigin().x(),world2points.getOrigin().y(),world2points.getOrigin().z(),world2points.getOrigin().w()); Eigen::Quaternionf sensor_orientation(world2points.getRotation().w(),world2points.getRotation().x(),world2points.getRotation().y(),world2points.getRotation().z()); node->pc_col->sensor_origin_ = sensor_origin; node->pc_col->sensor_orientation_ = sensor_orientation; node->header_.frame_id = fixed_frame_id; } filename.sprintf("%s_%04d.pcd", qPrintable(file_basename), it); ROS_INFO("Saving %s", qPrintable(filename)); pcl::io::savePCDFile(qPrintable(filename), *(node->pc_col), true); //Last arg: true is binary mode. ASCII mode drops color bits ROS_INFO ("Saved A points clouds to %sxxxx.pcd", qPrintable(file_basename)); batch_processing_runs_ = false; } void GraphManager::saveAllFeatures(QString filename, bool threaded) { if (ParameterServer::instance()->get<bool>("concurrent_io") && threaded) { QFuture<void> f1 = QtConcurrent::run(this, &GraphManager::saveAllFeaturesToFile, filename); //f1.waitForFinished(); } else {// Otherwise just call it without threading saveAllFeaturesToFile(filename); } } void GraphManager::saveAllFeaturesToFile(QString filename) { ScopedTimer s(__FUNCTION__); cv::FileStorage fs(qPrintable(filename), cv::FileStorage::WRITE); fs << "Feature_Locations" << "["; ROS_INFO("Saving all features to %s transformed to a common coordinate frame.", qPrintable(filename)); batch_processing_runs_ = true; tf::Transform world2rgb, cam2rgb; QString message; cam2rgb.setRotation(tf::createQuaternionFromRPY(-1.57,0,-1.57)); cam2rgb.setOrigin(tf::Point(0,-0.04,0)); int feat_count = 0; for (graph_it it = graph_.begin(); it != graph_.end(); ++it){ Node* node = it->second; if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); continue; } g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); tf::Transform world2cam = eigenTransf2TF(v->estimate()); world2rgb = cam2rgb*world2cam; Eigen::Matrix4f world2rgbMat; pcl_ros::transformAsMatrix(world2rgb, world2rgbMat); BOOST_FOREACH(Eigen::Vector4f loc, node->feature_locations_3d_) { loc.w() = 1.0; Eigen::Vector4f new_loc = world2rgbMat * loc; fs << "{:" << "x" << new_loc.x() << "y" << new_loc.y() << "z" << new_loc.z() << "}"; feat_count++; } Q_EMIT setGUIStatus(message.sprintf("Saving to %s: Features of Node %i/%i", qPrintable(filename), it->first, (int)camera_vertices.size())); } fs << "]"; //Assemble all descriptors into a big matrix assert(graph_.size()>0); int descriptor_size = graph_[0]->feature_descriptors_.cols; int descriptor_type = graph_[0]->feature_descriptors_.type(); cv::Mat alldescriptors(0, descriptor_size, descriptor_type); alldescriptors.reserve(feat_count); for (unsigned int i = 0; i < graph_.size(); ++i) { alldescriptors.push_back(graph_[i]->feature_descriptors_); } fs << "Feature_Descriptors" << alldescriptors; fs.release(); Q_EMIT setGUIStatus(message.sprintf("Saved %d features points to %s", feat_count, qPrintable(filename))); ROS_INFO ("Saved %d feature points to %s", feat_count, qPrintable(filename)); batch_processing_runs_ = false; } void GraphManager::saveAllCloudsToFile(QString filename){ ScopedTimer s(__FUNCTION__); if(graph_.size() < 1){ ROS_WARN("Cannot save empty graph. Aborted"); return; } pcl::PointCloud<point_type> aggregate_cloud; ///will hold all other clouds //Make big enough to hold all other clouds. This might be too much if NaNs are filtered. They are filtered according to the parameter preserve_raster_on_save aggregate_cloud.reserve(graph_.size() * graph_.begin()->second->pc_col->size()); ROS_INFO("Saving all clouds to %s, this may take a while as they need to be transformed to a common coordinate frame.", qPrintable(filename)); batch_processing_runs_ = true; std::string base_frame = ParameterServer::instance()->get<std::string>("base_frame_name"); if(base_frame.empty()){ //if there is no base frame defined, use frame of sensor data base_frame = graph_.begin()->second->header_.frame_id; } tf::Transform world2cam; //fill message //rgbdslam::CloudTransforms msg; QString message; ///FIXME: Should transform to <fixed_frame_name> tf::Transform cam2rgb; cam2rgb.setRotation(tf::createQuaternionFromRPY(-1.57,0,-1.57)); cam2rgb.setOrigin(tf::Point(0,-0.04,0)); for (graph_it it = graph_.begin(); it != graph_.end(); ++it){ Node* node = it->second; if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); continue; } g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); if(!v){ ROS_ERROR("Nullpointer in graph at position %i!", it->first); continue; } tf::Transform transform = eigenTransf2TF(v->estimate()); world2cam = cam2rgb*transform; transformAndAppendPointCloud (*(node->pc_col), aggregate_cloud, world2cam, ParameterServer::instance()->get<double>("maximum_depth"), node->id_); if(ParameterServer::instance()->get<bool>("batch_processing")) node->clearPointCloud(); //saving all is the last thing to do, so these are not required anymore Q_EMIT setGUIStatus(message.sprintf("Saving to %s: Transformed Node %i/%i", qPrintable(filename), it->first, (int)camera_vertices.size())); } aggregate_cloud.header.frame_id = base_frame; if(!filename.endsWith(".pcd", Qt::CaseInsensitive)){ filename.append(".pcd"); } pcl::io::savePCDFile(qPrintable(filename), aggregate_cloud, true); //Last arg is binary mode Q_EMIT setGUIStatus(message.sprintf("Saved %d data points to %s", (int)aggregate_cloud.points.size(), qPrintable(filename))); ROS_INFO ("Saved %d data points to %s", (int)aggregate_cloud.points.size(), qPrintable(filename)); if (whole_cloud_pub_.getNumSubscribers() > 0){ //if it should also be send out /* sensor_msgs::PointCloud2 cloudMessage_; //this will be send out in batch mode pcl::toROSMsg(aggregate_cloud,cloudMessage_); cloudMessage_.header.frame_id = base_frame; cloudMessage_.header.stamp = ros::Time::now(); whole_cloud_pub_.publish(cloudMessage_); */ whole_cloud_pub_.publish(aggregate_cloud.makeShared()); ROS_INFO("Aggregate pointcloud sent"); } batch_processing_runs_ = false; } void GraphManager::pointCloud2MeshFile(QString filename, pointcloud_type full_cloud) { QFile file(filename);//file is closed on destruction if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){ ROS_ERROR("Could not open file %s", qPrintable(filename)); return; } QTextStream out(&file); out << "ply\n"; out << "format ascii 1.0\n"; out << "element vertex " << (int)full_cloud.points.size() << "\n"; out << "property float x\n"; out << "property float y\n"; out << "property float z\n"; out << "property uchar red\n"; out << "property uchar green\n"; out << "property uchar blue\n"; out << "end_header\n"; unsigned char r,g,b; float x, y, z ; for(unsigned int i = 0; i < full_cloud.points.size() ; i++){ getColor(full_cloud.points[i], r,g,b); x = full_cloud.points[i].x; y = full_cloud.points[i].y; z = full_cloud.points[i].z; out << qSetFieldWidth(8) << x << " " << y << " " << z << " "; out << qSetFieldWidth(3) << r << " " << g << " " << b << "\n"; } } void GraphManager::saveTrajectory(QString filebasename, bool with_ground_truth) { ScopedTimer s(__FUNCTION__); if(graph_.size() == 0){ ROS_ERROR("Graph is empty, no trajectory can be saved"); return; } QMutexLocker locker(&optimizer_mutex_); //FIXME: DO this block only if with_ground_truth is true and !gt.empty() std::string gt = ParameterServer::instance()->get<std::string>("ground_truth_frame_name"); ROS_INFO("Comparison of relative motion with ground truth"); QString gtt_fname("_ground_truth.txt"); QFile gtt_file(gtt_fname.prepend(filebasename));//file is closed on destruction if(!gtt_file.open(QIODevice::WriteOnly|QIODevice::Text)) return; //TODO: Errormessage QTextStream gtt_out(&gtt_file); tf::StampedTransform b2p = graph_[0]->getGroundTruthTransform(); gtt_out.setRealNumberNotation(QTextStream::FixedNotation); gtt_out << "# TF Coordinate Frame ID: " << b2p.frame_id_.c_str() << "(data: " << b2p.child_frame_id_.c_str() << ")\n"; QString et_fname("_estimate.txt"); QFile et_file (et_fname.prepend(filebasename));//file is closed on destruction if(!et_file.open(QIODevice::WriteOnly|QIODevice::Text)) return; //TODO: Errormessage ROS_INFO("Logging Trajectory to %s", qPrintable(et_fname)); QTextStream et_out(&et_file); et_out.setRealNumberNotation(QTextStream::FixedNotation); b2p = graph_[0]->getBase2PointsTransform(); et_out << "# TF Coordinate Frame ID: " << b2p.frame_id_.c_str() << "(data: " << b2p.child_frame_id_.c_str() << ")\n"; for (graph_it it = graph_.begin(); it != graph_.end(); ++it){ Node* node = it->second; if(!node->valid_tf_estimate_) { ROS_INFO("Skipping node %i: No valid estimate", node->id_); continue; } g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(node->vertex_id_)); ROS_ERROR_COND(!v, "Nullpointer in graph at position %i!", it->first); tf::Transform pose = eigenTransf2TF(v->estimate()); tf::StampedTransform base2points = node->getBase2PointsTransform();//get pose of base w.r.t current pc at capture time tf::Transform world2base = init_base_pose_*base2points*pose*base2points.inverse(); logTransform(et_out, world2base, node->header_.stamp.toSec()); //Eigen::Matrix<double, 6,6> uncertainty = v->uncertainty(); //et_out << uncertainty(0,0) << "\t" << uncertainty(1,1) << "\t" << uncertainty(2,2) << "\t" << uncertainty(3,3) << "\t" << uncertainty(4,4) << "\t" << uncertainty(5,5) <<"\n" ; if(with_ground_truth && !gt.empty()){ tf::StampedTransform gt_world2base = node->getGroundTruthTransform();//get mocap pose of base in map if( gt_world2base.frame_id_ == "/missing_ground_truth" ){ ROS_WARN_STREAM("Skipping ground truth: " << gt_world2base.child_frame_id_ << " child/parent " << gt_world2base.frame_id_); continue; } logTransform(gtt_out, gt_world2base, gt_world2base.stamp_.toSec()); //logTransform(et_out, world2base, gt_world2base.stamp_.toSec()); } } ROS_INFO_COND(!gt.empty() && with_ground_truth, "Written logfiles ground_truth_trajectory.txt and estimated_trajectory.txt"); ROS_INFO_COND(gt.empty(), "Written logfile estimated_trajectory.txt"); } /** The following function are used for visualization in RVIZ. * They are only activated if their ros topics are subscribed to. * Be careful, they haven't been tested in a long time */ #include <visualization_msgs/Marker.h> #include <geometry_msgs/Point.h> typedef std::set<g2o::HyperGraph::Edge*> EdgeSet; void GraphManager::visualizeFeatureFlow3D(unsigned int marker_id, bool draw_outlier) { ScopedTimer s(__FUNCTION__); if (ransac_marker_pub_.getNumSubscribers() > 0){ //don't visualize, if nobody's looking if(curr_best_result_.edge.id1 < 0 || curr_best_result_.edge.id2 < 0) { ROS_WARN("Attempted to visualize invalid pairwise result"); return; } visualization_msgs::Marker marker_lines; marker_lines.header.frame_id = "/openni_rgb_optical_frame"; marker_lines.ns = "ransac_markers"; marker_lines.header.stamp = ros::Time::now(); marker_lines.action = visualization_msgs::Marker::ADD; marker_lines.pose.orientation.w = 1.0; marker_lines.id = marker_id; marker_lines.type = visualization_msgs::Marker::LINE_LIST; marker_lines.scale.x = 0.002; std_msgs::ColorRGBA color_red ; //red outlier color_red.r = 1.0; color_red.a = 1.0; std_msgs::ColorRGBA color_green; //green inlier, newer endpoint color_green.g = 1.0; color_green.a = 1.0; std_msgs::ColorRGBA color_yellow; //yellow inlier, earlier endpoint color_yellow.r = 1.0; color_yellow.g = 1.0; color_yellow.a = 1.0; std_msgs::ColorRGBA color_blue ; //red-blue outlier color_blue.b = 1.0; color_blue.a = 1.0; marker_lines.color = color_green; //just to set the alpha channel to non-zero const g2o::VertexSE3* earlier_v; //used to get the transform const g2o::VertexSE3* newer_v; //used to get the transform // end of initialization ROS_DEBUG("Matches Visualization start: %zu Matches, %zu Inliers", curr_best_result_.all_matches.size(), curr_best_result_.inlier_matches.size()); // write all inital matches to the line_list marker_lines.points.clear();//necessary? earlier_v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(nodeId2VertexId(curr_best_result_.edge.id1))); newer_v = dynamic_cast<g2o::VertexSE3*>(optimizer_->vertex(nodeId2VertexId(curr_best_result_.edge.id2))); Node* last = graph_.find(curr_best_result_.edge.id2)->second; Node* prev = graph_.find(curr_best_result_.edge.id1)->second; if (draw_outlier) { BOOST_FOREACH(cv::DMatch match, curr_best_result_.all_matches) { //for (unsigned int i=0;i<curr_best_result_.all_matches.size(); i++){ int newer_id = match.queryIdx; //feature id in newer node int earlier_id = match.trainIdx; //feature id in earlier node //Outliers are red (newer) to blue (older) marker_lines.colors.push_back(color_red); marker_lines.colors.push_back(color_blue); marker_lines.points.push_back( pointInWorldFrame(last->feature_locations_3d_[newer_id], newer_v->estimate())); marker_lines.points.push_back( pointInWorldFrame(prev->feature_locations_3d_[earlier_id], earlier_v->estimate())); } } BOOST_FOREACH(cv::DMatch match, curr_best_result_.inlier_matches) { //for (unsigned int i=0;i<last_inlier_matches_.size(); i++){ int newer_id = match.queryIdx; //feature id in newer node int earlier_id = match.trainIdx; //feature id in earlier node //inliers are green (newer) to blue (older) marker_lines.colors.push_back(color_green); marker_lines.colors.push_back(color_blue); marker_lines.points.push_back( pointInWorldFrame(last->feature_locations_3d_[newer_id], newer_v->estimate())); marker_lines.points.push_back( pointInWorldFrame(prev->feature_locations_3d_[earlier_id], earlier_v->estimate())); } ransac_marker_pub_.publish(marker_lines); ROS_DEBUG_STREAM("Published " << marker_lines.points.size()/2 << " lines"); } } void GraphManager::visualizeGraphEdges() const { ScopedTimer s(__FUNCTION__); if (marker_pub_.getNumSubscribers() > 0){ //no visualization for nobody ROS_WARN("Sending RVIZ Marker"); visualization_msgs::Marker edges_marker; edges_marker.header.frame_id = "/openni_rgb_optical_frame"; //TODO: Should be a meaningfull fixed frame with known relative pose to the camera edges_marker.header.stamp = ros::Time::now(); edges_marker.ns = "camera_pose_graph"; // Set the namespace and id for this marker. This serves to create a unique ID edges_marker.id = 0; // Any marker sent with the same namespace and id will overwrite the old one edges_marker.type = visualization_msgs::Marker::LINE_LIST; edges_marker.action = visualization_msgs::Marker::ADD; // Set the marker action. Options are ADD and DELETE edges_marker.frame_locked = true; //rviz automatically retransforms the markers into the frame every update cycle // Set the scale of the marker -- 1x1x1 here means 1m on a side edges_marker.scale.x = 0.005; //line width //Global pose (used to transform all points) edges_marker.pose.position.x = 0; edges_marker.pose.position.y = 0; edges_marker.pose.position.z = 0; edges_marker.pose.orientation.x = 0.0; edges_marker.pose.orientation.y = 0.0; edges_marker.pose.orientation.z = 0.0; edges_marker.pose.orientation.w = 1.0; // Set the color -- be sure to set alpha to something non-zero! edges_marker.color.r = 1.0f; edges_marker.color.g = 1.0f; edges_marker.color.b = 1.0f; edges_marker.color.a = 0.5f;//looks smoother geometry_msgs::Point point; //start and endpoint for each line segment g2o::VertexSE3* v1,* v2; //used in loop EdgeSet::iterator edge_iter = cam_cam_edges_.begin(); int counter = 0; for(;edge_iter != cam_cam_edges_.end(); edge_iter++, counter++) { g2o::EdgeSE3* myedge = dynamic_cast<g2o::EdgeSE3*>(*edge_iter); std::vector<g2o::HyperGraph::Vertex*>& myvertices = myedge->vertices(); v1 = dynamic_cast<g2o::VertexSE3*>(myvertices.at(1)); v2 = dynamic_cast<g2o::VertexSE3*>(myvertices.at(0)); point.x = v1->estimate().translation().x(); point.y = v1->estimate().translation().y(); point.z = v1->estimate().translation().z(); edges_marker.points.push_back(point); point.x = v2->estimate().translation().x(); point.y = v2->estimate().translation().y(); point.z = v2->estimate().translation().z(); edges_marker.points.push_back(point); } marker_pub_.publish (edges_marker); ROS_INFO("published %d graph edges", counter); } } void GraphManager::visualizeGraphNodes() const { ScopedTimer s(__FUNCTION__); if (marker_pub_.getNumSubscribers() > 0){ //don't visualize, if nobody's looking visualization_msgs::Marker nodes_marker; nodes_marker.header.frame_id = "/openni_rgb_optical_frame"; //TODO: Should be a meaningfull fixed frame with known relative pose to the camera nodes_marker.header.stamp = ros::Time::now(); nodes_marker.ns = "camera_pose_graph"; // Set the namespace and id for this marker. This serves to create a unique ID nodes_marker.id = 1; // Any marker sent with the same namespace and id will overwrite the old one nodes_marker.type = visualization_msgs::Marker::LINE_LIST; nodes_marker.action = visualization_msgs::Marker::ADD; // Set the marker action. Options are ADD and DELETE nodes_marker.frame_locked = true; //rviz automatically retransforms the markers into the frame every update cycle // Set the scale of the marker -- 1x1x1 here means 1m on a side nodes_marker.scale.x = 0.002; //Global pose (used to transform all points) //TODO: is this the default pose anyway? nodes_marker.pose.position.x = 0; nodes_marker.pose.position.y = 0; nodes_marker.pose.position.z = 0; nodes_marker.pose.orientation.x = 0.0; nodes_marker.pose.orientation.y = 0.0; nodes_marker.pose.orientation.z = 0.0; nodes_marker.pose.orientation.w = 1.0; // Set the color -- be sure to set alpha to something non-zero! nodes_marker.color.r = 1.0f; nodes_marker.color.g = 0.0f; nodes_marker.color.b = 0.0f; nodes_marker.color.a = 1.0f; geometry_msgs::Point tail; //same startpoint for each line segment geometry_msgs::Point tip; //different endpoint for each line segment std_msgs::ColorRGBA arrow_color_red ; //red x axis arrow_color_red.r = 1.0; arrow_color_red.a = 1.0; std_msgs::ColorRGBA arrow_color_green; //green y axis arrow_color_green.g = 1.0; arrow_color_green.a = 1.0; std_msgs::ColorRGBA arrow_color_blue ; //blue z axis arrow_color_blue.b = 1.0; arrow_color_blue.a = 1.0; Eigen::Vector3d origin(0.0,0.0,0.0); Eigen::Vector3d x_axis(0.2,0.0,0.0); //20cm long axis for the first (almost fixed) node Eigen::Vector3d y_axis(0.0,0.2,0.0); Eigen::Vector3d z_axis(0.0,0.0,0.2); Eigen::Vector3d tmp; //the transformed endpoints int counter = 0; g2o::VertexSE3* v; //used in loop for (g2o::HyperGraph::VertexSet::iterator it = camera_vertices.begin(); it != camera_vertices.end(); ++it){ // VertexIDMap::iterator vertex_iter = optimizer_->vertices().begin(); // for(/*see above*/; vertex_iter != optimizer_->vertices().end(); vertex_iter++, counter++) { v = dynamic_cast<g2o::VertexSE3* >(*it); //v->estimate().rotation().x()+ v->estimate().rotation().y()+ v->estimate().rotation().z()+ v->estimate().rotation().w(); tmp = v->estimate() * origin; tail.x = tmp.x(); tail.y = tmp.y(); tail.z = tmp.z(); //Endpoints X-Axis nodes_marker.points.push_back(tail); nodes_marker.colors.push_back(arrow_color_red); tmp = v->estimate() * x_axis; tip.x = tmp.x(); tip.y = tmp.y(); tip.z = tmp.z(); nodes_marker.points.push_back(tip); nodes_marker.colors.push_back(arrow_color_red); //Endpoints Y-Axis nodes_marker.points.push_back(tail); nodes_marker.colors.push_back(arrow_color_green); tmp = v->estimate() * y_axis; tip.x = tmp.x(); tip.y = tmp.y(); tip.z = tmp.z(); nodes_marker.points.push_back(tip); nodes_marker.colors.push_back(arrow_color_green); //Endpoints Z-Axis nodes_marker.points.push_back(tail); nodes_marker.colors.push_back(arrow_color_blue); tmp = v->estimate() * z_axis; tip.x = tmp.x(); tip.y = tmp.y(); tip.z = tmp.z(); nodes_marker.points.push_back(tip); nodes_marker.colors.push_back(arrow_color_blue); //shorten all nodes after the first one x_axis.x() = 0.1; y_axis.y() = 0.1; z_axis.z() = 0.1; } marker_pub_.publish (nodes_marker); ROS_INFO("published %d graph nodes", counter); } } void GraphManager::saveG2OGraph(QString filename) { ROS_INFO("Saving G2O graph to %s", qPrintable(filename)); optimizer_->save(qPrintable(filename)); } tf::StampedTransform GraphManager::stampedTransformInWorldFrame(const Node* node, const tf::Transform& computed_motion) const { std::string fixed_frame = ParameterServer::instance()->get<std::string>("fixed_frame_name"); std::string base_frame = ParameterServer::instance()->get<std::string>("base_frame_name"); if(base_frame.empty()){ //if there is no base frame defined, use frame of sensor data base_frame = node->header_.frame_id; } const tf::StampedTransform& base2points = node->getBase2PointsTransform();//get pose of base w.r.t current pc at capture time tf::Transform world2base = init_base_pose_*base2points*computed_motion*base2points.inverse(); //printTransform("World->Base", world2base); return tf::StampedTransform(world2base.inverse(), base2points.stamp_, base_frame, fixed_frame); } void GraphManager::broadcastLatestTransform(const ros::TimerEvent& event) const { //printTransform("Broadcasting cached transform", latest_transform_cache_); /* tf::StampedTransform tmp(latest_transform_cache_, ros::Time::now(), latest_transform_cache_.frame_id_, latest_transform_cache_.child_frame_id_); broadcastTransform(tmp); */ } void GraphManager::broadcastTransform(const tf::StampedTransform& stamped_transform) const { br_.sendTransform(stamped_transform); } /* void GraphManager::broadcastTransform(Node* node, tf::Transform& computed_motion){ std::string fixed_frame = ParameterServer::instance()->get<std::string>("fixed_frame_name"); std::string base_frame = ParameterServer::instance()->get<std::string>("base_frame_name"); if(base_frame.empty()){ //if there is no base frame defined, use frame of sensor data base_frame = node->header_.frame_id; } /* if(graph_.size() == 0){ ROS_WARN("Cannot broadcast transform while graph is empty sending identity"); br_.sendTransform(tf::StampedTransform(tf::Transform::getIdentity(), ros::Time::now(), fixed_frame, base_frame)); return; } * / const tf::StampedTransform& base2points = node->getBase2PointsTransform();//get pose of base w.r.t current pc at capture time //Assumption: computed_motion_ contains last pose tf::Transform world2base = init_base_pose_*base2points*computed_motion*base2points.inverse(); printTransform("World->Base", world2base); ROS_DEBUG("Broadcasting transform"); br_.sendTransform(tf::StampedTransform(world2base.inverse(), base2points.stamp_, base_frame, fixed_frame)); } */ ///Send node's pointcloud with given publisher and timestamp void publishCloud(Node* node, ros::Time timestamp, ros::Publisher pub){ myHeader backup_h(node->pc_col->header); myHeader newtime_h(node->pc_col->header); newtime_h.stamp = timestamp; node->pc_col->header = newtime_h; pub.publish(node->pc_col); ROS_INFO("Pointcloud with id %i sent with frame %s", node->id_, node->pc_col->header.frame_id.c_str()); node->pc_col->header = backup_h; } void drawFeatureConnectors(cv::Mat& canvas, cv::Scalar line_color, const std::vector<cv::DMatch> matches, const std::vector<cv::KeyPoint>& newer_keypoints, const std::vector<cv::KeyPoint>& older_keypoints) { const double pi_fourth = 3.14159265358979323846 / 4.0; const int line_thickness = 1; const int circle_radius = 6; const int cv_aa = 16; for(unsigned int mtch = 0; mtch < matches.size(); mtch++) { cv::Point2f p,q; //TODO: Use sub-pixel-accuracy unsigned int newer_idx = matches[mtch].queryIdx; unsigned int earlier_idx = matches[mtch].trainIdx; if(newer_idx > newer_keypoints.size()) break;//Added in case the feature info has been cleared q = newer_keypoints[newer_idx].pt; if(earlier_idx > older_keypoints.size()) break;//Added in case the feature info has been cleared p = older_keypoints[earlier_idx].pt; double angle; angle = atan2( (double) p.y - q.y, (double) p.x - q.x ); double hypotenuse = cv::norm(p-q); if(hypotenuse > 0.1){ //only larger motions larger than one pix get an arrow line cv::line( canvas, p, q, line_color, line_thickness, cv_aa ); } else { //draw a smaller circle into the bigger one cv::circle(canvas, p, 1, line_color, line_thickness, cv_aa); } if(hypotenuse > 3.0){ //only larger motions larger than this get an arrow tip /* Now draw the tips of the arrow. */ p.x = (q.x + 4 * cos(angle + pi_fourth)); p.y = (q.y + 4 * sin(angle + pi_fourth)); cv::line( canvas, p, q, line_color, line_thickness, cv_aa ); p.x = (q.x + 4 * cos(angle - pi_fourth)); p.y = (q.y + 4 * sin(angle - pi_fourth)); cv::line( canvas, p, q, line_color, line_thickness, cv_aa ); } } } void GraphManager::drawFeatureFlow(cv::Mat& canvas, cv::Scalar line_color, cv::Scalar circle_color) { struct timespec starttime, finish; double elapsed; clock_gettime(CLOCK_MONOTONIC, &starttime); if(!ParameterServer::instance()->get<bool>("use_gui")){ return; } ROS_DEBUG("Number of features to draw: %d", (int)curr_best_result_.inlier_matches.size()); if(graph_.empty()) { ROS_WARN("Feature Flow for empty graph requested. Bug?"); return; } else if(graph_.size() == 1 || curr_best_result_.edge.id1 == -1 ) {//feature flow is only available between at least two nodes Node* newernode = graph_[graph_.size()-1]; cv::drawKeypoints(canvas, newernode->feature_locations_2d_, canvas, cv::Scalar(255), 5); return; } Node* earliernode = graph_[curr_best_result_.edge.id1];//graph_.size()-2; //compare current to previous Node* newernode = graph_[curr_best_result_.edge.id2]; if(earliernode == NULL){ if(newernode == NULL ){ ROS_ERROR("Nullpointer for Node %u", (unsigned int)graph_.size()-1); } ROS_ERROR("Nullpointer for Node %d", curr_best_result_.edge.id1); curr_best_result_.edge.id1 = 0; return; } else if(newernode == NULL ){ ROS_ERROR("Nullpointer for Node %u", (unsigned int)graph_.size()-1); return; } cv::Mat tmpimage = cv::Mat::zeros(canvas.rows, canvas.cols, canvas.type()); if(canvas.type() == CV_8UC1) circle_color = cv::Scalar(255); //Generate different keypoint sets for those with depth and those without std::vector<cv::KeyPoint> with_depth, without_depth; for(int i = 0; i < newernode->feature_locations_2d_.size(); i++){ if(isnan(newernode->feature_locations_3d_[i](2))){ without_depth.push_back(newernode->feature_locations_2d_[i]); } else { with_depth.push_back(newernode->feature_locations_2d_[i]); } } //Draw normal keypoints in given color cv::drawKeypoints(canvas, with_depth, tmpimage, circle_color, 5); //Draw depthless keypoints in orange cv::drawKeypoints(canvas, without_depth, tmpimage, cv::Scalar(0,128,255,0), 5); canvas+=tmpimage; drawFeatureConnectors(canvas, cv::Scalar(0.0), curr_best_result_.all_matches, newernode->feature_locations_2d_, earliernode->feature_locations_2d_); drawFeatureConnectors(canvas, line_color, curr_best_result_.inlier_matches, newernode->feature_locations_2d_, earliernode->feature_locations_2d_); clock_gettime(CLOCK_MONOTONIC, &finish); elapsed = (finish.tv_sec - starttime.tv_sec); elapsed += (finish.tv_nsec - starttime.tv_nsec) / 1000000000.0; ROS_INFO_STREAM_COND_NAMED(elapsed > ParameterServer::instance()->get<double>("min_time_reported"), "timings", __FUNCTION__ << " runtime: "<< elapsed <<" s"); }
gpl-3.0
christosk92/Facts
Facts/obj/x86/Debug/XamlTypeInfo.g.cs
49285
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Facts { public partial class App : global::Windows.UI.Xaml.Markup.IXamlMetadataProvider { private global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider _provider; /// <summary> /// GetXamlType(Type) /// </summary> public global::Windows.UI.Xaml.Markup.IXamlType GetXamlType(global::System.Type type) { if(_provider == null) { _provider = new global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider(); } return _provider.GetXamlTypeByType(type); } /// <summary> /// GetXamlType(String) /// </summary> public global::Windows.UI.Xaml.Markup.IXamlType GetXamlType(string fullName) { if(_provider == null) { _provider = new global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider(); } return _provider.GetXamlTypeByName(fullName); } /// <summary> /// GetXmlnsDefinitions() /// </summary> public global::Windows.UI.Xaml.Markup.XmlnsDefinition[] GetXmlnsDefinitions() { return new global::Windows.UI.Xaml.Markup.XmlnsDefinition[0]; } } } namespace Facts.Facts_XamlTypeInfo { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal partial class XamlTypeInfoProvider { public global::Windows.UI.Xaml.Markup.IXamlType GetXamlTypeByType(global::System.Type type) { global::Windows.UI.Xaml.Markup.IXamlType xamlType; if (_xamlTypeCacheByType.TryGetValue(type, out xamlType)) { return xamlType; } int typeIndex = LookupTypeIndexByType(type); if(typeIndex != -1) { xamlType = CreateXamlType(typeIndex); } var userXamlType = xamlType as global::Facts.Facts_XamlTypeInfo.XamlUserType; if(xamlType == null || (userXamlType != null && userXamlType.IsReturnTypeStub && !userXamlType.IsLocalType)) { global::Windows.UI.Xaml.Markup.IXamlType libXamlType = CheckOtherMetadataProvidersForType(type); if (libXamlType != null) { if(libXamlType.IsConstructible || xamlType == null) { xamlType = libXamlType; } } } if (xamlType != null) { _xamlTypeCacheByName.Add(xamlType.FullName, xamlType); _xamlTypeCacheByType.Add(xamlType.UnderlyingType, xamlType); } return xamlType; } public global::Windows.UI.Xaml.Markup.IXamlType GetXamlTypeByName(string typeName) { if (string.IsNullOrEmpty(typeName)) { return null; } global::Windows.UI.Xaml.Markup.IXamlType xamlType; if (_xamlTypeCacheByName.TryGetValue(typeName, out xamlType)) { return xamlType; } int typeIndex = LookupTypeIndexByName(typeName); if(typeIndex != -1) { xamlType = CreateXamlType(typeIndex); } var userXamlType = xamlType as global::Facts.Facts_XamlTypeInfo.XamlUserType; if(xamlType == null || (userXamlType != null && userXamlType.IsReturnTypeStub && !userXamlType.IsLocalType)) { global::Windows.UI.Xaml.Markup.IXamlType libXamlType = CheckOtherMetadataProvidersForName(typeName); if (libXamlType != null) { if(libXamlType.IsConstructible || xamlType == null) { xamlType = libXamlType; } } } if (xamlType != null) { _xamlTypeCacheByName.Add(xamlType.FullName, xamlType); _xamlTypeCacheByType.Add(xamlType.UnderlyingType, xamlType); } return xamlType; } public global::Windows.UI.Xaml.Markup.IXamlMember GetMemberByLongName(string longMemberName) { if (string.IsNullOrEmpty(longMemberName)) { return null; } global::Windows.UI.Xaml.Markup.IXamlMember xamlMember; if (_xamlMembers.TryGetValue(longMemberName, out xamlMember)) { return xamlMember; } xamlMember = CreateXamlMember(longMemberName); if (xamlMember != null) { _xamlMembers.Add(longMemberName, xamlMember); } return xamlMember; } global::System.Collections.Generic.Dictionary<string, global::Windows.UI.Xaml.Markup.IXamlType> _xamlTypeCacheByName = new global::System.Collections.Generic.Dictionary<string, global::Windows.UI.Xaml.Markup.IXamlType>(); global::System.Collections.Generic.Dictionary<global::System.Type, global::Windows.UI.Xaml.Markup.IXamlType> _xamlTypeCacheByType = new global::System.Collections.Generic.Dictionary<global::System.Type, global::Windows.UI.Xaml.Markup.IXamlType>(); global::System.Collections.Generic.Dictionary<string, global::Windows.UI.Xaml.Markup.IXamlMember> _xamlMembers = new global::System.Collections.Generic.Dictionary<string, global::Windows.UI.Xaml.Markup.IXamlMember>(); string[] _typeNameTable = null; global::System.Type[] _typeTable = null; private void InitTypeTables() { _typeNameTable = new string[23]; _typeNameTable[0] = "Facts.Views.datefact"; _typeNameTable[1] = "Windows.UI.Xaml.Controls.Page"; _typeNameTable[2] = "Windows.UI.Xaml.Controls.UserControl"; _typeNameTable[3] = "Facts.Views.homePage"; _typeNameTable[4] = "Microsoft.Xaml.Interactivity.Interaction"; _typeNameTable[5] = "Object"; _typeNameTable[6] = "Microsoft.Xaml.Interactivity.BehaviorCollection"; _typeNameTable[7] = "Windows.UI.Xaml.DependencyObjectCollection"; _typeNameTable[8] = "Windows.UI.Xaml.DependencyObject"; _typeNameTable[9] = "Microsoft.Xaml.Interactions.Core.EventTriggerBehavior"; _typeNameTable[10] = "Microsoft.Xaml.Interactivity.Behavior"; _typeNameTable[11] = "Microsoft.Xaml.Interactivity.ActionCollection"; _typeNameTable[12] = "String"; _typeNameTable[13] = "Microsoft.Xaml.Interactions.Core.InvokeCommandAction"; _typeNameTable[14] = "System.Windows.Input.ICommand"; _typeNameTable[15] = "Windows.UI.Xaml.Data.IValueConverter"; _typeNameTable[16] = "Facts.Views.MainPage"; _typeNameTable[17] = "Facts.ViewModels.MainPageViewModel"; _typeNameTable[18] = "Caliburn.Micro.PropertyChangedBase"; _typeNameTable[19] = "Facts.Views.NumericTextBoxBehavior"; _typeNameTable[20] = "Boolean"; _typeNameTable[21] = "Facts.Views.mathFacct"; _typeNameTable[22] = "Facts.Views.triviafact"; _typeTable = new global::System.Type[23]; _typeTable[0] = typeof(global::Facts.Views.datefact); _typeTable[1] = typeof(global::Windows.UI.Xaml.Controls.Page); _typeTable[2] = typeof(global::Windows.UI.Xaml.Controls.UserControl); _typeTable[3] = typeof(global::Facts.Views.homePage); _typeTable[4] = typeof(global::Microsoft.Xaml.Interactivity.Interaction); _typeTable[5] = typeof(global::System.Object); _typeTable[6] = typeof(global::Microsoft.Xaml.Interactivity.BehaviorCollection); _typeTable[7] = typeof(global::Windows.UI.Xaml.DependencyObjectCollection); _typeTable[8] = typeof(global::Windows.UI.Xaml.DependencyObject); _typeTable[9] = typeof(global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior); _typeTable[10] = typeof(global::Microsoft.Xaml.Interactivity.Behavior); _typeTable[11] = typeof(global::Microsoft.Xaml.Interactivity.ActionCollection); _typeTable[12] = typeof(global::System.String); _typeTable[13] = typeof(global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction); _typeTable[14] = typeof(global::System.Windows.Input.ICommand); _typeTable[15] = typeof(global::Windows.UI.Xaml.Data.IValueConverter); _typeTable[16] = typeof(global::Facts.Views.MainPage); _typeTable[17] = typeof(global::Facts.ViewModels.MainPageViewModel); _typeTable[18] = typeof(global::Caliburn.Micro.PropertyChangedBase); _typeTable[19] = typeof(global::Facts.Views.NumericTextBoxBehavior); _typeTable[20] = typeof(global::System.Boolean); _typeTable[21] = typeof(global::Facts.Views.mathFacct); _typeTable[22] = typeof(global::Facts.Views.triviafact); } private int LookupTypeIndexByName(string typeName) { if (_typeNameTable == null) { InitTypeTables(); } for (int i=0; i<_typeNameTable.Length; i++) { if(0 == string.CompareOrdinal(_typeNameTable[i], typeName)) { return i; } } return -1; } private int LookupTypeIndexByType(global::System.Type type) { if (_typeTable == null) { InitTypeTables(); } for(int i=0; i<_typeTable.Length; i++) { if(type == _typeTable[i]) { return i; } } return -1; } private object Activate_0_datefact() { return new global::Facts.Views.datefact(); } private object Activate_3_homePage() { return new global::Facts.Views.homePage(); } private object Activate_6_BehaviorCollection() { return new global::Microsoft.Xaml.Interactivity.BehaviorCollection(); } private object Activate_9_EventTriggerBehavior() { return new global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior(); } private object Activate_11_ActionCollection() { return new global::Microsoft.Xaml.Interactivity.ActionCollection(); } private object Activate_13_InvokeCommandAction() { return new global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction(); } private object Activate_16_MainPage() { return new global::Facts.Views.MainPage(); } private object Activate_17_MainPageViewModel() { return new global::Facts.ViewModels.MainPageViewModel(); } private object Activate_18_PropertyChangedBase() { return new global::Caliburn.Micro.PropertyChangedBase(); } private object Activate_19_NumericTextBoxBehavior() { return new global::Facts.Views.NumericTextBoxBehavior(); } private object Activate_21_mathFacct() { return new global::Facts.Views.mathFacct(); } private object Activate_22_triviafact() { return new global::Facts.Views.triviafact(); } private void VectorAdd_6_BehaviorCollection(object instance, object item) { var collection = (global::System.Collections.Generic.ICollection<global::Windows.UI.Xaml.DependencyObject>)instance; var newItem = (global::Windows.UI.Xaml.DependencyObject)item; collection.Add(newItem); } private void VectorAdd_11_ActionCollection(object instance, object item) { var collection = (global::System.Collections.Generic.ICollection<global::Windows.UI.Xaml.DependencyObject>)instance; var newItem = (global::Windows.UI.Xaml.DependencyObject)item; collection.Add(newItem); } private global::Windows.UI.Xaml.Markup.IXamlType CreateXamlType(int typeIndex) { global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType xamlType = null; global::Facts.Facts_XamlTypeInfo.XamlUserType userType; string typeName = _typeNameTable[typeIndex]; global::System.Type type = _typeTable[typeIndex]; switch (typeIndex) { case 0: // Facts.Views.datefact userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.Controls.Page")); userType.Activator = Activate_0_datefact; userType.SetIsLocalType(); xamlType = userType; break; case 1: // Windows.UI.Xaml.Controls.Page xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 2: // Windows.UI.Xaml.Controls.UserControl xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 3: // Facts.Views.homePage userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.Controls.Page")); userType.Activator = Activate_3_homePage; userType.SetIsLocalType(); xamlType = userType; break; case 4: // Microsoft.Xaml.Interactivity.Interaction userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Object")); userType.AddMemberName("Behaviors"); xamlType = userType; break; case 5: // Object xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 6: // Microsoft.Xaml.Interactivity.BehaviorCollection userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.DependencyObjectCollection")); userType.CollectionAdd = VectorAdd_6_BehaviorCollection; userType.SetIsReturnTypeStub(); xamlType = userType; break; case 7: // Windows.UI.Xaml.DependencyObjectCollection xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 8: // Windows.UI.Xaml.DependencyObject xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 9: // Microsoft.Xaml.Interactions.Core.EventTriggerBehavior userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Microsoft.Xaml.Interactivity.Behavior")); userType.Activator = Activate_9_EventTriggerBehavior; userType.SetContentPropertyName("Microsoft.Xaml.Interactions.Core.EventTriggerBehavior.Actions"); userType.AddMemberName("Actions"); userType.AddMemberName("EventName"); userType.AddMemberName("SourceObject"); xamlType = userType; break; case 10: // Microsoft.Xaml.Interactivity.Behavior userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.DependencyObject")); userType.AddMemberName("AssociatedObject"); xamlType = userType; break; case 11: // Microsoft.Xaml.Interactivity.ActionCollection userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.DependencyObjectCollection")); userType.CollectionAdd = VectorAdd_11_ActionCollection; userType.SetIsReturnTypeStub(); xamlType = userType; break; case 12: // String xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 13: // Microsoft.Xaml.Interactions.Core.InvokeCommandAction userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.DependencyObject")); userType.Activator = Activate_13_InvokeCommandAction; userType.AddMemberName("Command"); userType.AddMemberName("CommandParameter"); userType.AddMemberName("InputConverter"); userType.AddMemberName("InputConverterParameter"); userType.AddMemberName("InputConverterLanguage"); xamlType = userType; break; case 14: // System.Windows.Input.ICommand userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, null); userType.SetIsReturnTypeStub(); xamlType = userType; break; case 15: // Windows.UI.Xaml.Data.IValueConverter xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 16: // Facts.Views.MainPage userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.Controls.Page")); userType.Activator = Activate_16_MainPage; userType.AddMemberName("ViewModel"); userType.SetIsLocalType(); xamlType = userType; break; case 17: // Facts.ViewModels.MainPageViewModel userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Caliburn.Micro.PropertyChangedBase")); userType.SetIsReturnTypeStub(); userType.SetIsLocalType(); xamlType = userType; break; case 18: // Caliburn.Micro.PropertyChangedBase userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Object")); userType.Activator = Activate_18_PropertyChangedBase; xamlType = userType; break; case 19: // Facts.Views.NumericTextBoxBehavior userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.DependencyObject")); userType.Activator = Activate_19_NumericTextBoxBehavior; userType.AddMemberName("AllowDecimal"); userType.AddMemberName("AssociatedObject"); userType.SetIsLocalType(); xamlType = userType; break; case 20: // Boolean xamlType = new global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType(typeName, type); break; case 21: // Facts.Views.mathFacct userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.Controls.Page")); userType.Activator = Activate_21_mathFacct; userType.SetIsLocalType(); xamlType = userType; break; case 22: // Facts.Views.triviafact userType = new global::Facts.Facts_XamlTypeInfo.XamlUserType(this, typeName, type, GetXamlTypeByName("Windows.UI.Xaml.Controls.Page")); userType.Activator = Activate_22_triviafact; userType.SetIsLocalType(); xamlType = userType; break; } return xamlType; } private global::System.Collections.Generic.List<global::Windows.UI.Xaml.Markup.IXamlMetadataProvider> _otherProviders; private global::System.Collections.Generic.List<global::Windows.UI.Xaml.Markup.IXamlMetadataProvider> OtherProviders { get { if(_otherProviders == null) { var otherProviders = new global::System.Collections.Generic.List<global::Windows.UI.Xaml.Markup.IXamlMetadataProvider>(); global::Windows.UI.Xaml.Markup.IXamlMetadataProvider provider; provider = new global::Caliburn.Micro.XamlMetadataProvider() as global::Windows.UI.Xaml.Markup.IXamlMetadataProvider; otherProviders.Add(provider); provider = new global::Template10.Template10__Library__XamlTypeInfo.XamlMetaDataProvider() as global::Windows.UI.Xaml.Markup.IXamlMetadataProvider; otherProviders.Add(provider); _otherProviders = otherProviders; } return _otherProviders; } } private global::Windows.UI.Xaml.Markup.IXamlType CheckOtherMetadataProvidersForName(string typeName) { global::Windows.UI.Xaml.Markup.IXamlType xamlType = null; global::Windows.UI.Xaml.Markup.IXamlType foundXamlType = null; foreach(global::Windows.UI.Xaml.Markup.IXamlMetadataProvider xmp in OtherProviders) { xamlType = xmp.GetXamlType(typeName); if(xamlType != null) { if(xamlType.IsConstructible) // not Constructible means it might be a Return Type Stub { return xamlType; } foundXamlType = xamlType; } } return foundXamlType; } private global::Windows.UI.Xaml.Markup.IXamlType CheckOtherMetadataProvidersForType(global::System.Type type) { global::Windows.UI.Xaml.Markup.IXamlType xamlType = null; global::Windows.UI.Xaml.Markup.IXamlType foundXamlType = null; foreach(global::Windows.UI.Xaml.Markup.IXamlMetadataProvider xmp in OtherProviders) { xamlType = xmp.GetXamlType(type); if(xamlType != null) { if(xamlType.IsConstructible) // not Constructible means it might be a Return Type Stub { return xamlType; } foundXamlType = xamlType; } } return foundXamlType; } private object get_0_Interaction_Behaviors(object instance) { return global::Microsoft.Xaml.Interactivity.Interaction.GetBehaviors((global::Windows.UI.Xaml.DependencyObject)instance); } private void set_0_Interaction_Behaviors(object instance, object Value) { global::Microsoft.Xaml.Interactivity.Interaction.SetBehaviors((global::Windows.UI.Xaml.DependencyObject)instance, (global::Microsoft.Xaml.Interactivity.BehaviorCollection)Value); } private object get_1_EventTriggerBehavior_Actions(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior)instance; return that.Actions; } private object get_2_EventTriggerBehavior_EventName(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior)instance; return that.EventName; } private void set_2_EventTriggerBehavior_EventName(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior)instance; that.EventName = (global::System.String)Value; } private object get_3_EventTriggerBehavior_SourceObject(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior)instance; return that.SourceObject; } private void set_3_EventTriggerBehavior_SourceObject(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.EventTriggerBehavior)instance; that.SourceObject = (global::System.Object)Value; } private object get_4_Behavior_AssociatedObject(object instance) { var that = (global::Microsoft.Xaml.Interactivity.Behavior)instance; return that.AssociatedObject; } private object get_5_InvokeCommandAction_Command(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; return that.Command; } private void set_5_InvokeCommandAction_Command(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; that.Command = (global::System.Windows.Input.ICommand)Value; } private object get_6_InvokeCommandAction_CommandParameter(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; return that.CommandParameter; } private void set_6_InvokeCommandAction_CommandParameter(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; that.CommandParameter = (global::System.Object)Value; } private object get_7_InvokeCommandAction_InputConverter(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; return that.InputConverter; } private void set_7_InvokeCommandAction_InputConverter(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; that.InputConverter = (global::Windows.UI.Xaml.Data.IValueConverter)Value; } private object get_8_InvokeCommandAction_InputConverterParameter(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; return that.InputConverterParameter; } private void set_8_InvokeCommandAction_InputConverterParameter(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; that.InputConverterParameter = (global::System.Object)Value; } private object get_9_InvokeCommandAction_InputConverterLanguage(object instance) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; return that.InputConverterLanguage; } private void set_9_InvokeCommandAction_InputConverterLanguage(object instance, object Value) { var that = (global::Microsoft.Xaml.Interactions.Core.InvokeCommandAction)instance; that.InputConverterLanguage = (global::System.String)Value; } private object get_10_MainPage_ViewModel(object instance) { var that = (global::Facts.Views.MainPage)instance; return that.ViewModel; } private void set_10_MainPage_ViewModel(object instance, object Value) { var that = (global::Facts.Views.MainPage)instance; that.ViewModel = (global::Facts.ViewModels.MainPageViewModel)Value; } private object get_11_NumericTextBoxBehavior_AllowDecimal(object instance) { var that = (global::Facts.Views.NumericTextBoxBehavior)instance; return that.AllowDecimal; } private void set_11_NumericTextBoxBehavior_AllowDecimal(object instance, object Value) { var that = (global::Facts.Views.NumericTextBoxBehavior)instance; that.AllowDecimal = (global::System.Boolean)Value; } private object get_12_NumericTextBoxBehavior_AssociatedObject(object instance) { var that = (global::Facts.Views.NumericTextBoxBehavior)instance; return that.AssociatedObject; } private global::Windows.UI.Xaml.Markup.IXamlMember CreateXamlMember(string longMemberName) { global::Facts.Facts_XamlTypeInfo.XamlMember xamlMember = null; global::Facts.Facts_XamlTypeInfo.XamlUserType userType; switch (longMemberName) { case "Microsoft.Xaml.Interactivity.Interaction.Behaviors": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactivity.Interaction"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "Behaviors", "Microsoft.Xaml.Interactivity.BehaviorCollection"); xamlMember.SetTargetTypeName("Windows.UI.Xaml.DependencyObject"); xamlMember.SetIsAttachable(); xamlMember.Getter = get_0_Interaction_Behaviors; xamlMember.Setter = set_0_Interaction_Behaviors; break; case "Microsoft.Xaml.Interactions.Core.EventTriggerBehavior.Actions": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.EventTriggerBehavior"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "Actions", "Microsoft.Xaml.Interactivity.ActionCollection"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_1_EventTriggerBehavior_Actions; xamlMember.SetIsReadOnly(); break; case "Microsoft.Xaml.Interactions.Core.EventTriggerBehavior.EventName": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.EventTriggerBehavior"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "EventName", "String"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_2_EventTriggerBehavior_EventName; xamlMember.Setter = set_2_EventTriggerBehavior_EventName; break; case "Microsoft.Xaml.Interactions.Core.EventTriggerBehavior.SourceObject": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.EventTriggerBehavior"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "SourceObject", "Object"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_3_EventTriggerBehavior_SourceObject; xamlMember.Setter = set_3_EventTriggerBehavior_SourceObject; break; case "Microsoft.Xaml.Interactivity.Behavior.AssociatedObject": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactivity.Behavior"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "AssociatedObject", "Windows.UI.Xaml.DependencyObject"); xamlMember.Getter = get_4_Behavior_AssociatedObject; xamlMember.SetIsReadOnly(); break; case "Microsoft.Xaml.Interactions.Core.InvokeCommandAction.Command": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.InvokeCommandAction"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "Command", "System.Windows.Input.ICommand"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_5_InvokeCommandAction_Command; xamlMember.Setter = set_5_InvokeCommandAction_Command; break; case "Microsoft.Xaml.Interactions.Core.InvokeCommandAction.CommandParameter": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.InvokeCommandAction"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "CommandParameter", "Object"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_6_InvokeCommandAction_CommandParameter; xamlMember.Setter = set_6_InvokeCommandAction_CommandParameter; break; case "Microsoft.Xaml.Interactions.Core.InvokeCommandAction.InputConverter": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.InvokeCommandAction"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "InputConverter", "Windows.UI.Xaml.Data.IValueConverter"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_7_InvokeCommandAction_InputConverter; xamlMember.Setter = set_7_InvokeCommandAction_InputConverter; break; case "Microsoft.Xaml.Interactions.Core.InvokeCommandAction.InputConverterParameter": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.InvokeCommandAction"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "InputConverterParameter", "Object"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_8_InvokeCommandAction_InputConverterParameter; xamlMember.Setter = set_8_InvokeCommandAction_InputConverterParameter; break; case "Microsoft.Xaml.Interactions.Core.InvokeCommandAction.InputConverterLanguage": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Microsoft.Xaml.Interactions.Core.InvokeCommandAction"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "InputConverterLanguage", "String"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_9_InvokeCommandAction_InputConverterLanguage; xamlMember.Setter = set_9_InvokeCommandAction_InputConverterLanguage; break; case "Facts.Views.MainPage.ViewModel": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Facts.Views.MainPage"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "ViewModel", "Facts.ViewModels.MainPageViewModel"); xamlMember.Getter = get_10_MainPage_ViewModel; xamlMember.Setter = set_10_MainPage_ViewModel; break; case "Facts.Views.NumericTextBoxBehavior.AllowDecimal": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Facts.Views.NumericTextBoxBehavior"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "AllowDecimal", "Boolean"); xamlMember.SetIsDependencyProperty(); xamlMember.Getter = get_11_NumericTextBoxBehavior_AllowDecimal; xamlMember.Setter = set_11_NumericTextBoxBehavior_AllowDecimal; break; case "Facts.Views.NumericTextBoxBehavior.AssociatedObject": userType = (global::Facts.Facts_XamlTypeInfo.XamlUserType)GetXamlTypeByName("Facts.Views.NumericTextBoxBehavior"); xamlMember = new global::Facts.Facts_XamlTypeInfo.XamlMember(this, "AssociatedObject", "Windows.UI.Xaml.DependencyObject"); xamlMember.Getter = get_12_NumericTextBoxBehavior_AssociatedObject; xamlMember.SetIsReadOnly(); break; } return xamlMember; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal class XamlSystemBaseType : global::Windows.UI.Xaml.Markup.IXamlType { string _fullName; global::System.Type _underlyingType; public XamlSystemBaseType(string fullName, global::System.Type underlyingType) { _fullName = fullName; _underlyingType = underlyingType; } public string FullName { get { return _fullName; } } public global::System.Type UnderlyingType { get { return _underlyingType; } } virtual public global::Windows.UI.Xaml.Markup.IXamlType BaseType { get { throw new global::System.NotImplementedException(); } } virtual public global::Windows.UI.Xaml.Markup.IXamlMember ContentProperty { get { throw new global::System.NotImplementedException(); } } virtual public global::Windows.UI.Xaml.Markup.IXamlMember GetMember(string name) { throw new global::System.NotImplementedException(); } virtual public bool IsArray { get { throw new global::System.NotImplementedException(); } } virtual public bool IsCollection { get { throw new global::System.NotImplementedException(); } } virtual public bool IsConstructible { get { throw new global::System.NotImplementedException(); } } virtual public bool IsDictionary { get { throw new global::System.NotImplementedException(); } } virtual public bool IsMarkupExtension { get { throw new global::System.NotImplementedException(); } } virtual public bool IsBindable { get { throw new global::System.NotImplementedException(); } } virtual public bool IsReturnTypeStub { get { throw new global::System.NotImplementedException(); } } virtual public bool IsLocalType { get { throw new global::System.NotImplementedException(); } } virtual public global::Windows.UI.Xaml.Markup.IXamlType ItemType { get { throw new global::System.NotImplementedException(); } } virtual public global::Windows.UI.Xaml.Markup.IXamlType KeyType { get { throw new global::System.NotImplementedException(); } } virtual public object ActivateInstance() { throw new global::System.NotImplementedException(); } virtual public void AddToMap(object instance, object key, object item) { throw new global::System.NotImplementedException(); } virtual public void AddToVector(object instance, object item) { throw new global::System.NotImplementedException(); } virtual public void RunInitializer() { throw new global::System.NotImplementedException(); } virtual public object CreateFromString(string input) { throw new global::System.NotImplementedException(); } } internal delegate object Activator(); internal delegate void AddToCollection(object instance, object item); internal delegate void AddToDictionary(object instance, object key, object item); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal class XamlUserType : global::Facts.Facts_XamlTypeInfo.XamlSystemBaseType { global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider _provider; global::Windows.UI.Xaml.Markup.IXamlType _baseType; bool _isArray; bool _isMarkupExtension; bool _isBindable; bool _isReturnTypeStub; bool _isLocalType; string _contentPropertyName; string _itemTypeName; string _keyTypeName; global::System.Collections.Generic.Dictionary<string, string> _memberNames; global::System.Collections.Generic.Dictionary<string, object> _enumValues; public XamlUserType(global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider provider, string fullName, global::System.Type fullType, global::Windows.UI.Xaml.Markup.IXamlType baseType) :base(fullName, fullType) { _provider = provider; _baseType = baseType; } // --- Interface methods ---- override public global::Windows.UI.Xaml.Markup.IXamlType BaseType { get { return _baseType; } } override public bool IsArray { get { return _isArray; } } override public bool IsCollection { get { return (CollectionAdd != null); } } override public bool IsConstructible { get { return (Activator != null); } } override public bool IsDictionary { get { return (DictionaryAdd != null); } } override public bool IsMarkupExtension { get { return _isMarkupExtension; } } override public bool IsBindable { get { return _isBindable; } } override public bool IsReturnTypeStub { get { return _isReturnTypeStub; } } override public bool IsLocalType { get { return _isLocalType; } } override public global::Windows.UI.Xaml.Markup.IXamlMember ContentProperty { get { return _provider.GetMemberByLongName(_contentPropertyName); } } override public global::Windows.UI.Xaml.Markup.IXamlType ItemType { get { return _provider.GetXamlTypeByName(_itemTypeName); } } override public global::Windows.UI.Xaml.Markup.IXamlType KeyType { get { return _provider.GetXamlTypeByName(_keyTypeName); } } override public global::Windows.UI.Xaml.Markup.IXamlMember GetMember(string name) { if (_memberNames == null) { return null; } string longName; if (_memberNames.TryGetValue(name, out longName)) { return _provider.GetMemberByLongName(longName); } return null; } override public object ActivateInstance() { return Activator(); } override public void AddToMap(object instance, object key, object item) { DictionaryAdd(instance, key, item); } override public void AddToVector(object instance, object item) { CollectionAdd(instance, item); } override public void RunInitializer() { System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(UnderlyingType.TypeHandle); } override public object CreateFromString(string input) { if (_enumValues != null) { int value = 0; string[] valueParts = input.Split(','); foreach (string valuePart in valueParts) { object partValue; int enumFieldValue = 0; try { if (_enumValues.TryGetValue(valuePart.Trim(), out partValue)) { enumFieldValue = global::System.Convert.ToInt32(partValue); } else { try { enumFieldValue = global::System.Convert.ToInt32(valuePart.Trim()); } catch( global::System.FormatException ) { foreach( string key in _enumValues.Keys ) { if( string.Compare(valuePart.Trim(), key, global::System.StringComparison.OrdinalIgnoreCase) == 0 ) { if( _enumValues.TryGetValue(key.Trim(), out partValue) ) { enumFieldValue = global::System.Convert.ToInt32(partValue); break; } } } } } value |= enumFieldValue; } catch( global::System.FormatException ) { throw new global::System.ArgumentException(input, FullName); } } return value; } throw new global::System.ArgumentException(input, FullName); } // --- End of Interface methods public Activator Activator { get; set; } public AddToCollection CollectionAdd { get; set; } public AddToDictionary DictionaryAdd { get; set; } public void SetContentPropertyName(string contentPropertyName) { _contentPropertyName = contentPropertyName; } public void SetIsArray() { _isArray = true; } public void SetIsMarkupExtension() { _isMarkupExtension = true; } public void SetIsBindable() { _isBindable = true; } public void SetIsReturnTypeStub() { _isReturnTypeStub = true; } public void SetIsLocalType() { _isLocalType = true; } public void SetItemTypeName(string itemTypeName) { _itemTypeName = itemTypeName; } public void SetKeyTypeName(string keyTypeName) { _keyTypeName = keyTypeName; } public void AddMemberName(string shortName) { if(_memberNames == null) { _memberNames = new global::System.Collections.Generic.Dictionary<string,string>(); } _memberNames.Add(shortName, FullName + "." + shortName); } public void AddEnumValue(string name, object value) { if (_enumValues == null) { _enumValues = new global::System.Collections.Generic.Dictionary<string, object>(); } _enumValues.Add(name, value); } } internal delegate object Getter(object instance); internal delegate void Setter(object instance, object value); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal class XamlMember : global::Windows.UI.Xaml.Markup.IXamlMember { global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider _provider; string _name; bool _isAttachable; bool _isDependencyProperty; bool _isReadOnly; string _typeName; string _targetTypeName; public XamlMember(global::Facts.Facts_XamlTypeInfo.XamlTypeInfoProvider provider, string name, string typeName) { _name = name; _typeName = typeName; _provider = provider; } public string Name { get { return _name; } } public global::Windows.UI.Xaml.Markup.IXamlType Type { get { return _provider.GetXamlTypeByName(_typeName); } } public void SetTargetTypeName(string targetTypeName) { _targetTypeName = targetTypeName; } public global::Windows.UI.Xaml.Markup.IXamlType TargetType { get { return _provider.GetXamlTypeByName(_targetTypeName); } } public void SetIsAttachable() { _isAttachable = true; } public bool IsAttachable { get { return _isAttachable; } } public void SetIsDependencyProperty() { _isDependencyProperty = true; } public bool IsDependencyProperty { get { return _isDependencyProperty; } } public void SetIsReadOnly() { _isReadOnly = true; } public bool IsReadOnly { get { return _isReadOnly; } } public Getter Getter { get; set; } public object GetValue(object instance) { if (Getter != null) return Getter(instance); else throw new global::System.InvalidOperationException("GetValue"); } public Setter Setter { get; set; } public void SetValue(object instance, object value) { if (Setter != null) Setter(instance, value); else throw new global::System.InvalidOperationException("SetValue"); } } }
gpl-3.0
Wildhaus/DewRecode
ChatPlugin/ModuleVoIP.cpp
8988
#include "ModuleVoIP.hpp" #include "TeamspeakClient.hpp" #include "TeamspeakServer.hpp" #include <teamspeak/public_definitions.h> #include <teamspeak/public_errors.h> #include <teamspeak/clientlib_publicdefinitions.h> #include <teamspeak/clientlib.h> Modules::ModuleVoIP VoipModule; namespace { bool VariablePushToTalkUpdate(const std::vector<std::string>& Arguments, std::string& returnInfo) { unsigned int error; uint64 scHandlerID = VoIPGetscHandlerID(); if (scHandlerID != NULL) if (VoipModule.VarVoIPPushToTalk->ValueInt == 0) { if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "vad", "true")) != ERROR_ok) { returnInfo = "Error setting voice activation detection. Error: " + std::to_string(error); return false; } if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "voiceactivation_level", VoipModule.VarVoIPVADLevel->ValueString.c_str())) != ERROR_ok) { returnInfo = "Error setting voice activation level. Error: " + std::to_string(error); return false; } if ((error = ts3client_setClientSelfVariableAsInt(scHandlerID, CLIENT_INPUT_DEACTIVATED, INPUT_ACTIVE)) != ERROR_ok) { char* errorMsg; if (ts3client_getErrorMessage(error, &errorMsg) != ERROR_ok) ts3client_freeMemory(errorMsg); else returnInfo = errorMsg; return false; } if (ts3client_flushClientSelfUpdates(scHandlerID, NULL) != ERROR_ok) { char* errorMsg; if (ts3client_getErrorMessage(error, &errorMsg) != ERROR_ok) ts3client_freeMemory(errorMsg); else returnInfo = errorMsg; return false; } } else { if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "vad", "false")) != ERROR_ok) { returnInfo = "Error setting voice activation detection. Error: " + std::to_string(error); return false; } if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "voiceactivation_level", "-50")) != ERROR_ok) { returnInfo = "Error setting voice activation level. Error: " + std::to_string(error); return false; } } returnInfo = VoipModule.VarVoIPPushToTalk->ValueInt ? "Enabled VoIP PushToTalk, disabled voice activation detection" : "Disabled VoIP PushToTalk, enabled voice activation detection."; return true; } bool VariableVolumeModifierUpdate(const std::vector<std::string>& Arguments, std::string& returnInfo) { unsigned int error; uint64 scHandlerID = VoIPGetscHandlerID(); if (scHandlerID != NULL) if ((error = ts3client_setPlaybackConfigValue(scHandlerID, "volume_modifier", VoipModule.VarVoIPVolumeModifier->ValueString.c_str())) != ERROR_ok) { returnInfo = "Unable to set volume modifier, are you connected to a server? Error: " + std::to_string(error); return false; } returnInfo = "Set VoIP Volume Modifier to " + VoipModule.VarVoIPVolumeModifier->ValueString; return true; } bool VariableAGCUpdate(const std::vector<std::string>& Arguments, std::string& returnInfo) { unsigned int error; uint64 scHandlerID = VoIPGetscHandlerID(); if (scHandlerID != NULL) if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "agc", VoipModule.VarVoIPAGC->ValueInt ? "true" : "false")) != ERROR_ok) { returnInfo = "Unable to set Automatic Gain Control, are you connected to a server? Error: " + std::to_string(error); return false; } returnInfo = VoipModule.VarVoIPAGC->ValueInt ? "Enabled VoIP automatic gain control" : "Disabled VoIP automatic gain control"; return true; } bool VariableEchoCancellationUpdate(const std::vector<std::string>& Arguments, std::string& returnInfo) { unsigned int error; uint64 scHandlerID = VoIPGetscHandlerID(); if (scHandlerID != NULL) if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "echo_canceling", VoipModule.VarVoIPEchoCancellation->ValueInt ? "true" : "false")) != ERROR_ok) { returnInfo = "Unable to set echo cancellation. Error: " + std::to_string(error); return false; } returnInfo = VoipModule.VarVoIPEchoCancellation->ValueInt ? "Enabled VoIP echo cancellation" : "Disabled VoIP echo cancellation"; return true; } bool VariableVADLevelUpdate(const std::vector<std::string>& Arguments, std::string& returnInfo) { unsigned int error; uint64 scHandlerID = VoIPGetscHandlerID(); if (scHandlerID != NULL) if ((error = ts3client_setPreProcessorConfigValue(scHandlerID, "voiceactivation_level", VoipModule.VarVoIPVADLevel->ValueString.c_str())) != ERROR_ok) { returnInfo = "Error setting voice activation level. Error: " + std::to_string(error); return false; } returnInfo = "Set voice activation level to " + VoipModule.VarVoIPVADLevel->ValueString; return true; } bool VariableServerEnabledUpdate(const std::vector<std::string>& Arguments, std::string& returnInfo) { //TODO: Check if host, kill client too. StopTeamspeakClient(); //TODO: Figure out why this doesn't stop the teamspeak server when setting to 0.... if (VoipModule.VarVoIPServerEnabled->ValueInt == 0) StopTeamspeakServer(); returnInfo = VoipModule.VarVoIPServerEnabled->ValueInt ? "VoIP Server will start when a new lobby is created" : "Disabled VoIP auto-startup."; return true; } DWORD __stdcall StartClient(LPVOID) { return StartTeamspeakClient(VoipModule); } DWORD __stdcall StartServer(LPVOID) { return StartTeamspeakServer(VoipModule); } void CallbackServerStop(void* param) { StopTeamspeakClient(); StopTeamspeakServer(); } // TODO5: kick players from TS /*void CallbackServerPlayerKick(void* param) { PlayerKickInfo* playerInfo = reinterpret_cast<PlayerKickInfo*>(param); IRCModule.UserKick(IRCModule.GenerateIRCNick(playerInfo->Name, playerInfo->UID)); }*/ void CallbackClientStart(void* param) { // todo: a way to specify to the client which IP/port to connect to, instead of reading it from memory CreateThread(0, 0, StartClient, 0, 0, 0); } void CallbackServerStart(void* param) { // Start the Teamspeak VoIP Server since this is the host CreateThread(0, 0, StartServer, 0, 0, 0); // Join the Teamspeak VoIP Server so the host can talk CallbackClientStart(param); } } namespace Modules { ModuleVoIP::ModuleVoIP() : ModuleBase("VoIP") { engine->OnEvent("Core", "Server.Start", CallbackServerStart); engine->OnEvent("Core", "Server.Stop", CallbackServerStop); //engine->OnEvent("Core", "Server.PlayerKick", CallbackServerPlayerKick); engine->OnEvent("Core", "Game.Joining", CallbackClientStart); engine->OnEvent("Core", "Game.Leave", CallbackServerStop); VarVoIPPushToTalk = AddVariableInt("PushToTalk", "voip_ptt", "Requires the user to press a key to talk", eCommandFlagsArchived, 1, VariablePushToTalkUpdate); VarVoIPPushToTalk->ValueIntMin = 0; VarVoIPPushToTalk->ValueIntMax = 1; VarVoIPVolumeModifier = AddVariableInt("VolumeModifier", "voip_vm", "Modify the volume of other speakers (db)." "0 = no modification, negative values make the signal quieter," "greater than zero boost the signal louder. High positive values = really bad audio quality." , eCommandFlagsArchived, 6, VariableVolumeModifierUpdate); VarVoIPVolumeModifier->ValueInt64Min = -15; VarVoIPVolumeModifier->ValueInt64Max = 30; VarVoIPAGC = AddVariableInt("AGC", "voip_agc", "Automatic gain control keeps volumes level with each other. Less really soft, and less really loud.", eCommandFlagsArchived, 1, VariableAGCUpdate); VarVoIPAGC->ValueIntMin = 0; VarVoIPAGC->ValueIntMax = 1; VarVoIPEchoCancellation = AddVariableInt("EchoCancellation", "voip_ec", "Reduces echo over voice chat", eCommandFlagsArchived, 1, VariableEchoCancellationUpdate); VarVoIPEchoCancellation->ValueIntMin = 0; VarVoIPEchoCancellation->ValueIntMax = 1; VarVoIPVADLevel = AddVariableFloat("VoiceActivationLevel", "voip_vadlevel", "A high voice activation level means you have to speak louder into the microphone" "in order to start transmitting. Reasonable values range from -50 to 50. Default is -45." , eCommandFlagsArchived, -45.0f, VariableVADLevelUpdate); VarVoIPVADLevel->ValueFloatMin = -50.0f; VarVoIPVADLevel->ValueFloatMax = 50.0f; VarVoIPServerEnabled = AddVariableInt("ServerEnabled", "voip_server", "Enables or disables the VoIP Server.", eCommandFlagsArchived, 1, VariableServerEnabledUpdate); VarVoIPServerEnabled->ValueIntMin = 0; VarVoIPServerEnabled->ValueIntMax = 1; VarVoIPServerPort = AddVariableInt("ServerPort", "voip_port", "The port number to listen for VoIP connections on." "Tries listening on ports in the range [ServerPort..ServerPort+10].", (CommandFlags)(eCommandFlagsArchived | eCommandFlagsReplicated), 11794); VarVoIPServerPort->ValueIntMin = 0; VarVoIPServerPort->ValueIntMax = 0xFFFF; VarVoIPTalk = AddVariableInt("Talk", "voip_Talk", "Enables or disables talking (for push to talk)", eCommandFlagsNone, 0); VarVoIPTalk->ValueIntMin = 0; VarVoIPTalk->ValueIntMax = 1; } }
gpl-3.0
sdemingo/chex
model/answers/answer.go
5331
package answers import ( "errors" "html/template" "strconv" "time" "appengine/data" "appengine/srv" ) const ( TYPE_TESTSINGLE = iota + 1 TYPE_TESTMULTIPLE = iota + 1 ERR_ANSWERNOTFOUND = "Respuesta no encontrada" ERR_BADRENDEREDANSWER = "Respuesta renderizada erroneamente" ERR_ANSWERWITHOUTBODY = "Respuesta sin cuerpo definido" ERR_BADANSWERTYPE = "Respuesta con tipo de cuerpo desconocido" ERR_AUTHORID = "Respuesta con autor incorrecto" ) var bodiesTable = []string{ TYPE_TESTSINGLE: "testsingles-bodies", TYPE_TESTMULTIPLE: "testmultiples-bodies"} type Answer struct { Id int64 `json:",string" datastore:"-"` RawBody string `datastore:"-"` QuestId int64 `json:",string"` ExerciseId int64 `json:",string"` AuthorId int64 `json:",string"` TimeStamp time.Time //Author *users.NUser BodyType AnswerBodyType `json:",string"` Body AnswerBody `datastore:"-"` BodyId int64 Comment string } type AnswerBodyType int type AnswerBody interface { GetType() AnswerBodyType Equals(master AnswerBody) bool GetHTML(options []string) (template.HTML, error) IsUnsolved() bool data.DataItem } // Return an answer wihtout a body func NewAnswer(questionId int64, authorId int64) *Answer { a := new(Answer) a.Id = 0 a.QuestId = questionId a.ExerciseId = 0 a.AuthorId = authorId a.Comment = "" a.BodyType = -1 a.BodyId = -1 return a } // Return an answer with a blank body of bodyType func NewAnswerWithBody(questionId int64, authorId int64, bodyType AnswerBodyType) (*Answer, error) { a := NewAnswer(questionId, authorId) a.BodyType = bodyType err := a.BuildBody() return a, err } // Try build a body of BodyType from the RawBody property func (a *Answer) BuildBody() error { var abody AnswerBody if a.BodyType < 0 { return errors.New(ERR_ANSWERWITHOUTBODY) } switch a.BodyType { case TYPE_TESTSINGLE: sol, err := strconv.ParseInt(a.RawBody, 10, 32) if err != nil { abody = NewTestSingleAnswer(-1) } else { abody = NewTestSingleAnswer(int(sol)) } default: return errors.New(ERR_BADANSWERTYPE) } a.SetBody(abody) return nil } func (a *Answer) SetBody(abody AnswerBody) { a.Body = abody a.BodyType = abody.GetType() } func (a Answer) ID() int64 { return a.Id } func (a *Answer) SetID(id int64) { a.Id = id } type AnswerBuffer []*Answer func NewAnswerBuffer() AnswerBuffer { return make([]*Answer, 0) } func (v AnswerBuffer) At(i int) data.DataItem { return data.DataItem(v[i]) } func (v AnswerBuffer) Set(i int, t data.DataItem) { v[i] = t.(*Answer) } func (v AnswerBuffer) Len() int { return len(v) } // Get the answers for a question with questId, for a exercise with // exerciseId from an author with authorId func GetAnswers(wr srv.WrapperRequest, authorId int64, questId int64, exerciseId int64) ([]*Answer, error) { as := NewAnswerBuffer() q := data.NewConn(wr, "answers") q.AddFilter("AuthorId =", authorId) if questId > 0 { q.AddFilter("QuestId =", questId) } if exerciseId > 0 { q.AddFilter("ExerciseId =", exerciseId) } err := q.GetMany(&as) if err != nil || len(as) == 0 { return nil, errors.New(ERR_ANSWERNOTFOUND) } for i := range as { getAnswerBody(wr, as[i]) } return as, err } // Create or update an solution answer func PutAnswer(wr srv.WrapperRequest, a *Answer) error { if a.BodyType < 0 { return errors.New(ERR_ANSWERWITHOUTBODY) } all, err := GetAnswers(wr, a.AuthorId, a.QuestId, a.ExerciseId) qry := data.NewConn(wr, "answers") if err != nil { // New a.TimeStamp = time.Now() a.AuthorId = wr.NU.ID() err = putAnswerBody(wr, a) if err != nil { return err } qry.Put(a) } else { // Updated a2 := all[0] a2.TimeStamp = time.Now() a2.BodyType = a.BodyType a2.Body = a.Body // store the new body in the older id a2.Body.SetID(a2.BodyId) err = putAnswerBody(wr, a2) if err != nil { return err } qry.Put(a2) } return nil } func GetAnswersById(wr srv.WrapperRequest, id int64) (*Answer, error) { a := NewAnswer(-1, -1) qry := data.NewConn(wr, "answers") a.Id = id err := qry.Get(a) if err != nil { return a, errors.New(ERR_ANSWERNOTFOUND) } getAnswerBody(wr, a) return a, nil } // Create or update an answer for an exercise func putAnswer(wr srv.WrapperRequest, a *Answer) error { return nil } func putAnswerBody(wr srv.WrapperRequest, a *Answer) error { bodyTable := bodiesTable[a.BodyType] q := data.NewConn(wr, bodyTable) var err error switch a.Body.GetType() { case TYPE_TESTSINGLE: tbody := a.Body.(*TestSingleBody) q.Put(tbody) a.BodyId = tbody.ID() default: err = errors.New(ERR_ANSWERWITHOUTBODY) } return err } func getAnswerBody(wr srv.WrapperRequest, a *Answer) error { bodyTable := bodiesTable[a.BodyType] q := data.NewConn(wr, bodyTable) var err error switch a.BodyType { case TYPE_TESTSINGLE: body := NewTestSingleAnswer(-1) body.Solution = 0 // must be set to zero to unmarshall propertly in cache body.Id = a.BodyId err = q.Get(body) a.Body = body } return err } /* func getAnswers(wr srv.WrapperRequest, filters map[string][]string) (AnswerBuffer, error) { as := NewAnswerBuffer() var err error if filters["id"] != nil { a, err := GetAnswersById(wr, filters["id"][0]) as[0] = a return as, err } return as, err } */
gpl-3.0
sg-s/xolotl
c++/conductances/morris-lecar/CaCurrent.hpp
1240
// _ _ ____ _ ____ ___ _ // \/ | | | | | | | // _/\_ |__| |___ |__| | |___ // // component source [Morris & Lecar]() // component info: Morris & Lecar Calcium conductance #pragma once //inherit conductance class spec class CaCurrent: public conductance { public: double V1 = 0; double V2 = 1; double E = 100; // specify parameters + initial conditions CaCurrent(double gbar_, double V1_, double V2_, double E_) { gbar = gbar_; V1 = V1_; V2 = V2_; E = E_; // defaults if (isnan(gbar)) { gbar = 4.4; } if (isnan(E)) { E = 120; } if (isnan (V1)) { V1 = -1.2; } if (isnan (V2)) { V2 = 18; } p = 1; q = 0; name = "CaCurrent"; } void integrate(double, double); double m_inf(double V, double CaCurrent); }; void CaCurrent::integrate(double V, double Ca) { if (isnan(E)) { // update form container E = container->E_Ca; } else { // update to container container->E_Ca = E; } g = gbar*m_inf(V,Ca); container->i_Ca += getCurrent(V); } double CaCurrent::m_inf(double V, double Ca) {return 0.5*(1.0 + tanh((V-V1)/(V2)));}
gpl-3.0
ratmandu/HappyMapper
outwindow.cpp
772
#include "outwindow.h" #include "ui_outwindow.h" OutWindow::OutWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::OutWindow) { ui->setupUi(this); connect(ui->widget, SIGNAL(outputResized(QSize)), this, SLOT(outSizeChanged(QSize))); } OutWindow::~OutWindow() { delete ui; } QSize OutWindow::getSize() { return ui->widget->getOutputSize(); } QList<Quad*> *OutWindow::getQuadList() const { return quadList; } void OutWindow::setQuadList(QList<Quad*> *value) { quadList = value; ui->widget->setQuadList(value); } void OutWindow::MapMouseMoved(QPoint pos) { ui->widget->setCursorPos(pos); } void OutWindow::updateDisplay() { ui->widget->setNeedsUpdate(true); } void OutWindow::outSizeChanged(QSize size) { emit outputSizeChanged(size); }
gpl-3.0
elaeon/dsignature
creacion_firma/management/commands/sign.py
2874
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.conf import settings from creacion_firma.views import id_generator, SIZE_NAME from creacion_firma.classes import DigitalSign, tmp_dir_o_file, tmp_prefix from creacion_firma.models import UserDocumentSign from creacion_firma.utils import create_docs_test from subprocess import call import datetime class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--type', default=None, help='production, test') parser.add_argument('--password', default=None, help='escribe la contraseña') def handle(self, *args, **options): type_ocsp = options.get('type', "production") password = options.get('password', "") self.sign(password, type_ocsp) def sign(self, password, type_ocsp): tmp_dir_pkcs7_file = tmp_prefix + "pkcs7_files_test/" tmp_dir_pkcs7_file_date = tmp_dir_pkcs7_file+datetime.date.today().strftime("%Y%m") call(["mkdir", tmp_prefix]) call(["mkdir", tmp_dir_o_file]) call(["mkdir", tmp_dir_pkcs7_file]) call(["mkdir", tmp_dir_pkcs7_file_date]) if type_ocsp == "test": user_document_sign = create_docs_test("PXXD941105MDFCZL09", tmp_dir_o_file, 1000, "test") cer = "/home/agmartinez/ocsp_3_uat/1024-v2/aimr770903ri4.cer" key = "/home/agmartinez/ocsp_3_uat/1024-v2/AIMR770903RI4.key" else: user_document_sign = create_docs_test("MARA800822HDFRML00", tmp_dir_o_file, 155, "agmartinez") cer = "/home/agmartinez/Documentos/FIEL 2013/FIEL_MARA800822JQ4_20130523120921/mara800822jq4.cer" key = "/home/agmartinez/Documentos/FIEL 2013/FIEL_MARA800822JQ4_20130523120921/Claveprivada_FIEL_MARA800822JQ4_20130523_120921.key" cer_f = open(cer, "rb") key_f = open(key, "rb") digital_sign = DigitalSign(cer=cer_f, key=key_f, test=type_ocsp == "test") cer_f.close() key_f.close() print(digital_sign.get_info_cer()["o"]) number = digital_sign.get_ocsp_origin() OCSP_NUMBER = "C"+number if type_ocsp == "test": OCSP_NUMBER = "C0" print(digital_sign.sign( tmp_dir_pkcs7_file_date, user_document_sign, password, settings.CERTS[OCSP_NUMBER]["issuer"], settings.CERTS[OCSP_NUMBER]["ocsp"], settings.CERTS[OCSP_NUMBER]["chain"])) print("SIGN: ", digital_sign.verify(user_document_sign.xml.url)) print(user_document_sign.xml_pkcs7.url) print("CLEAN") digital_sign.clean() call(["rm", user_document_sign.xml_pkcs7.url]) call(["rm", user_document_sign.xml.url]) user_document_sign.delete()
gpl-3.0
albertoriva/bioscripts
methylfilter.py
11767
#!/usr/bin/env python ## (c) 2014-2017, Alberto Riva ([email protected]) ## DiBiG, ICBR Bioinformatics, University of Florida import sys from Bio import SeqIO import Script # Script class def usage(): sys.stderr.write("""methylfilter.py - Separate sequences by average methylation. Usage: methylfilter.py input.fa [options] outdesc ... The input file should be a fasta file in which the first sequence is the reference. All other sequences are compared to the reference to determine % methylation. Each `outdesc' argument should be a string of the form: min-max:filename where min and max should be expressed as percentages, ie integer numbers in the range 0..100. If min is omitted it defaults to 0. If max is omitted it defaults to 100. Each outdesc specifies that sequences with methylation values between min (inclusive) and max (exclusive) should be written to filename. Any number of outdesc arguments can be used. Options: -h, --help | Write this usage message. -v, --version | Print version number. -a, --addref | Write reference sequence at the beginning of each output file. -r, --report filename | Write to `filename' a report showing, for each input sequence, its % methylation and the output file it was written to. -s, --summary filename | Write to `filename' a summary showing the number of sequences written to each output file. -gcg | Do not exclude GCG sites from analysis. -gc | Output is based on GC methylation instead of CG. """) P = Script.Script("methylfilter.py", version="1.0", usage=usage, errors=[('BADRANGE', 'Bad range specification', "Cannot parse argument `{}'. Format should be: low-high:filename.")]) # Utility classes class refDesc(): """A class containing the reference sequence, its length, and a list of CG and GC positions.""" sequence = None length = 0 CGpositions = [] GCpositions = [] numCGs = 0 numGCs = 0 excludeGCG = True def __init__(self, ref, excludeGCG): length = len(ref) self.sequence = ref self.length = length self.excludeGCG = excludeGCG self.CGpositions = detectCG(ref, length, excludeGCG=self.excludeGCG) self.GCpositions = detectGC(ref, length, excludeGCG=self.excludeGCG) self.numCGs = len(self.CGpositions) self.numGCs = len(self.GCpositions) class outFile(): """A class that writes sequences whose methylation rate is in a specified range to a file.""" mrmin = 0 mrmax = 0 filename = None stream = None nout = 0 def __init__(self, filename, min, max): self.min = min self.max = max self.filename = filename self.nout = 0 def open(self): self.stream = open(self.filename, "w") def close(self): self.stream.close() def writeSeq(self, seq, count=True): SeqIO.write(seq, self.stream, "fasta") if count: self.nout = self.nout + 1 class mfrun(): """A class representing the whole run. Includes the refDesc object and the list of output file objects.""" rd = None infile = None outfiles = [] writeRef = False # If true, writes the reference sequence at the beginning of each output file reportFile = False # Name of report file, if desired reportStream = None summaryFile = False # Name of summary file, if desired summaryStream = None excludeGCG = True # mode = "CG" def parseArgs(self, args): """Parse command-line arguments creating outfiles.""" P.standardOpts(args) prev = False for arg in args: if prev == "r": self.reportFile = arg prev = False elif prev == "s": self.summaryFile = arg prev = False elif (arg == "--addref") or (arg == "-a"): self.writeRef = True elif (arg == "--report") or (arg == "-r"): prev = "r" elif (arg == "--summary") or (arg == "-s"): prev = "s" elif (arg == "-gcg"): self.excludeGCG = False elif arg == "-gc": self.mode = "GC" elif self.infile == None: self.infile = P.isFile(arg) else: pdash = arg.find('-') pcolon = arg.find(':', pdash) if (pdash == -1) or (pcolon == -1): P.errmsg(P.BADRANGE, arg) else: low = arg[0:pdash] high = arg[pdash+1:pcolon] fn = arg[pcolon+1:] if low == "": low = 0 else: low = int(low) if high == "": high = 100 else: high = int(high) if high == 100: high = 101 # hack so that we can use < in comparisons and still catch 100% self.outfiles.append(outFile(fn, low, high)) def openAll(self): """Open all necessary output files.""" for of in self.outfiles: of.open() if self.writeRef: of.writeSeq(self.rd.sequence, False) # don't count ref seq in number of written sequences if self.reportFile: print("Writing report to {}".format(self.reportFile)) self.reportStream = open(self.reportFile, "w") if self.mode == "CG": self.reportStream.write("Sequence\t% CG Meth\tConv\tTot\t% GC Meth\tFilename\n") elif self.mode == "GC": self.reportStream.write("Sequence\t% GC Meth\tConv\tTot\t% CG Meth\tFilename\n") def closeAll(self): """Close all output files.""" for of in self.outfiles: of.close() if self.reportStream: self.reportStream.close() def showOutfiles(self): """Show all defined output files with their ranges.""" for of in self.outfiles: print("{}% - {}% -> {}".format(of.min, of.max, of.filename)) def findOutfile(self, x): """Find the output file for value `x'.""" for of in self.outfiles: if (x >= of.min) and (x < of.max): return of return None def showSummary(self): tot = 0 for of in self.outfiles: tot = tot + of.nout print("{:5} {}".format(of.nout, of.filename)) if self.summaryFile: print("Writing summary to {}".format(self.summaryFile)) with open(self.summaryFile, "w") as out: out.write("Filename\tMin\tMax\tNseqs\n") for of in self.outfiles: out.write("{}\t{}\t{}\t{}\n".format(of.filename, of.min, of.max, of.nout)) return tot def report(self, s, p, c, t, p2, o): if self.reportStream: if o: self.reportStream.write("{}\t{:.2f}\t{}\t{}\t{:.2f}\t{}\n".format(s.id, p, c, t, p2, o.filename)) else: self.reportStream.write("{}\t{:.2f}\t{}\t{}\t{:.2f}\t{}\n".format(s.id, p, c, t, p2, "-")) ### General def loadSequences(filename): return SeqIO.parse(filename, "fasta") def detectCG(seq, length, excludeGCG=True): """Returns the list of C positions in CG dinucleotides in sequence `seq'. If `excludeGCG' is True, ignores GCG positions.""" result = [] candidate = False for i in range(length): if (seq[i] == 'C'): candidate = i elif (seq[i] == 'G') and candidate: if excludeGCG: if (i < 2) or seq[i-2] != 'G': result.append(candidate) candidate = False else: result.append(candidate) candidate = False else: candidate = False return result def detectGC(seq, length, excludeGCG=True): """Returns the list of C positions in GC dinucleotides in sequence `seq'. If `excludeGCG' is True, ignores GCG positions.""" result = [] candidate = False for i in range(1, length): if (seq[i] == 'C') and (seq[i-1] == 'G'): # This is a GC position. Now check position i+1 if excluding GCGs if excludeGCG: if (i == length-1) or seq[i+1] != 'G': result.append(i) # Otherwise, simply add the position else: result.append(i) return result def countCGconverted(rd, seq): return countConverted(seq, rd.CGpositions) def countGCconverted(rd, seq): return countConverted(seq, rd.GCpositions) def countConverted(seq, positions): """Check for C->T conversion in `seq' at the positions in the list `positions'. Returns a tuple containing the number of converted Cs and the total number of Cs in the list `positions' actually present in `seq' (ie, skipping the - positions).""" tot = 0 cnt = 0 for cgpos in positions: if seq[cgpos] != '-': tot = tot + 1 if seq[cgpos] == 'T': cnt = cnt + 1 return (cnt, tot) ### Main def main(): run = mfrun() run.parseArgs(sys.argv[1:]) if run.infile == None: sys.stderr.write("""No reference file specified. Please use the -h option for usage.\n""") sys.exit(-3) if len(run.outfiles) == 0: sys.stderr.write("""No output files specified. Please use the -h option for usage.\n""") sys.exit(-4) seqs = loadSequences(run.infile) rd = refDesc(seqs.next(), run.excludeGCG) # reference sequence run.rd = rd print("Reference sequence loaded from file `{}'.".format(run.infile)) if run.excludeGCG: print("Excluding GCG positions.") else: print("Not excluding GCG positions.") if run.mode == "CG": print("{}bp, {} CG positions.".format(rd.length, rd.numCGs)) elif run.mode == "GC": print("{}bp, {} GC positions.".format(rd.length, rd.numGCs)) try: run.openAll() print("{} output files opened:".format(len(run.outfiles))) run.showOutfiles() print("Parsing sequences...") nread = 0 for s in seqs: nread = nread + 1 (CGcnt, CGtot) = countCGconverted(rd, s) (GCcnt, GCtot) = countGCconverted(rd, s) if CGtot > 0: CGp = 100 * (1.0 - (CGcnt * 1.0 / CGtot)) # ensure we work with floats else: CGp = 0.0 if GCtot > 0: GCp = 100 * (1.0 - (GCcnt * 1.0 / GCtot)) else: GCp = 0.0 if run.mode == "CG": o = run.findOutfile(CGp) if o: o.writeSeq(s) run.report(s, CGp, CGcnt, CGtot, GCp, o) else: run.report(s, CGp, CGcnt, CGtot, GCp, None) elif run.mode == "GC": o = run.findOutfile(GCp) if o: o.writeSeq(s) run.report(s, GCp, GCcnt, GCtot, CGp, o) else: run.report(s, GCp, GCcnt, GCtot, CGp, None) finally: run.closeAll() print("Done. {} sequences read.".format(nread)) print("Report:") nwritten = run.showSummary() print("{} sequences written.".format(nwritten)) if __name__ == "__main__": if (len(sys.argv) == 1): usage() else: main()
gpl-3.0
graeme-lockley/mn-workspace
Data/Integer.js
1247
//- The following interface represents all numbers that can be expressed without a fractional component. //- //-```haskell //- interface Integer a extends Number a, Ordered a //- (/), mod :: a -> Maybe a //- divMod :: a -> Maybe (a * a) //- divMod y = //- this.(/)(y).reduce(() => Nothing)(q => this.mod(y).reduce(() => Nothing)(t => (q, r)) //- ``` //- //- Note the following: //- //- * The division centered operations all return a Maybe to cater for the scenario where an attempt is used to divide //- by 0. //- * The type `a * a` signifies a tuple. const Interfaces = require("./Interfaces"); const Number = require("./Number"); const Ordered = require("./Ordered"); const Maybe = require("./Maybe"); function IntegerType() { } Interfaces.extend(IntegerType, [ Number.NumberType, Ordered.OrderedType ]); //- Default implementation for `divMod`. //= Integer a => defaultDivMod :: a -> Maybe (a * a) IntegerType.prototype.divMod = function (y) { return this.$SLASH(y).reduce( () => Maybe.Nothing)( q => this.mod(y).reduce( () => Maybe.Nothing)( r => Maybe.Just([q, r]) ) ); }; module.exports = { Integer: new IntegerType(), IntegerType };
gpl-3.0
OSTraining/OSEmbed
src/library/mpratt/embera/src/Embera/Provider/Slideshare.php
1198
<?php /** * Slideshare.php * * @package Embera * @author Michael Pratt <[email protected]> * @link http://www.michael-pratt.com/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Embera\Provider; use Embera\Url; /** * Slideshare Provider * @link https://slideshare.net */ class Slideshare extends ProviderAdapter implements ProviderInterface { /** inline {@inheritdoc} */ protected $endpoint = 'https://www.slideshare.net/api/oembed/2?format=json'; /** inline {@inheritdoc} */ protected static $hosts = [ '*.slideshare.net' ]; /** inline {@inheritdoc} */ protected $httpsSupport = true; /** inline {@inheritdoc} */ protected $responsiveSupport = true; /** inline {@inheritdoc} */ public function validateUrl(Url $url) { return (bool) (preg_match('~slideshare\.net/([^/]+)/([^/]+)~i', (string) $url)); } /** inline {@inheritdoc} */ public function normalizeUrl(Url $url) { $url->convertToHttps(); $url->removeQueryString(); $url->removeLastSlash(); return $url; } }
gpl-3.0
MrBigBoy/BestilNemt
BestilNemt/WcfService/Properties/AssemblyInfo.cs
1357
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WcfService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WcfService")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f2662365-442d-4cdc-ba64-0cc2d500a3e3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
VKsai/Java-Experiments
LongestSubstring.java
1369
import java.util.*; import java.lang.*; public class LongestSubstring { static int minus = 0; public static int lengthOfLongestSubstring(String s) { if(s.length() == 0) return 0; Hashtable<Integer, Character> ht = new Hashtable<Integer, Character>(); int start = 0; int result = subStringCheck(ht, s, start); return result; } public static int subStringCheck(Hashtable<Integer, Character> t, String s1, int track) { System.out.println(s1.length()); int end = s1.length(); //while(track <= s1.length()) //{ if(t.containsValue(s1.charAt(track)) == false && (track < end-1)) { t.put(track, s1.charAt(track)); track +=1; subStringCheck(t, s1.substring(track), track); //Recursive Call System.out.println("Track1:" +track); } else if(t.containsValue(s1.charAt(track)) == true && (track < end - 1)) { track += 1; subStringCheck(t, s1.substring(track), track); System.out.println("Track2::" +track); minus++; } //} System.out.println("Elements of HashTable are: " +t); return (t.size()-minus); } public static void main(String[] args) { String str = "abcabcbb"; System.out.println("The string is: " +str); int length = lengthOfLongestSubstring(str); System.out.println("Max sub-string is of: " +length); } }
gpl-3.0
fabrimaciel/colosoft
Web/Colosoft.Web.Mvc/XmlNodeChildElementAccessExpressionBuilder.cs
2139
/* * Colosoft Framework - generic framework to assist in development on the .NET platform * Copyright (C) 2013 <http://www.colosoft.com.br/framework> - [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Colosoft.Web.Mvc.Infrastructure.Implementation.Expressions { /// <summary> /// Representa o construtor de expressão de acesso ao elemento filho do nó XML. /// </summary> class XmlNodeChildElementAccessExpressionBuilder : MemberAccessExpressionBuilderBase { /// <summary> /// Método usado para acessar o texto interno do elemento filho. /// </summary> private static readonly System.Reflection.MethodInfo ChildElementInnerTextMethod = typeof(XmlNodeExtensions).GetMethod("ChildElementInnerText", new[] { typeof(System.Xml.XmlNode), typeof(string) }); /// <summary> /// Construtor padrão. /// </summary> /// <param name="memberName"></param> public XmlNodeChildElementAccessExpressionBuilder(string memberName) : base(typeof(System.Xml.XmlNode), memberName) { } /// <summary> /// Cria a expressão de acesso ao membro. /// </summary> /// <returns></returns> public override System.Linq.Expressions.Expression CreateMemberAccessExpression() { var expression = System.Linq.Expressions.Expression.Constant(base.MemberName); return System.Linq.Expressions.Expression.Call(ChildElementInnerTextMethod, base.ParameterExpression, expression); } } }
gpl-3.0
moodlehq/totara
totara/core/js/icon.preview.js
336
$(function() { // Handle icon change preview $('#id_icon').change(function() { var selected = $(this); var src = $('#icon_preview').attr('src'); src = src.replace(/image=(.*?)icons%2F(.*?)(&.*?){0,1}$/, 'image=$1'+'icons%2F'+selected.val()+'$3'); $('#icon_preview').attr('src', src); }); });
gpl-3.0
alevinval/gop
example/glass_actions.go
1232
package main import ( "fmt" "github.com/alevinval/gop" ) const ( EMPTY_GLASS action = iota FILL_GLASS ) type action byte func (a action) PreConditions(world gop.World) []gop.State { switch a { case EMPTY_GLASS: return []gop.State{GLASS_IS_FULL} case FILL_GLASS: return []gop.State{GLASS_IS_EMPTY} default: return []gop.State{} } } func (a action) PostConditions(world gop.World) []gop.State { switch a { case EMPTY_GLASS: return []gop.State{GLASS_IS_EMPTY} case FILL_GLASS: return []gop.State{GLASS_IS_FULL} default: return []gop.State{} } } func (a action) Name() string { switch a { case FILL_GLASS: return "fill-glass" case EMPTY_GLASS: return "empty-glass" default: return "{action not implemented}" } } func (a action) String() string { return a.Name() } type Drink struct { name string } func (d *Drink) Name() string { return fmt.Sprintf("%q drinks", d.name) } func (d *Drink) String() string { return d.Name() } func (d *Drink) PreConditions(world gop.World) []gop.State { return []gop.State{NewPerson(d.name, THIRSTY), GLASS_IS_FULL} } func (d *Drink) PostConditions(world gop.World) []gop.State { return []gop.State{NewPerson(d.name, NOT_THIRSTY), GLASS_IS_EMPTY} }
gpl-3.0
PeerioTechnologies/peerio-client
application/js/peerio/ui/UI.newGhost.js
8230
Peerio.UI.controller('newGhost', function ($scope) { 'use strict'; var g = $scope.newGhost = { recipient: '', selectedFiles: [], sending: false }; g.selectedLocale = null; g.languages = Peerio.PhraseGenerator.languages; g.expiration = 7; $scope.$on('newMessageReset', function () { if (g.sending) return; g.recipient = ''; g.subject = ''; g.body = ''; g.uploadState = null; g.selectedFiles = []; if (g.selectedLocale == null) { g.selectedLocale = Peerio.user.settings && Peerio.user.settings.localeCode || 'en'; if (Peerio.PhraseGenerator.languages.findIndex(i=>i.value === g.selectedLocale) < 0) { g.selectedLocale = 'en'; } } g.refreshPassphrase(); }); $scope.$on('newGhostAttachFileIDs', function (event, ids) { g.attachFileIDs = ids; $('div.attachFile').removeClass('visible'); $('div.newGhost').addClass('visible'); }); g.lintRecipient = function () { if(!g.recipient) return; g.recipient = g.recipient.split(/;|\,| /).filter(item => !!item).reduce((prev, next)=>prev + '; ' + next); }; g.attachFile = function () { $('input.fileSelectDialogGhost').click(); }; g.refreshPassphrase = function () { Peerio.PhraseGenerator.getPassPhrase(g.selectedLocale, 5, function (p) { g.passphrase = p; $scope.$apply(); }); }; $('input.fileSelectDialogGhost').unbind().on('change', function (event) { event.preventDefault(); g.selectedFiles = this.files; $scope.$apply(); return false }); function showUploadErr() { swal({ title: document.l10n.getEntitySync('fileUploadError').value, text: document.l10n.getEntitySync('fileUploadErrorText').value, type: 'error', confirmButtonText: document.l10n.getEntitySync('OK').value }) } function uploadFiles(ghostRecipientKey) { return new Promise(function (resolve, reject) { if (!g.selectedFiles.length) { resolve([]); return; } // validating individual file sizes for (var i = 0; i < g.selectedFiles.length; i++) { var file = g.selectedFiles[i]; if (file.size >= Peerio.config.fileUploadSizeLimit) { swal({ title: document.l10n.getEntitySync('sizeError').value, text: document.l10n.getEntitySync('sizeErrorText').value, type: 'error', confirmButtonText: document.l10n.getEntitySync('OK').value }, function () { reject(); }); return; } } g.uploadState = {}; // uploading var ids = []; var i = 0; function uploadOne() { var file = g.selectedFiles[i]; g.uploadState.file = file.name; g.uploadState.totalFiles = g.selectedFiles.length; g.uploadState.currentFileNum = i + 1; g.uploadState.progress = 0; $scope.$apply(); Peerio.file.uploadGhost(file, ghostRecipientKey, // on progress function (data, progress) { if (hasProp(data, 'error')) { reject(); return; } g.uploadState.progress = progress; $scope.$apply(); }, // on finish function (data) { if (hasProp(data, 'error')) { reject(); return; } ids.push(data.id); i++; if (i === g.selectedFiles.length) { resolve(ids); } else { uploadOne(); } } ) } uploadOne(); }); } g.send = function () { // validating // todo check email regexp if (!g.recipient) { swal({ title: document.l10n.getEntitySync('newGhostRecipientError').value, text: document.l10n.getEntitySync('newGhostRecipientErrorText').value, type: 'error', confirmButtonText: document.l10n.getEntitySync('OK').value }); return false; } if (!g.subject) { g.subject = ''; } if (!g.body) { g.body = '' } g.sending = true; // generating keys var ghostID = Base58.encode(nacl.randomBytes(32)); var publicKey; miniLock.crypto.getKeyPair(g.passphrase, ghostID, function (keyPair) { publicKey = miniLock.crypto.getMiniLockID(keyPair.publicKey); // uploading files uploadFiles(publicKey) .then(function (ids) { // sending the ghost return sendGhost(ghostID, publicKey, ids); }, function () { showUploadErr(); g.sending = false; g.uploadState = null; $scope.$apply(); }) .then(function () { g.sending = false; g.uploadState = null; $scope.$root.$broadcast('frontModalsClose', null); $scope.$root.$broadcast('newMessageReset', null); $scope.$apply(); }, function (err) { console.error(err); swal({ title: document.l10n.getEntitySync('newGhostSendError').value, text: document.l10n.getEntitySync('newGhostSendErrorText').value, type: 'error', confirmButtonText: document.l10n.getEntitySync('OK').value }); g.sending = false; g.uploadState = null; $scope.$apply(); }); }); }; function sendGhost(id, pk, ids) { return new Promise(function (resolve, reject) { var files = []; for (var i = 0; i < g.selectedFiles.length; i++) { var info = g.selectedFiles[i]; files.push({id: ids[i], name: info.name, size: info.size, type: info.type}); } var ghostMsg = { id: id, recipient: g.recipient, subject: g.subject, message: g.body, files: files, timestamp: Date.now(), passphrase: g.passphrase, lifeSpanInSeconds: (+g.expiration) * 60 * 60 * 24 }; Peerio.crypto.encryptMessage(ghostMsg, pk, function (header, body) { if (!header || !body) { reject(); return; } var ghost = { ghostID: id, publicKey: pk, lifeSpanInSeconds: ghostMsg.lifeSpanInSeconds, recipients: g.recipient.split('; '), version: '1.0.0', files: ids, header: header, body: body }; Peerio.network.sendGhost(ghost, function (res) { if (res && res.error) { reject(res); } else resolve(); }); }); }); } });
gpl-3.0
joomlatools/joomlatools-framework
code/libraries/joomlatools/library/object/interface.php
2011
<?php /** * Joomlatools Framework - https://www.joomlatools.com/developer/framework/ * * @copyright Copyright (C) 2007 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/joomlatools/joomlatools-framework for the canonical source repository */ /** * Object Interface * * @author Johan Janssens <https://github.com/johanjanssens> * @package Koowa\Library\Object */ interface KObjectInterface { /** * Constructor. * * @param KObjectConfig $config Configuration options */ //public function __construct(KObjectConfig $config); /** * Get an instance of a class based on a class identifier only creating it if it does not exist yet. * * @param string|object $identifier The class identifier or identifier object * @param array $config An optional associative array of configuration settings. * @throws RuntimeException if the object manager has not been defined. * @return object Return object on success, throws exception on failure * @see KObjectInterface */ public function getObject($identifier, array $config = array()); /** * Gets the object identifier. * * @param null|KObjectIdentifier|string $identifier Identifier * @return KObjectIdentifier * * @see KObjectInterface * @throws RuntimeException if the object manager has not been defined. */ public function getIdentifier($identifier = null); /** * Get the object configuration * * If no identifier is passed the object config of this object will be returned. Function recursively * resolves identifier aliases and returns the aliased identifier. * * @param string|object $identifier A valid identifier string or object implementing ObjectInterface * @return KObjectConfig */ public function getConfig($identifier = null); }
gpl-3.0
mariniere/nanahira
jpnum.py
901
#jpnum.py v0.01 NUMS = { 1: u"一",2: u"二",3: u"三",4: u"四",5: u"五",6: u"六",7: u"七",8: u"八",9: u"九",10: u"十", 100: u"百",1000: u"千",10000: u"万" } def convert(string): block = False for i in str(string): try: int(i) except Exception as e: block = True raise if not block: if int(string) in NUMS: return NUMS[int(string)] else: if len(str(string)) in (2,3,4): final = "" LENGTH = len(str(string)) if LENGTH <= 5: for i in str(string): if int(i) not in (0,1): final += NUMS[int(i)] if LENGTH > 1: final += NUMS[10**(LENGTH-1)] LENGTH -= 1 return final
gpl-3.0
wolfbane8653/fogproject
packages/web/lib/fog/ScheduledTaskManager.class.php
66
<?php class ScheduledTaskManager extends FOGManagerController { }
gpl-3.0
goday-org/learnPython
src/Numbers.py
136
# -*- coding: utf-8 -*- ''' Created on May 3, 2014 @author: andy ''' #int long float bool complex if __name__ == '__main__': pass
gpl-3.0
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/new/php-5.2.5/ext/standard/tests/file/stat_error-win32.phpt
1333
--TEST-- Test stat() function: error conditions --SKIPIF-- <?php if (substr(PHP_OS, 0, 3) != 'WIN') { die('skip.. only for Windows'); } ?> --FILE-- <?php /* Prototype: array stat ( string $filename ); Description: Gives information about a file */ $file_path = dirname(__FILE__); $arr = array(__FILE__); echo "\n*** Testing stat() for error conditions ***\n"; var_dump( stat() ); // args < expected var_dump( stat(__FILE__, 2) ); // file, args > expected var_dump( stat(dirname(__FILE__), 2) ); //dir, args > expected var_dump( stat("$file_path/temp.tmp") ); // non existing file var_dump( stat("$file_path/temp/") ); // non existing dir var_dump( stat(22) ); // scalar argument var_dump( stat($arr) ); // array argument echo "Done\n"; ?> --EXPECTF-- *** Testing stat() for error conditions *** Warning: Wrong parameter count for stat() in %s on line %d NULL Warning: Wrong parameter count for stat() in %s on line %d NULL Warning: Wrong parameter count for stat() in %s on line %d NULL Warning: stat(): stat failed for %s in %s on line %d bool(false) Warning: stat(): stat failed for %s in %s on line %d bool(false) Warning: stat(): stat failed for 22 in %s on line %d bool(false) Notice: Array to string conversion in %s on line %d Warning: stat(): stat failed for Array in %s on line %d bool(false) Done
gpl-3.0
tomarch/librenms
html/legacy_api_v0.php
13343
<?php /* * LibreNMS * * Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ $init_modules = array('web', 'alerts'); require realpath(__DIR__ . '/..') . '/includes/init.php'; use LibreNMS\Config; $app = new \Slim\Slim(); if (Config::get('api.cors.enabled') === true) { $corsOptions = array( "origin" => Config::get('api.cors.origin'), "maxAge" => Config::get('api.cors.maxage'), "allowMethods" => Config::get('api.cors.allowmethods'), "allowHeaders" => Config::get('api.cors.allowheaders'), ); $cors = new \CorsSlim\CorsSlim($corsOptions); $app->add($cors); } require $config['install_dir'] . '/html/includes/api_functions.inc.php'; $app->setName('api'); $app->notFound(function () use ($app) { api_error(404, "This API route doesn't exist."); }); $app->group( '/api', function () use ($app) { $app->group( '/v0', function () use ($app) { $app->get('/system', 'authToken', 'server_info')->name('server_info'); $app->get('/bgp', 'authToken', 'list_bgp')->name('list_bgp'); $app->get('/bgp/:id', 'authToken', 'get_bgp')->name('get_bgp'); $app->get('/ospf', 'authToken', 'list_ospf')->name('list_ospf'); // api/v0/bgp $app->get('/oxidized(/:hostname)', 'authToken', 'list_oxidized')->name('list_oxidized'); $app->group( '/devices', function () use ($app) { $app->delete('/:hostname', 'authToken', 'del_device')->name('del_device'); // api/v0/devices/$hostname $app->get('/:hostname', 'authToken', 'get_device')->name('get_device'); // api/v0/devices/$hostname $app->patch('/:hostname', 'authToken', 'update_device')->name('update_device_field'); $app->patch('/:hostname/rename/:new_hostname', 'authToken', 'rename_device')->name('rename_device'); $app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans'); // api/v0/devices/$hostname/vlans $app->get('/:hostname/links', 'authToken', 'list_links')->name('get_links'); // api/v0/devices/$hostname/links $app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs'); // api/v0/devices/$hostname/graphs $app->get('/:hostname/health(/:type)(/:sensor_id)', 'authToken', 'list_available_health_graphs')->name('list_available_health_graphs'); $app->get('/:hostname/wireless(/:type)(/:sensor_id)', 'authToken', 'list_available_wireless_graphs')->name('list_available_wireless_graphs'); $app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs'); $app->get('/:hostname/ip', 'authToken', 'get_ip_addresses')->name('get_device_ip_addresses'); $app->get('/:hostname/port_stack', 'authToken', 'get_port_stack')->name('get_port_stack'); // api/v0/devices/$hostname/ports $app->get('/:hostname/components', 'authToken', 'get_components')->name('get_components'); $app->post('/:hostname/components/:type', 'authToken', 'add_components')->name('add_components'); $app->put('/:hostname/components', 'authToken', 'edit_components')->name('edit_components'); $app->delete('/:hostname/components/:component', 'authToken', 'delete_components')->name('delete_components'); $app->get('/:hostname/groups', 'authToken', 'get_device_groups')->name('get_device_groups'); $app->get('/:hostname/graphs/health/:type(/:sensor_id)', 'authToken', 'get_graph_generic_by_hostname')->name('get_health_graph'); $app->get('/:hostname/graphs/wireless/:type(/:sensor_id)', 'authToken', 'get_graph_generic_by_hostname')->name('get_wireless_graph'); $app->get('/:hostname/:type', 'authToken', 'get_graph_generic_by_hostname')->name('get_graph_generic_by_hostname'); // api/v0/devices/$hostname/$type $app->get('/:hostname/ports/:ifname', 'authToken', 'get_port_stats_by_port_hostname')->name('get_port_stats_by_port_hostname'); // api/v0/devices/$hostname/ports/$ifName $app->get('/:hostname/ports/:ifname/:type', 'authToken', 'get_graph_by_port_hostname')->name('get_graph_by_port_hostname'); // api/v0/devices/$hostname/ports/$ifName/$type } ); $app->get('/devices', 'authToken', 'list_devices')->name('list_devices'); // api/v0/devices $app->post('/devices', 'authToken', 'add_device')->name('add_device'); // api/v0/devices (json data needs to be passed) $app->group( '/devicegroups', function () use ($app) { $app->get('/:name', 'authToken', 'get_devices_by_group')->name('get_devices_by_group'); } ); $app->get('/devicegroups', 'authToken', 'get_device_groups')->name('get_devicegroups'); $app->group( '/ports', function () use ($app) { $app->get('/:portid', 'authToken', 'get_port_info')->name('get_port_info'); $app->get('/:portid/ip', 'authToken', 'get_ip_addresses')->name('get_port_ip_info'); } ); $app->get('/ports', 'authToken', 'get_all_ports')->name('get_all_ports'); $app->group( '/portgroups', function () use ($app) { $app->get('/multiport/bits/:id', 'authToken', 'get_graph_by_portgroup')->name('get_graph_by_portgroup_multiport_bits'); $app->get('/:group', 'authToken', 'get_graph_by_portgroup')->name('get_graph_by_portgroup'); } ); $app->group( '/bills', function () use ($app) { $app->get('/:bill_id', 'authToken', 'list_bills')->name('get_bill'); $app->delete('/:id', 'authToken', 'delete_bill')->name('delete_bill'); // api/v0/bills/$bill_id $app->get('/:bill_id/graphs/:graph_type', 'authToken', 'get_bill_graph')->name('get_bill_graph'); $app->get('/:bill_id/graphdata/:graph_type', 'authToken', 'get_bill_graphdata')->name('get_bill_graphdata'); $app->get('/:bill_id/history', 'authToken', 'get_bill_history')->name('get_bill_history'); $app->get('/:bill_id/history/:bill_hist_id/graphs/:graph_type', 'authToken', 'get_bill_history_graph')->name('get_bill_history_graph'); $app->get('/:bill_id/history/:bill_hist_id/graphdata/:graph_type', 'authToken', 'get_bill_history_graphdata')->name('get_bill_history_graphdata'); } ); $app->get('/bills', 'authToken', 'list_bills')->name('list_bills'); $app->post('/bills', 'authToken', 'create_edit_bill')->name('create_bill'); // api/v0/bills // /api/v0/alerts $app->group( '/alerts', function () use ($app) { $app->get('/:id', 'authToken', 'list_alerts')->name('get_alert'); // api/v0/alerts $app->put('/:id', 'authToken', 'ack_alert')->name('ack_alert'); // api/v0/alerts/$id (PUT) $app->put('/unmute/:id', 'authToken', 'unmute_alert')->name('unmute_alert'); // api/v0/alerts/unmute/$id (PUT) } ); $app->get('/alerts', 'authToken', 'list_alerts')->name('list_alerts'); // api/v0/alerts // /api/v0/rules $app->group( '/rules', function () use ($app) { $app->get('/:id', 'authToken', 'list_alert_rules')->name('get_alert_rule'); // api/v0/rules/$id $app->delete('/:id', 'authToken', 'delete_rule')->name('delete_rule'); // api/v0/rules/$id (DELETE) } ); $app->get('/rules', 'authToken', 'list_alert_rules')->name('list_alert_rules'); // api/v0/rules $app->post('/rules', 'authToken', 'add_edit_rule')->name('add_rule'); // api/v0/rules (json data needs to be passed) $app->put('/rules', 'authToken', 'add_edit_rule')->name('edit_rule'); // api/v0/rules (json data needs to be passed) // Inventory section $app->group( '/inventory', function () use ($app) { $app->get('/:hostname', 'authToken', 'get_inventory')->name('get_inventory'); } ); // End Inventory // Routing section $app->group( '/routing', function () use ($app) { $app->get('/bgp/cbgp', 'authToken', 'list_cbgp')->name('list_cbgp'); $app->get('/vrf', 'authToken', 'list_vrf')->name('list_vrf'); $app->get('/vrf/:id', 'authToken', 'get_vrf')->name('get_vrf'); $app->group( '/ipsec', function () use ($app) { $app->get('/data/:hostname', 'authToken', 'list_ipsec')->name('list_ipsec'); } ); } ); // End Routing // Resources section $app->group( '/resources', function () use ($app) { $app->get('/links', 'authToken', 'list_links')->name('list_links'); $app->get('/links/:id', 'authToken', 'get_link')->name('get_link'); $app->get('/locations', 'authToken', 'list_locations')->name('list_locations'); $app->get('/sensors', 'authToken', 'list_sensors')->name('list_sensors'); $app->get('/vlans', 'authToken', 'list_vlans')->name('list_vlans'); $app->group( '/ip', function () use ($app) { $app->get('/addresses/', 'authToken', 'list_ip_addresses')->name('list_ip_addresses'); $app->get('/arp/:ip', 'authToken', 'list_arp')->name('list_arp')->conditions(array('ip' => '[^?]+')); $app->get('/networks/', 'authToken', 'list_ip_networks')->name('list_ip_networks'); $app->get('/networks/:id/ip', 'authToken', 'get_ip_addresses')->name('get_network_ip_addresses'); } ); } ); // End Resources // Service section $app->group( '/services', function () use ($app) { $app->get('/:hostname', 'authToken', 'list_services')->name('get_service_for_host'); $app->post('/:hostname', 'authToken', 'add_service_for_host')->name('add_service_for_host'); } ); $app->get('/services', 'authToken', 'list_services')->name('list_services'); // End Service $app->group( '/logs', function () use ($app) { $app->get('/eventlog(/:hostname)', 'authToken', 'list_logs')->name('list_eventlog'); $app->get('/syslog(/:hostname)', 'authToken', 'list_logs')->name('list_syslog'); $app->get('/alertlog(/:hostname)', 'authToken', 'list_logs')->name('list_alertlog'); $app->get('/authlog(/:hostname)', 'authToken', 'list_logs')->name('list_authlog'); } ); } ); $app->get('/v0', 'authToken', 'show_endpoints'); // api/v0 } ); $app->run();
gpl-3.0
gabrielfalcao/carpentry
tests/functional/test_api.py
15018
#!/usr/bin/env python # -*- coding: utf-8 -*- # import httpretty import uuid import json from carpentry.models import Builder, CarpentryPreference, Build from .helpers import api @api def test_create_builder(context): ('POST to /api/builder should create a builder') context.github.on_post( path='/repos/gabrielfalcao/lettuce/hooks', body=json.dumps({ 'hook_set': True }) ) context.github.on_get( path='/repos/gabrielfalcao/lettuce/hooks', body=json.dumps([ { 'id': 'hookid1', 'config': { 'url': 'https://carpentry.io/hookid1' } } ]) ) context.github.on_delete( path='/repos/gabrielfalcao/lettuce/hook/hookid1', body=json.dumps({'msg': 'hook deleted successfully'}) ) # Given that I POST to /api/builders response = context.http.post( '/api/builder', data=json.dumps({ 'name': 'Device Management [unit tests]', 'git_uri': '[email protected]:gabrielfalcao/lettuce.git', 'shell_script': 'make test', 'id_rsa_private': 'the private key', 'id_rsa_public': 'the public key', }), headers=context.headers, ) # Then the response should be 200 response.status_code.should.equal(200) # And it should be a json data = json.loads(response.data) builder_id = data.pop('id', None) data.should.equal({ u'branch': u'', u'build_timeout_in_seconds': 0, u'creator': { u'carpentry_token': bytes(context.user.carpentry_token), u'email': u'', u'github_access_token': u'Default:FAKE:Token', u'github_metadata': { u'avatar_url': u'https://github.com/images/error/octocat_happy.gif', u'bio': u'There once was...', u'blog': u'https://github.com/blog', u'collaborators': 8, u'company': u'GitHub', u'created_at': u'2008-01-14T04:33:35Z', u'disk_usage': 10000, u'email': u'[email protected]', u'events_url': u'https://api.github.com/users/octocat/events{/privacy}', u'followers': 20, u'followers_url': u'https://api.github.com/users/octocat/followers', u'following': 0, u'following_url': u'https://api.github.com/users/octocat/following{/other_user}', u'gists_url': u'https://api.github.com/users/octocat/gists{/gist_id}', u'gravatar_id': u'', u'hireable': False, u'html_url': u'https://github.com/octocat', u'id': 1, u'location': u'San Francisco', u'login': u'octocat', u'name': u'monalisa octocat', u'organizations': [{u'login': u'cnry'}], u'organizations_url': u'https://api.github.com/users/octocat/orgs', u'owned_private_repos': 100, u'plan': { u'collaborators': 0, u'name': u'Medium', u'private_repos': 20, u'space': 400 }, u'private_gists': 81, u'public_gists': 1, u'public_repos': 2, u'received_events_url': u'https://api.github.com/users/octocat/received_events', u'repos_url': u'https://api.github.com/users/octocat/repos', u'site_admin': False, u'starred_url': u'https://api.github.com/users/octocat/starred{/owner}{/repo}', u'subscriptions_url': u'https://api.github.com/users/octocat/subscriptions', u'total_private_repos': 100, u'type': u'User', u'updated_at': u'2008-01-14T04:33:35Z', u'url': u'https://api.github.com/users/octocat' }, u'id': bytes(context.user.id), u'name': u'' }, u'css_status': u'success', u'git_clone_timeout_in_seconds': 0, u'git_uri': u'[email protected]:gabrielfalcao/lettuce.git', u'github_hook_data': u'{"hook_set": true}', u'github_hook_url': u'http://localhost:5000/api/hooks/{0}'.format(builder_id), u'json_instructions': u'', u'last_build': None, u'name': u'Device Management [unit tests]', u'shell_script': u'make test', u'slug': u'devicemanagementunittests', u'status': u'ready' }) builder_id.should_not.be.none # And it should be in the list of builders results = list(Builder.objects.all()) # Then it should have one result results.should.have.length_of(1) # And that one result should match the created Builder builder = results[0] builder.should.have.property('name').being.equal( 'Device Management [unit tests]') builder.should.have.property('git_uri').being.equal( '[email protected]:gabrielfalcao/lettuce.git') builder.should.have.property('shell_script').being.equal('make test') builder.should.have.property( 'id_rsa_private').being.equal('the private key') builder.should.have.property('id_rsa_public').being.equal('the public key') builder.should.have.property('status').being.equal('ready') @api def test_set_preferences(context): ('POST to /api/preferences should set multiple preferences') # And I POST to /api/builders response = context.http.post( '/api/preferences', data=json.dumps({ 'docker_registry_url': 'https://docker.cnry.io', 'global_id_rsa_private_key': 'the private key', 'global_id_rsa_public_key': 'the public key', }), headers=context.headers, ) # Then the response should be 200 response.status_code.should.equal(200) # And it should be a json data = json.loads(response.data) data.should.equal({ 'docker_registry_url': 'https://docker.cnry.io', 'global_id_rsa_private_key': 'the private key', 'global_id_rsa_public_key': 'the public key', }) # And it should be in the list of preferences results = list(CarpentryPreference.objects.all()) # Then it should have one result results.should.have.length_of(3) @api def test_list_builders(context): ('GET on /api/builders should list existing builders') # Givent that there are 3 builders Builder.create( id=uuid.uuid1(), name=u'Builder 1', git_uri='1-git-url-one', shell_script='make test', ) Builder.create( id=uuid.uuid1(), name=u'Builder 2', git_uri='2-git-url-one', shell_script='make test', ) Builder.create( id=uuid.uuid1(), name=u'Builder 3', git_uri='3-git-url-one', shell_script='make test', ) # And I GET on /api/builders response = context.http.get( '/api/builders', headers=context.headers, ) # Then the response should be 200 response.status_code.should.equal(200) # And it should be a json data = json.loads(response.data) data.should.be.a(list) data.should.have.length_of(3) # And there are also 3 items in the database Builder.objects.all().should.have.length_of(3) @api def test_delete_builder(context): ('DELETE to /api/builder should delete a builder') # Given a builder that there are 3 builders bd1 = Builder.create( id=uuid.uuid1(), name='Device Management [unit tests]', git_uri='[email protected]:gabrielfalcao/lettuce.git', shell_script='make test', creator_user_id=context.user.id ) # And I DELETE to /api/builders response = context.http.delete( '/api/builder/{0}'.format(bd1.id), headers=context.headers, ) # Then the response should be 200 response.status_code.should.equal(200) # And it should be a json data = json.loads(response.data) builder_id = data.pop('id', None) data.should.equal({ 'branch': u'', u'build_timeout_in_seconds': 0, u'css_status': u'success', u'git_clone_timeout_in_seconds': 0, u'git_uri': u'[email protected]:gabrielfalcao/lettuce.git', u'github_hook_data': u'', u'github_hook_url': u'http://localhost:5000/api/hooks/{0}'.format(builder_id), u'json_instructions': u'', u'last_build': None, u'name': u'Device Management [unit tests]', u'shell_script': u'make test', u'slug': u'devicemanagementunittests', u'status': u'', 'creator': None }) builder_id.should_not.be.none # And it should be in the list of builders results = list(Builder.objects.all()) # Then it should have no results results.should.be.empty @api def test_create_build_instance_from_builder(context): ('POST to /api/builder/uuid/build should create a new build and scheduler it') context.github.on_post( path='/repos/gabrielfalcao/lettuce/hooks', body=json.dumps({ 'hook_set': True }) ) # Given a builder that there are 3 builders bd1 = Builder.create( id=uuid.uuid1(), name='Device Management [unit tests]', git_uri='[email protected]:gabrielfalcao/lettuce.git', shell_script='make test', status='ready', creator=context.user, ) # And I POST on /api/builder/uuid/build response = context.http.post( '/api/builder/{0}/build'.format(bd1.id), data=json.dumps({ 'author_name': 'Gabriel', 'author_email': '[email protected]', 'commit': 'oooo', }), headers=context.headers, ) # Then the response should be 200 response.status_code.should.equal(200) # And it should be a json data = json.loads(response.data) build_id = data.pop('id', None) builder_id = data.get('builder', {}).get('id', None) date_created = data.pop('date_created', None) data.should.equal({ u'author_email': u'[email protected]', u'author_gravatar_url': u'https://s.gravatar.com/avatar/3fa0df5c54f5ac0f8652d992d7d24039', u'author_name': u'Gabriel', u'branch': u'master', u'builder': { u'branch': u'', u'build_timeout_in_seconds': 0, u'creator': { u'carpentry_token': bytes(context.user.carpentry_token), u'email': u'', u'github_access_token': u'Default:FAKE:Token', u'github_metadata': u'', u'id': bytes(context.user.id), u'name': u'', }, u'git_clone_timeout_in_seconds': 0, u'git_uri': u'[email protected]:gabrielfalcao/lettuce.git', u'github_hook_data': u'', u'id': bytes(bd1.id), u'id_rsa_private': u'', u'id_rsa_public': u'', u'json_instructions': u'', u'name': u'Device Management [unit tests]', u'shell_script': u'make test', u'status': u'ready' }, u'code': 0, u'commit': u'', u'commit_message': u'', u'css_status': u'success', u'date_finished': None, u'docker_status': {}, u'git_uri': u'[email protected]:gabrielfalcao/lettuce.git', u'github_repo_info': { u'name': u'lettuce', u'owner': u'gabrielfalcao' }, u'github_status_data': u'', u'github_webhook_data': u'', u'status': u'ready', u'stderr': u'', u'stdout': u'' }) build_id.should_not.be.none date_created.should_not.be.none # And it should be in the list of builders results = list(Build.objects.all()) # Then it should have one result results.should.have.length_of(1) # And that one result should match the edited Builder build = results[0] builder_id.should.equal(str(bd1.id)) build.should.have.property('stderr').being.equal('') build.should.have.property('stdout').being.equal('') build.should.have.property('code').being.equal(0) build.should.have.property('status').being.equal('ready') @api def test_edit_builder(context): ('PUT to /api/builder should edit a builder') context.github.on_post( path='/repos/gabrielfalcao/lettuce/hooks', body=json.dumps({ 'hook_set': True }) ) context.github.on_get( path='/repos/gabrielfalcao/lettuce/hooks', body=json.dumps([ { 'id': 'hookid1', 'config': { 'url': 'https://carpentry.io/hookid1' } } ]) ) # Given a builder that there are 3 builders bd1 = Builder.create( id=uuid.uuid1(), name=u'Lettuce', git_uri='[email protected]:gabrielfalcao/lettuce.git', shell_script='make unit', status='ready' ) # And I PUT on /api/builders response = context.http.put( '/api/builder/{0}'.format(bd1.id), data=json.dumps({ 'shell_script': 'make unit', 'id_rsa_private': 'the private key', 'id_rsa_public': 'the public key', }), headers=context.headers, ) # Then the response should be 200 response.status_code.should.equal(200) # And it should be a json data = json.loads(response.data) builder_id = data.pop('id', None) data.should.equal({ u'branch': u'', u'build_timeout_in_seconds': 0, u'creator': None, u'css_status': u'success', u'git_clone_timeout_in_seconds': 0, u'git_uri': u'[email protected]:gabrielfalcao/lettuce.git', u'github_hook_data': u'{"hook_set": true}', u'github_hook_url': u'http://localhost:5000/api/hooks/{0}'.format(builder_id), u'json_instructions': u'', u'last_build': None, u'name': u'Lettuce', u'shell_script': u'make unit', u'slug': u'lettuce', u'status': u'ready' }) builder_id.should_not.be.none # And it should be in the list of builders results = list(Builder.objects.all()) # Then it should have one result results.should.have.length_of(1) # And that one result should match the edited Builder builder = results[0] builder.should.have.property('name').being.equal( 'Lettuce') builder.should.have.property('git_uri').being.equal( '[email protected]:gabrielfalcao/lettuce.git') builder.should.have.property('shell_script').being.equal('make unit') builder.should.have.property( 'id_rsa_private').being.equal('the private key') builder.should.have.property('id_rsa_public').being.equal('the public key') builder.should.have.property('status').being.equal('ready')
gpl-3.0
sio2project/oioioi
oioioi/participants/apps.py
109
from django.apps import AppConfig class ParticipantsAppConfig(AppConfig): name = "oioioi.participants"
gpl-3.0
Angerona/angerona-framework
simple/src/main/java/com/github/angerona/fw/simple/operators/ExecuteOperator.java
2060
package com.github.angerona.fw.simple.operators; import java.util.List; import com.github.angerona.fw.Action; import com.github.angerona.fw.Agent; import com.github.angerona.fw.Intention; import com.github.angerona.fw.PlanElement; import com.github.angerona.fw.Subgoal; import com.github.angerona.fw.am.secrecy.operators.parameter.PlanParameter; import com.github.angerona.fw.operators.Operator; import com.github.angerona.fw.simple.operators.parameter.SimplePlanParameter; import com.github.angerona.fw.util.Pair; /** * I decided to add an ExecuteOperator, that realizes the * ActionSelectionFunction from the BDI-Architecture, because apparently it has * not been implemented yet. * * @author Manuel Barbi * */ public class ExecuteOperator extends Operator<Agent, PlanParameter, Void> { public static final String OPERATION_TYPE = "Execute"; @Override public Pair<String, Class<?>> getOperationType() { return new Pair<String, Class<?>>(OPERATION_TYPE, ExecuteOperator.class); } @Override protected PlanParameter getEmptyParameter() { return new SimplePlanParameter(); } @Override protected Void processImpl(PlanParameter param) { List<Subgoal> plans = param.getActualPlan().getPlans(); if (!plans.isEmpty()) { if (!sweep(plans.get(0), param)) { param.report("agent has decided to wait"); } } else { param.report("no plans executable"); } return null; } /** * search in chronological order for the first Intention, that is and Action * and execute it */ protected boolean sweep(Intention intention, PlanParameter param) { if (intention instanceof Action) { param.getAgent().performAction((Action) intention); return true; } else if (intention instanceof Subgoal) { Subgoal sub = (Subgoal) intention; for (int i = 0; i < sub.getNumberOfStacks(); i++) { for (PlanElement elem : sub.getStack(i)) { if (sweep(elem.getIntention(), param)) { return true; } } } } return false; } @Override protected Void defaultReturnValue() { return null; } }
gpl-3.0
monocasual/giada-www
src/forum/vendor/s9e/text-formatter/src/Plugins/Litedown/Parser/ParsedText.php
4683
<?php /** * @package s9e\TextFormatter * @copyright Copyright (c) 2010-2019 The s9e Authors * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace s9e\TextFormatter\Plugins\Litedown\Parser; class ParsedText { /** * @var bool Whether to decode HTML entities when decoding text */ public $decodeHtmlEntities = false; /** * @var bool Whether text contains escape characters */ protected $hasEscapedChars = false; /** * @var bool Whether text contains link references */ public $hasReferences = false; /** * @var array Array of [label => link info] */ public $linkReferences = []; /** * @var string Text being parsed */ protected $text; /** * @param string $text Original text */ public function __construct($text) { if (strpos($text, '\\') !== false && preg_match('/\\\\[!"\'()*[\\\\\\]^_`~]/', $text)) { $this->hasEscapedChars = true; // Encode escaped literals that have a special meaning otherwise, so that we don't have // to take them into account in regexps $text = strtr( $text, [ '\\!' => "\x1B0", '\\"' => "\x1B1", "\\'" => "\x1B2", '\\(' => "\x1B3", '\\)' => "\x1B4", '\\*' => "\x1B5", '\\[' => "\x1B6", '\\\\' => "\x1B7", '\\]' => "\x1B8", '\\^' => "\x1B9", '\\_' => "\x1BA", '\\`' => "\x1BB", '\\~' => "\x1BC" ] ); } // We append a couple of lines and a non-whitespace character at the end of the text in // order to trigger the closure of all open blocks such as quotes and lists $this->text = $text . "\n\n\x17"; } /** * @return string */ public function __toString() { return $this->text; } /** * Return the character at given position * * @param integer $pos * @return string */ public function charAt($pos) { return $this->text[$pos]; } /** * Decode a chunk of encoded text to be used as an attribute value * * Decodes escaped literals and removes slashes and 0x1A characters * * @param string $str Encoded text * @return string Decoded text */ public function decode($str) { if ($this->decodeHtmlEntities && strpos($str, '&') !== false) { $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8'); } $str = str_replace("\x1A", '', $str); if ($this->hasEscapedChars) { $str = strtr( $str, [ "\x1B0" => '!', "\x1B1" => '"', "\x1B2" => "'", "\x1B3" => '(', "\x1B4" => ')', "\x1B5" => '*', "\x1B6" => '[', "\x1B7" => '\\', "\x1B8" => ']', "\x1B9" => '^', "\x1BA" => '_', "\x1BB" => '`', "\x1BC" => '~' ] ); } return $str; } /** * Find the first occurence of given substring starting at given position * * @param string $str * @param integer $pos * @return bool|integer */ public function indexOf($str, $pos = 0) { return strpos($this->text, $str, $pos); } /** * Test whether given position is preceded by whitespace * * @param integer $pos * @return bool */ public function isAfterWhitespace($pos) { return ($pos > 0 && $this->isWhitespace($this->text[$pos - 1])); } /** * Test whether given character is alphanumeric * * @param string $chr * @return bool */ public function isAlnum($chr) { return (strpos(' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', $chr) > 0); } /** * Test whether given position is followed by whitespace * * @param integer $pos * @return bool */ public function isBeforeWhitespace($pos) { return $this->isWhitespace($this->text[$pos + 1]); } /** * Test whether a length of text is surrounded by alphanumeric characters * * @param integer $pos Start of the text * @param integer $len Length of the text * @return bool */ public function isSurroundedByAlnum($pos, $len) { return ($pos > 0 && $this->isAlnum($this->text[$pos - 1]) && $this->isAlnum($this->text[$pos + $len])); } /** * Test whether given character is an ASCII whitespace character * * NOTE: newlines are normalized to LF before parsing so we don't have to check for CR * * @param string $chr * @return bool */ public function isWhitespace($chr) { return (strpos(" \n\t", $chr) !== false); } /** * Mark the boundary of a block in the original text * * @param integer $pos * @return void */ public function markBoundary($pos) { $this->text[$pos] = "\x17"; } /** * Overwrite part of the text with substitution characters ^Z (0x1A) * * @param integer $pos Start of the range * @param integer $len Length of text to overwrite * @return void */ public function overwrite($pos, $len) { if ($len > 0) { $this->text = substr($this->text, 0, $pos) . str_repeat("\x1A", $len) . substr($this->text, $pos + $len); } } }
gpl-3.0
wvangeit/AllenSDK
doc_template/examples/data_api_client_ex2.py
197
from gene_acronym_query import GeneAcronymQuery query = GeneAcronymQuery() gene_info = query.get_data('ABAT') for gene in gene_info: print "%s (%s)" % (gene['name'], gene['organism']['name'])
gpl-3.0
thecreamedcorn/city-scape
src/View/RenderLine.java
2709
/* city-scape: a 3d scene of a city soft rendered in java Copyright (C) 2017 Wil Gaboury This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/ */ package View; import Model.Point3D; import Model.TransformationMatrix; import java.util.ArrayList; import java.util.Collection; /** * Created by 18wgaboury on 4/21/2017. */ public class RenderLine implements Cloneable { private Point3D point1; private Point3D point2; private double thickness; private int color; public RenderLine(Point3D point1, Point3D point2, double thickness, int color) { this.point1 = point1; this.point2 = point2; this.color = color; this.thickness = thickness; } public RenderLine() { this.point1 = new Point3D(0,0,0); this.point2 = new Point3D(0,0,0); } public Collection<Point3D> getPoints() { ArrayList<Point3D> points = new ArrayList<>(); points.add(point1); points.add(point2); return points; } void setPoints(Point3D point1, Point3D point2) { this.point1 = point1; this.point2 = point2; } public void setColor(int color) { this.color = color; } public int getColor() { return color; } public double getThickness() { return thickness; } public double getXYSlope() { return (point1.getY() - point2.getY()) / (point1.getX() - point2.getX()); } public Point3D getPoint1() { return point1; } public void setPoint1(Point3D point1) { this.point1 = point1; } public Point3D getPoint2() { return point2; } public void setPoint2(Point3D point2) { this.point2 = point2; } public String toString() { return "{" + point1 + ", " + point2 + "}"; } public RenderLine apply(TransformationMatrix m) { point1.apply(m); point2.apply(m); return this; } public RenderLine compound(TransformationMatrix m) { RenderLine result = new RenderLine(); result.color = color; result.thickness = thickness; result.point1 = point1.clone().apply(m); result.point2 = point2.clone().apply(m); return result; } public RenderLine clone() { try { return (RenderLine) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } }
gpl-3.0
matxin/matxin-lineariser
matxin_lineariser/utlgrammars/word.py
2589
from .printing import Printing class Word: def __init__(self, upostag): self.upostag = upostag self.feats = frozenset({}) self.lemma = None def add_lemma(self, lemma): self.lemma = lemma @classmethod def deserialise(cls, node_etree): upostag = node_etree.get('pos') feats = node_etree.get('feats') word = Word(upostag) word.parse_feats(feats) word.add_lemma(node_etree.get('lem')) return word def parse_feats(self, feats): if feats is None: self.feats = frozenset({}) else: self.feats = frozenset( tuple(feat.split('=')) for feat in feats.split('|')) def __hash__(self): return hash((self.get_upostag(), )) def get_upostag(self): return self.upostag def get_lemma(self): return self.lemma def __eq__(self, other): return isinstance(other, Word) and self.get_upostag( ) == other.get_upostag() and self.get_feats() == other.get_feats( ) and self.get_lemma() == other.get_lemma() def get_feats(self): return self.feats def __lt__(self, other): if not isinstance(other, Word): raise TypeError if self.get_upostag() != other.get_upostag(): return self.get_upostag() < other.get_upostag() if len(self.get_feats()) != 0 and len(other.get_feats()) != 0: if self.get_feats() != other.get_feats(): return self.get_feats() < other.get_feats() if self.get_lemma() is not None and other.get_lemma() is not None: if self.get_lemma() != other.get_lemma(): return self.get_lemma() < other.get_lemma() return False def __str__(self): return Printing.get_module_qualname(self) + ' = {\n' + \ ' upostag = ' + repr(self.get_upostag()) + '\n' + \ ' feats = ' + Printing.shift_str(Printing.print_list(self.get_feats(), print_item=Printing.print_tuple)) + '\n' + \ ' lemma = ' + repr(self.get_lemma()) + '\n' + \ '}' def word_eq(a, b): if not (isinstance(a, Word) and isinstance(b, Word)): return False if a.get_upostag() != b.get_upostag(): return False if len(a.get_feats()) != 0 and len(b.get_feats()) != 0: if a.get_feats() != b.get_feats(): return False if a.get_lemma() is not None and b.get_lemma() is not None: if a.get_lemma() != b.get_lemma(): return False return True
gpl-3.0
kareem2048/ADwytee
Code/Application/reservation.php
933
<?php class reservation{ private $file_name= '../../Database/reservation.php'; private $reservation; function __construct() { try { include_once $this->file_name ; } catch (Exception $e) { echo "error"; } $this->reservation = new reservation_Query(); } public function add($userId, $pId, $date) { $this->reservation->add_reservation($userId, $pId, $date); } public function update($id, $date) { $this->reservation->update_reservation($id, $date); } public function delete($id) { $this->reservation->delete_reservation($id); } public function retrieve($userId) { $result = $this->reservation->retrieve_reservation($userId); for ($i=0; $i<sizeof($result); $i++){ if ($result[$i]['Date'] < $result[$i]['cDate']){ $this->delete($result[$i]['Id']); } } return $this->reservation->retrieve_reservation($userId); } } ?>
gpl-3.0
hamptus/mftpy
mftpy/mft.2.7/tests/old.gui.py
1581
from wsgiref.util import request_uri, application_uri, shift_path_info from wsgiref.simple_server import make_server import datetime from urlparse import parse_qs from paste import httpserver from webob import Request, Response from mbr import Mbr class RequestHandler(object): template = None def __init__(self): #self.environ = environ #self.start_response = start_response self.response = Response() self.response.status = 200 self.response.content_type = 'text/html' self.response.body = '<html><body>It works!</body></html>' def __call__(self, environ, start_response): self.request = Request(environ) self.start_response = start_response if self.request.method == 'GET': return self.get() def get(self): return self.response(self.request.environ, self.start_response) class MbrHandler(RequestHandler): def get(self): mbr = Mbr(open('/dev/sda', 'rb').read(512)) self.response.body = "<html><body>" self.response.body += mbr.partition1.get_type() self.response.body += "</body></html>" return self.response(self.request.environ, self.start_response) urls = { '/mbr/': MbrHandler, '/': MbrHandler, '/static/', StaticHandler, } class UrlRouter(object): def __call__(self, environ, start_response): request = Request(environ) handler = urls[request.path] return handler().__call__(environ, start_response) httpserver.serve(UrlRouter(), host='127.0.0.1', port=8080)
gpl-3.0
LatvianModder/Silicio
src/main/java/com/latmod/silicio/api_impl/SilCaps.java
1673
package com.latmod.silicio.api_impl; import com.feed_the_beast.ftbl.lib.EmptyCapStorage; import com.latmod.silicio.api.module.IModuleContainer; import com.latmod.silicio.api.pipes.IPipe; import com.latmod.silicio.api.pipes.IPipeConnection; import com.latmod.silicio.api.tile.ISilNetTile; import com.latmod.silicio.api.tile.ISocketBlock; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; /** * Created by LatvianModder on 16.09.2016. */ public class SilCaps { @CapabilityInject(IModuleContainer.class) public static Capability<IModuleContainer> MODULE_CONTAINER = null; @CapabilityInject(ISilNetTile.class) public static Capability<ISilNetTile> SILNET_TILE = null; @CapabilityInject(ISocketBlock.class) public static Capability<ISocketBlock> SOCKET_BLOCK = null; @CapabilityInject(IPipe.class) public static Capability<IPipe> PIPE = null; @CapabilityInject(IPipe.class) public static Capability<IPipeConnection> PIPE_CONNECTION = null; public static void init() { CapabilityManager.INSTANCE.register(IModuleContainer.class, new EmptyCapStorage<>(), () -> null); CapabilityManager.INSTANCE.register(ISilNetTile.class, new EmptyCapStorage<>(), () -> null); CapabilityManager.INSTANCE.register(ISocketBlock.class, new EmptyCapStorage<>(), () -> null); CapabilityManager.INSTANCE.register(IPipe.class, new EmptyCapStorage<>(), () -> null); CapabilityManager.INSTANCE.register(IPipeConnection.class, new EmptyCapStorage<>(), () -> null); } }
gpl-3.0
gouchangjiang/opengeoda
Regression/SparseVector.cpp
5017
/** * OpenGeoDa TM, Copyright (C) 2011 by Luc Anselin - all rights reserved * * This file is part of OpenGeoDa. * * OpenGeoDa is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGeoDa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include "../ShapeOperations/shp.h" #include "../ShapeOperations/shp2cnt.h" #include "mix.h" #include "SparseVector.h" SparseVector::SparseVector(const int sz) : size(0), nzEntries(0), val(NULL), nz(NULL), isNz(NULL) { if (sz <= 0) error(" size of vector must be positive "); size = sz; nzEntries = 0; denseReady = true; val = new double[ sz ]; nz = new int[ sz ]; isNz = new bool[ sz ]; if (!val || !nz || !isNz) error("fail to allocate"); for (int cnt = 0; cnt < size; ++cnt) { val[ cnt ] = 0; isNz[ cnt ] = false; }; } SparseVector::~SparseVector() { release(&val); release(&nz); release(&isNz); } // sets vector to zero void SparseVector::checkout() { for (int cnt = 0; cnt < nzEntries; ++cnt) { isNz[ nz[cnt] ] = false; val[ nz[cnt] ] = 0; }; nzEntries = 0; } void SparseVector::addTimes(const SparseVector &v, const double &w) { for (int cnt = 0; cnt < v.getNzEntries(); ++cnt) { int ix = v.getIx(cnt); this->plusAt( ix, v.getValue(ix) * w ); } } void SparseVector::minus(const SparseVector &a, const SparseVector &b) { reset(); if (a.size > this->size || b.size > this->size) { msg("vector size does not match"); }; // process all indices that are non-zeros in a. some of them might have corresponding zeros in b. for (int ax = 0; ax < a.nzEntries; ++ax) { int ix = a.nz[ax]; this->setAt( ix, a.val[ix] - b.val[ix] ); }; // process all indices for non-zeros in b. filter out those that have been already processed. for (int bx = 0; bx < b.nzEntries; ++bx) { int ix = b.nz[bx]; if (!a.isNz[ix]) this->setAt( ix, -b.val[ix] ); }; } double SparseVector::norm() const { double scale = 0, ssq = 1, t; for (int cnt = 0; cnt < nzEntries; ++cnt) { double absc = fabs(val[nz[cnt]]); if (scale < absc) { t = scale / absc; ssq = 1.0 + ssq * t *t; scale = absc; } else if (absc > 0) { t = absc / scale; ssq += t * t; }; }; return scale * scale * ssq; } double SparseVector::product(const SparseVector &a) const { double ss = 0; if (this->nzEntries > a.nzEntries) return a.product(*this); for (int cnt = 0; cnt < this->nzEntries; ++cnt) { int ix = this->nz[ cnt ]; if ( a.isNz[ ix ] ) ss += a.val[ ix ] * this->val[ ix ]; }; return ss; } void SparseVector::print(const char * t) const { (*logFile) << " sparse vector "; if (t != NULL) (*logFile) << t; (*logFile) << "\n size: " << size << " non-zeros: " << nzEntries << '\n'; for (int cnt = 0; cnt < nzEntries; ++cnt) { (*logFile).width(4); (*logFile) << cnt << ' '; (*logFile).width(4); (*logFile) << nz[cnt] << " " << val[nz[cnt]] << '\n'; }; } void SparseVector::copy(const SparseVector &a) { this->reset(); for (int cnt = 0; cnt < a.nzEntries; ++cnt) { int ix = a.nz[ cnt ]; this->setAt( ix, a.val[ ix ] ); }; } // multiplies vector by a scalar s and adds vector a void SparseVector::timesPlus(const SparseVector &a, const double &s) { if (s != 1.0) for (int cnt = 0; cnt < this->nzEntries; ++cnt) { this->val[ this->nz[ cnt ] ] *= s; }; for (int cnt = 0; cnt < a.nzEntries; ++cnt) { int ix = a.nz[ cnt ]; this->plusAt( ix, a.val[ ix ] ); }; } void SparseVector::dropZeros() { for (int cnt = 0; cnt < nzEntries; ++cnt) { int ix = nz[cnt]; if (fabs(val[ ix ]) < 1.0e-14) { nz[cnt] = nz[--nzEntries]; isNz[ix] = false; val[ix] = 0; }; }; }
gpl-3.0
beelancer/beelancer-api
lib/routes/task-create.js
2860
/* ** beelancer-api ** author: gordon hall ** ** create-task endpoint */ var endpoint = require('../classes/endpoint.js'); module.exports = endpoint({ method : 'POST', path : '/projects/:projectId/tasks', handler : createTask, params : [ { name : 'title', type : 'string', required : true, message : 'Title of the task to be created' }, { name : 'rate', type : 'number', required : true, message : 'Billable rate in dollars' }, { name : 'isFixedRate', type : 'boolean', required : false, message : 'Flag designating whenther or not this task is billed hourly' }, { name : 'assignee', type : 'string', required : false, message : 'User ID of the team member to which the task will be assigned' } ], description : 'Creates a new task under the specified project', response : '', auth : true }); function createTask(req, res) { var async = require('async') , db = require('../models').get() , body = req.params , ObjectId = new require('mongoose').Types.ObjectId ; async.waterfall( [ getProject, checkUserCanCreateTask, checkAssigneeIsOnTeam, saveTask, referenceTaskFromProject ], respond ); function getProject(next) { db.project.findOne({ _id : body.projectId }) .exec(function(err, project) { if (err) return next(err); if (!project) return next('Project not found.'); next(null, project); }); }; function checkUserCanCreateTask(project, next) { if (project.owner.equals(req.user._id)) return next(null, project); if (~~project.members.indexOf(req.user._id)) return next(null, project); next('You must be on the project team to create a task.'); }; function checkAssigneeIsOnTeam(project, next) { var assignee = (body.assignee) ? new ObjectId(body.assignee) : null; if (!body.assignee) return next(null, project); if (req.user._id == assignee) return next(null, project); if (~req.user.team.indexOf(assignee)) return next('Assignee must be part of your team.'); next(null, project); }; function saveTask(project, next) { var task = new db.task({ title : body.title, rate : body.rate, isFixedRate : body.isFixedRate || false, assignee : body.assignee || null, isBilled : false, owner : req.user._id, isPaid : false, isComplete : false, project : project._id }); task.save(function(err) { if (err) return next(err); next(null, task, project); }); }; function referenceTaskFromProject(task, project, next) { project.tasks.addToSet(task._id); project.save(function(err) { if (err) return next(err); next(null, task); }); }; // respond to caller function respond(err, task) { if (err) return res.send(500, { error : err }); res.send(task); }; };
gpl-3.0
deependhulla/powermail-debian9
files/rootdir/var/www/html/archivesearch/view_archive_mail.php
5092
<?php $smtphost="127.0.0.1"; $smtpport="2525"; $enkey="getkeynowxyz"; function encode($string,$key) { $j=0; $key = sha1($key); $strLen = strlen($string); $keyLen = strlen($key); for ($i = 0; $i < $strLen; $i++) { $ordStr = ord(substr($string,$i,1)); if ($j == $keyLen) { $j = 0; } $ordKey = ord(substr($key,$j,1)); $j++; $hash .= strrev(base_convert(dechex($ordStr + $ordKey),16,36)); } return $hash; } function decode($string,$key) { $key = sha1($key); $strLen = strlen($string); $keyLen = strlen($key); for ($i = 0; $i < $strLen; $i+=2) { $ordStr = hexdec(base_convert(strrev(substr($string,$i,2)),36,16)); if ($j == $keyLen) { $j = 0; } $ordKey = ord(substr($key,$j,1)); $j++; $hash .= chr($ordStr - $ordKey); } return $hash; } #$encoded = encode($globalwebmailuser , $enkey); #echo $encoded; #echo "\n"; #$decoded = decode($encoded, $enkey); #echo $decoded; #echo "\n"; $mfilex=$_GET['mfilex']; $mfile = decode($mfilex, $enkey); #print "--> MFILEX : $mfilex --> $mfile"; $globalwebmailuser=""; $cookie_name = "mailarchiveid"; $loginok=0; if(isset($_COOKIE[$cookie_name])) { $decoded = decode($_COOKIE[$cookie_name], $enkey); if($decoded) { $globalwebmailuser=$decoded; $loginok=1; } } if($loginok==0) { $_COOKIE[$cookie_name]=""; session_destroy(); header("location:/groupoffice/index.php"); exit; } if($loginok==1) { $mailfrom=$globalwebmailuser; #print "Content-type: text/html\n\n"; $e=0; $qsdata=$_SERVER["QUERY_STRING"]; $qsdata=str_replace("..","",$qsdata); $qsdata=str_replace("|","",$qsdata); $qsdata=str_replace(";","",$qsdata); $qsdata=str_replace(":","",$qsdata); $indata=array(); $indata=explode("&",$qsdata); $mfile=""; $forwardto=""; $sendmailnow=""; for($e=0;$e<sizeof($indata);$e++) { $datax=array(); $datax=explode("=",$indata[$e]); if($datax[0]=="mfile"){$mfile=urldecode($datax[1]);} if($datax[0]=="forwardto"){$forwardto=urldecode($datax[1]);} if($datax[0]=="sendmailnow"){$sendmailnow=urldecode($datax[1]);} } #print "aa -> $qsdata --> $mfile -->$forwardto --> $sendmailnow"; #exit; $mfile = decode($mfilex, $enkey); #print "--> MFILEX : $mfilex --> $mfile"; $xfile=$mfile; $zfile=array(); $zfile=explode("/",$mfile); $xfile="/tmp/".$zfile[sizeof($zfile)-1]; #$xfile="/tmp/".$zfile[sizeof($zfile)-1]; $mfile=str_replace("/headerdata/","/maindata/",$mfile); $cmdx="/bin/cp -pRv ".$mfile." ".$xfile." ; /bin/gzip -d ".$xfile.""; $xfile=str_replace(".gz","",$xfile); $cmdxout=`$cmdx`; #print "<hr> $cmdx --> $xfile : $cmdxout<hr>"; require_once 'vendor/autoload.php'; $Parser = new PhpMimeMailParser\Parser(); #print "--> $xfile "; if (file_exists($xfile)) { # echo "The file $filename exists"; } else { #print "NO File"; } $Parser->setPath($xfile); #echo $Parser->getRawHeader('diagnostic-code'); $to = $Parser->getHeader('to'); $from = $Parser->getHeader('from'); $subject = $Parser->getHeader('subject'); $maildatex = $Parser->getHeader('date'); $stringHeaders = $Parser->getHeadersRaw(); // Get all headers as a string, no charset conversion $arrayHeaders = $Parser->getHeaders(); // Get all headers as an array, with charset conversion $text = $Parser->getMessageBody('text'); $html = $Parser->getMessageBody('html'); $htmlem = $Parser->getMessageBody('htmlEmbedded'); //HTML Body included data #print "\n --> $from -->$to --> $subject --> $maildatex"; $from=str_replace("<","&lt;",$from); $to=str_replace("<","&lt;",$to); print "From : ".$from."<br>"; print "To : ".$to."<br>"; print "Subject : ".$subject."<br>"; print "Date : ".$maildatex.""; $attach_dir = $xfile."_attach_tmp/"; // Be sure to include the trailing slash mkdir($attach_dir, 0777, true); $include_inline = false ; $Parser->saveAttachments($attach_dir,[$include_inline]); $attachments = $Parser->getAttachments([$include_inline]); ?> <script> function okf() { document.myform.submit(); } </script> <?php if($sendmailnow =="") { print '<font color=brown><form name="myform" action="view_archive_mail.php" method="GET">Restore/Forward to <input type=text name=forwardto value="'.$forwardto.'" size=30><input type=hidden name=mfilex value="'.$mfilex.'"> <input type=hidden name=sendmailnow value=yes> <input type=button name="sendnow" value="Send Now" onclick="okf();return false;"></form></font>'; } else { $sendnowx="sendEmail -f ".$mailfrom." -t ".$forwardto." -s ".$smtphost.":".$smtpport." -o message-format=raw -o message-file=".$xfile." -o tls=no "; $cc=`$sendnowx`; #print "<br> Mail send <br> $sendnowx"; print "<br><font color=green> Mail send ".$cc."</font>"; } // Loop through all the Attachments if (count($attachments) > 0) { print "<hr>"; foreach ($attachments as $attachment) { echo '<a href="downloadatt.php?folder='.$attach_dir.'&filex='.$attachment->getFilename().'">'.$attachment->getFilename().' ('.filesize($attach_dir.$attachment->getFilename()).' Bytes)</a><br />'; } } print "<hr>"; $donex=0; #if($html !=""){print "".$html."<hr>"; $donex=1;} if($htmlem !=""){print "".$htmlem."<hr>"; $donex=1;} if($html !="" && $donex==0){print "".$html."<hr>"; $donex=1;} if($donex==0){print "<pre>".$text."</pre><hr>";} } ?>
gpl-3.0
GH1995/tools
archives/cpp-primer-5th/VisualStudio2012/4/sizeof_pgm.cpp
2980
/* * This file contains code from "C++ Primer, Fifth Edition", by Stanley B. * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Permissions Department * One Lake Street * Upper Saddle River, NJ 07458 * Fax: (201) 236-3290 */\r/\r/g #include "Version_test.h" #include <iostream> using std::cout; using std::endl; #include "Sales_data.h" int main() { Sales_data data, *p; sizeof(Sales_data); // size required to hold an object of type Sales_data sizeof data; // size of data's type, i.e., sizeof(Sales_data) sizeof p; // size of a pointer sizeof *p; // size of the type to which p points, i.e., sizeof(Sales_data) sizeof data.revenue; // size of the type of Sales_data's revenue member #ifdef SIZEOF_MEMBER sizeof Sales_data::revenue; // alternative way to get the size of revenue #else sizeof Sales_data().revenue; // use an object #endif cout << "short: " << sizeof(short) << "\n" << "short[3]: " << sizeof(short[3]) << "\n" << "short*: " << sizeof(short*) << "\n" << "short&: " << sizeof(short&) << endl; cout << endl; cout << "int: " << sizeof(int) << "\n" << "int[3]: " << sizeof(int[3]) << "\n" << "int*: " << sizeof(int*) << "\n" << "int&: " << sizeof(int&) << endl; cout << endl; cout << "Sales_data: " << sizeof(Sales_data) << "\n" << "Sales_data[3]: " << sizeof(Sales_data[3]) << "\n" << "Sales_data*: " << sizeof(Sales_data*) << "\n" << "Sales_data&: " << sizeof(Sales_data&) << endl; #ifdef SIZEOF_MEMBER cout << "Sales_data::revenue: " << sizeof Sales_data::revenue << "\n" #else cout << "Sales_data().revenue: " << sizeof Sales_data().revenue << "\n" << "data.revenue: " << sizeof data.revenue << endl; #endif int x[10]; int *ip = x; // number of elements in x cout << sizeof(x)/sizeof(*x) << endl; // divides sizeof a pointer by sizeof an int cout << sizeof(ip)/sizeof(*ip) << endl; return 0; }
gpl-3.0
cSploit/android.MSF
modules/auxiliary/scanner/http/rewrite_proxy_bypass.rb
3587
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit4 < Msf::Auxiliary include Msf::Exploit::Remote::HttpClient include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'Apache Reverse Proxy Bypass Vulnerability Scanner', 'Description' => %q{ Scan for poorly configured reverse proxy servers. By default, this module attempts to force the server to make a request with an invalid domain name. Then, if the bypass is successful, the server will look it up and of course fail, then responding with a status code 502. A baseline status code is always established and if that baseline matches your test status code, the injection attempt does not occur. "set VERBOSE true" if you are paranoid and want to catch potential false negatives. Works best against Apache and mod_rewrite }, 'Author' => ['chao-mu'], 'License' => MSF_LICENSE, 'References' => [ ['URL', 'http://www.contextis.com/research/blog/reverseproxybypass/'], ['CVE', '2011-3368'], ] ) register_options( [ OptString.new('ESCAPE_SEQUENCE', [true, 'Character(s) that terminate the rewrite rule', '@']), OptString.new('INJECTED_URI', [true, 'String injected after escape sequence', '...']), OptInt.new('EXPECTED_RESPONSE', [true, 'Status code that indicates vulnerability', 502]), OptString.new('BASELINE_URI', [true, 'Requested to establish that EXPECTED_RESPONSE is not the usual response', '/']), ], self.class) end def make_request(host, uri, timeout=20) begin requested_at = Time.now.utc response = send_request_raw({'uri' => uri}, timeout) responded_at = Time.now.utc rescue ::Rex::ConnectionError => e vprint_error e.to_s return nil end if response.nil? vprint_error "#{rhost}:#{rport} Request timed out" return nil end seconds_transpired = (responded_at - requested_at).to_f vprint_status "#{rhost}:#{rport} Server took #{seconds_transpired} seconds to respond to URI #{uri}" status_code = response.code vprint_status "#{rhost}:#{rport} Server responded with status code #{status_code} to URI #{uri}" return { :requested_at => requested_at, :responded_at => responded_at, :status_code => status_code } end def run_host(host) test_status_code = datastore['EXPECTED_RESPONSE'] baseline = make_request(host, datastore['BASELINE_URI']) if baseline.nil? return end if baseline[:status_code] == test_status_code vprint_error "#{rhost}:#{rport} The baseline status code for #{host} matches our test's" return end uri = datastore['ESCAPE_SEQUENCE'] + datastore['INJECTED_URI'] injection_info = make_request(host, uri, 60) status_code = injection_info[:status_code] if status_code == test_status_code print_good "#{rhost}:#{rport} Server appears to be vulnerable!" report_vuln( :host => host, :port => rport, :proto => 'tcp', :sname => ssl ? 'https' : 'http', :name => self.name, :info => "Module #{self.fullname} obtained #{status_code} when requesting #{uri}", :refs => self.references, :exploited_at => injection_info[:requested_at] ) end end end
gpl-3.0
fikrimuhal/kmlk
web-app/common/theme/scripts/demo/image_crop.js
2024
/* ========================================================== * FLAT KIT v1.2.0 * image_crop.js * * http://www.mosaicpro.biz * Copyright MosaicPro * * Built exclusively for sale @Envato Marketplaces * ========================================================== */ $(function() { $('#jcrop-target-1').Jcrop({},function(){ api = this; api.setSelect([130,65,130+350,65+285]); api.setOptions({ bgFade: true }); api.ui.selection.addClass('jcrop-selection'); }); /* * JCrop with preview Example */ // Create variables (in this scope) to hold the API and image size var jcrop_api, boundx, boundy, // Grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), xsize = $pcnt.width(), ysize = $pcnt.height(); function handleTarget2() { $('#jcrop-target-2').Jcrop({ onChange: updatePreview, onSelect: updatePreview, aspectRatio: xsize / ysize },function(){ // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; // Store the API in the jcrop_api variable jcrop_api = this; jcrop_api.setSelect([130,65,130+350,65+285]); jcrop_api.setOptions({ bgFade: true }); jcrop_api.ui.selection.addClass('jcrop-selection'); // Move the preview into the jcrop container for css positioning $preview.appendTo(jcrop_api.ui.holder); }); } function updatePreview(c) { if (parseInt(c.w) > 0) { var rx = xsize / c.w; var ry = ysize / c.h; $pimg.css({ width: Math.round(rx * boundx) + 'px', height: Math.round(ry * boundy) + 'px', marginLeft: '-' + Math.round(rx * c.x) + 'px', marginTop: '-' + Math.round(ry * c.y) + 'px' }); } }; handleTarget2(); });
gpl-3.0
jonjahren/unity8
tests/mocks/IntegratedLightDM/MockUsersModel.cpp
1307
/* * Copyright (C) 2014 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "MockUsersModel.h" #include <QLightDM/UsersModel> #include <QSortFilterProxyModel> QString MockUsersModel::mockMode() const { QLightDM::UsersModel* qUsersModel = static_cast<QLightDM::UsersModel*>(static_cast<QSortFilterProxyModel*>(sourceModel())->sourceModel()); return qUsersModel->mockMode(); } void MockUsersModel::setMockMode(QString mockMode) { QLightDM::UsersModel* qUsersModel = static_cast<QLightDM::UsersModel*>(static_cast<QSortFilterProxyModel*>(sourceModel())->sourceModel()); if (qUsersModel->mockMode() != mockMode) { qUsersModel->setMockMode(mockMode); Q_EMIT mockModeChanged(mockMode); } }
gpl-3.0
rabbie/syslogagent
SyslogAgentConfig/NTSyslogCtrlDlg.cpp
35428
// NTSyslogCtrlDlg.cpp : implementation file // #include "..\Syslogserver\common_stdafx.h" //#include "stdafx.h" #include "NTSyslogCtrl.h" #include "NTService.h" #include "NTSyslogCtrlDlg.h" #include "ConfAppl.h" #include "ConfigLogging.h" #include "process.h" #include <shlobj.h> #include "..\Syslogagent\RegistrySettings.h" #include "..\Syslogserver\common_registry.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void logger(int severity,char *text,...) { va_list args; va_start(args,text); char outText[1024]; _vsnprintf_s(outText,1024,text,args); AfxMessageBox(text, MB_ICONSTOP); } //Dummy, since this is not used in the gui application. For the syslog agent, however, it is used. extern "C" { void CreateMiniDump( EXCEPTION_POINTERS* pep ){ } } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //MAYBE HAVE TO COMMENT THIS OUT AND CALL IT //THE WAY THE OTHER ONE IS CALLED void CNTSyslogCtrlDlg::OnAppAbout() { CAboutDlg aDlg; aDlg.DoModal(); } CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //CDialog(IDD_ABOUTBOX).DoModal(); //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CAboutDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } ///////////////////////////////////////////////////////////////////////////// // CNTSyslogCtrlDlg dialog CNTSyslogCtrlDlg::CNTSyslogCtrlDlg(CWnd* pParent /*=NULL*/) : CDialog(CNTSyslogCtrlDlg::IDD, pParent) { //{{AFX_DATA_INIT(CNTSyslogCtrlDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } //***MUST*** be called ***AFTER*** setting the m_csComputer property for //CNTSyslogCtrlDlg objects void CNTSyslogCtrlDlg::ReadMachineEventLogSettings(int good_query) { HKEY hKeyRemote, hKey; //Sometimes connecting to a remote computer takes a while //Especially if that computer doesn't exist on the network //or is off-line CWaitCursor cWait; //reset the EventlogSelect property & free memory to avoid memory leaks m_csaEventlogSelect.RemoveAll(); m_csaEventlogSelect.FreeExtra(); //set the EventlogSelect size to the default m_csaEventlogSelectSize = 1; //Check if query service status was successful //if it wasn't skip attempting to connect to the registry //Attempting to connect if the computer is unreachable //adds about 15-30 seconds on loading time each time //an unreachable computer is selected if(good_query == TRUE) { // Connect to the selected computer's registry on HKLM if (RegConnectRegistry( (char*)(LPCTSTR)m_csComputer, HKEY_LOCAL_MACHINE, &hKeyRemote) == ERROR_SUCCESS) { CStringArray __tmp; //Open the key to where Windows stores EventLog info if (RegOpenKeyEx( hKeyRemote, EVENTLOG_REG_PATH, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { //Read the subkeys in HKLM\System\CurrentControlSet\Services\Eventlog DWORD no_subkeys, subkey_max_len; if(::RegQueryInfoKey(hKey,NULL,NULL,NULL,&no_subkeys,&subkey_max_len,NULL,NULL,NULL,NULL,NULL,NULL) == ERROR_SUCCESS ) { subkey_max_len++; m_csaEventlogSelectSize = no_subkeys; //loop until done reading all subkeys for(DWORD index = 0; index < no_subkeys; index++ ) { CString buffer; DWORD buffer_size = subkey_max_len; LONG retval = RegEnumKeyEx( hKey, index, buffer.GetBuffer(buffer_size), &buffer_size, NULL, NULL, NULL, NULL); if(retval == ERROR_SUCCESS && retval != ERROR_NO_MORE_ITEMS) { __tmp.Add((LPCSTR)buffer); }//end if(retval == ERROR_SUCCESS && retval != ERROR_NO_MORE_ITEMS) }//end for(DWORD index = 0; index < no_subkeys; index++ ) }//end if(ReqQueryInfoKey(hKeyRemote,NULL,NULL,NULL,&no_subkeys,&subkey_max_len,NULL,NULL,NUL.NULL,NULL) == ERROR_SUCCESS) //don't need the handles to the Registry anymore RegCloseKey(hKey); RegCloseKey(hKeyRemote); //populate the m_csaEventlogSelect CString array //no apparent need to sort this as RegEnumKeyEx appears //to be returning the registry key names in alphabetical order for(DWORD i = 0; i < no_subkeys; i++) { m_csaEventlogSelect.Add(__tmp.GetAt(i)); }//end for(DWORD i = 0; i < no_subkeys; i++) }//end if (RegOpenKeyEx( hKeyRemote, EVENTLOG_REG_PATH, 0, KEY_READ, &hKey) == ERROR_SUCCESS) }//end if (RegConnectRegistry( (char*)((LPCTSTR)m_csComputer), HKEY_LOCAL_MACHINE, &hKeyRemote) != ERROR_SUCCESS) }//end if(good_query == TRUE) else { //Add extra notification to the soon to be disabled combobox // m_csaEventlogSelect.Add("Error Connecting to Registry"); m_csaEventlogSelect.Add(" "); }//end else clause of if(good_query == TRUE) //Now need to populate the combo box with data // Get pointer to the combo boxe. CComboBox *peType = (CComboBox *)GetDlgItem(IDC_EVENTLOG_SELECT); peType->ResetContent(); // If it doesn't exist stop rather than crashing. Should never happen. if(peType == NULL) { AfxMessageBox("Program error: Dialog now missing controls. This " "message should never appear.", MB_ICONSTOP); CDialog::OnCancel(); } for(DWORD i = 0; i < m_csaEventlogSelectSize; i++) { peType->AddString( m_csaEventlogSelect.GetAt(i)); } //add something here to set the combobox to the first value in the list peType->SelectString(0,m_csaEventlogSelect.GetAt(0)); }//end NYSyslogCtrlDlg::ReadMachineEventLogSettings() void CNTSyslogCtrlDlg::DoDataExchange(CDataExchange* pDX){ CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CNTSyslogCtrlDlg) DDX_Control(pDX, IDC_STATUS_LIGHT, m_StatusIcon); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_APPLICATION_LIST, m_ApplicationList); } BEGIN_MESSAGE_MAP(CNTSyslogCtrlDlg, CDialog) //{{AFX_MSG_MAP(CNTSyslogCtrlDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //erno ON_BN_CLICKED(IDC_SELECT_COMPUTER, OnSelectComputer) ON_WM_TIMER() //ON_BN_CLICKED(IDC_SYSLOGD, OnSyslogd) ON_BN_CLICKED(IDC_EVENTLOG, OnEventLog) ON_BN_CLICKED(IDC_START, OnStartService) ON_BN_CLICKED(IDC_STOP, OnStopService) ON_BN_CLICKED(IDC_ABOUTBOX, OnAppAbout) //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_INSTALL, OnBnClickedInstall) ON_BN_CLICKED(IDC_HELPBOX, OnBnClickedHelp) ON_BN_CLICKED(IDC_FORWARD_EVENTS, OnBnClickedForwardEvents) ON_BN_CLICKED(IDC_FORWARD_APPLICATION, OnBnClickedForwardApplication) ON_BN_CLICKED(IDC_ADD_APPLICATION, OnBnClickedAddApplication) ON_BN_CLICKED(IDC_USEPING, OnBnClickedUseping) ON_LBN_SELCHANGE(IDC_APPLICATION_LIST, OnLbnSelchangeApplicationList) ON_BN_CLICKED(IDC_REMOVEAPPLICATION, OnBnClickedRemoveapplication) ON_BN_CLICKED(IDC_EDIT_APPLICATION, OnBnClickedEditApplication) ON_BN_CLICKED(IDCANCEL, OnBnClickedCancel) ON_MESSAGE(WM_HELP, OnHelpCommand) ON_EN_CHANGE(IDC_FILTERARRAY, OnEnChangeFilterarray) ON_BN_CLICKED(IDC_USE_MIRROR, OnBnClickedUseMirror) ON_BN_CLICKED(IDC_RADIO_UDP, OnBnClickedRadioUdp) ON_BN_CLICKED(IDC_RADIO_UDP_PING, OnBnClickedRadioUdpPing) ON_BN_CLICKED(IDC_RADIO_TCP, OnBnClickedRadioTcp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CNTSyslogCtrlDlg message handlers BOOL CNTSyslogCtrlDlg::OnInitDialog(){ CString keyName; CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon //Disable tcp support - it's not tested and a new version needed to be published. GetDlgItem( IDC_RADIO_TCP)->ShowWindow(false); // Load last computer from the registry m_csComputer = AfxGetApp()->GetProfileString( COMPUTERS_SECTION, LAST_COMPUTER_ENTRY); SetComputerName(); int queryserviceresults = ( QueryServiceStatus() ) ? 1 : 0; SetMainDialogControls(queryserviceresults); ReadMachineEventLogSettings(queryserviceresults); //Read syslog server reg info OpenRegistry(NTSYSLOG_SYSLOG_KEY); ReadRegKey(&reg_primary,_T("0.0.0.0"),PRIMARY_SYSLOGD_ENTRY); ReadRegKey(&reg_secondary,_T("0.0.0.0"),BACKUP_SYSLOGD_ENTRY); ReadRegKey(&m_usePing,false,USE_PING_ENTRY); ReadRegKey(&m_deliveryMode,false,TCP_DELIVERY); if (m_usePing|m_deliveryMode) GetDlgItem( IDC_USE_MIRROR)->EnableWindow( FALSE); bool ForwardApplication,ForwardEvents, ForwardToMirror; ReadRegKey(&ForwardToMirror,false,FORWARDTOMIRROR); if (!ForwardToMirror) { GetDlgItem( IDC_BACKUP_SYSLOGD)->EnableWindow( FALSE); GetDlgItem( IDC_PORT2)->EnableWindow( FALSE); } ReadRegKey(&ForwardApplication,false,FORWARDAPPLICATIONLOGS); ReadRegKey(&ForwardEvents,true,FORWARDEVENTLOGS); ReadRegKey((unsigned int*)&reg_Port,514,PORT_ENTRY); ReadRegKey((unsigned int*)&reg_Port2,514,PORT_BACKUP_ENTRY); ReadRegKey(&reg_FilterArray,"",EVENTIDFILTERARRAY); CloseRegistry(); //fill application log listBox UpdateApplicationList(); //Set syslog server info in window SetDlgItemText( IDC_PRIMARY_SYSLOGD, (LPCTSTR)reg_primary); SetDlgItemText( IDC_BACKUP_SYSLOGD, (LPCTSTR)reg_secondary); CheckDlgButton(IDC_FORWARD_APPLICATION, ForwardApplication); CheckDlgButton(IDC_FORWARD_EVENTS, ForwardEvents); CheckDlgButton(IDC_USE_MIRROR, ForwardToMirror); SetDlgItemInt(IDC_PORT,reg_Port,TRUE); SetDlgItemInt(IDC_PORT2,reg_Port2,TRUE); //Set radio button if (m_deliveryMode==1) { //TCP CheckDlgButton(IDC_RADIO_TCP, true); } else { if (m_usePing==0) CheckDlgButton(IDC_RADIO_UDP, true); else CheckDlgButton(IDC_RADIO_UDP_PING, true); } CheckDlgButton(IDC_USEPING, m_usePing); SetDlgItemText( IDC_FILTERARRAY, (LPCTSTR)reg_FilterArray); // KillTimer(2); //Otherwise popup 'change settings' after initialization SetTimer( 1, 1000, NULL); SetTimer( 2, 1000, NULL); m_RestartServiceQuestionPlanned=false; return TRUE; // return TRUE unless you set the focus to a control } void CNTSyslogCtrlDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CNTSyslogCtrlDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CNTSyslogCtrlDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CNTSyslogCtrlDlg::OnSelectComputer() { //Erno This code can not be reached now. Button 'Select computer', that supported remote configuration, was removed. // Remote installation is instead performed via commandLine/A.D./Logon scripts/SMS/... // The original only supported service configuration, not installation (=reason not to support it, lots of work) /* CSelectServerDlg cDlg; cDlg.SetCurrentComputer( m_csComputer); if (cDlg.DoModal() == IDCANCEL) return; //Set a wait cursor -- PERHAPS THIS IS CONFUSING THE ISSUE CWaitCursor cWait; m_csComputer = cDlg.GetNewComputer(); // Write computer name to the registry AfxGetApp()->WriteProfileString( COMPUTERS_SECTION, LAST_COMPUTER_ENTRY, m_csComputer); SetComputerName(); KillTimer( 1); //Check for service on remote machine and set dialog buttons int queryserviceresults = (QueryServiceStatus()) ? 1 : 0; SetMainDialogControls(queryserviceresults); //Setup the dialog with the new machine settings, if any ReadMachineEventLogSettings(queryserviceresults); */ } //This function either enables or disables the contained buttons //from the main dialog. Use 1 to enable, 0 to disable. Any other //buttons added later which require enabling or disabling should //be placed here void CNTSyslogCtrlDlg::SetMainDialogControls(int _i_) { GetDlgItem( IDC_EDIT_APPLICATION)->EnableWindow( _i_); GetDlgItem( IDC_ADD_APPLICATION)->EnableWindow( _i_); GetDlgItem( IDC_EVENTLOG)->EnableWindow( _i_); GetDlgItem( IDC_EVENTLOG_SELECT)->EnableWindow( _i_); } void CNTSyslogCtrlDlg::OnTimer(UINT_PTR nIDEvent) { // Add your message handler code here and/or call default CString csPrimary,csBackup,charPort,csFilterArray; int Port,Port2; CDialog::OnTimer(nIDEvent); if (nIDEvent==1) { if (QueryServiceStatus()) SetTimer( 1, 1000, NULL); } if (nIDEvent==2) { //user changing ip or port settings //Read status GetDlgItemText(IDC_PORT,charPort); Port=atoi(charPort); GetDlgItemText(IDC_PORT2,charPort); Port2=atoi(charPort); GetDlgItemText( IDC_PRIMARY_SYSLOGD, csPrimary); GetDlgItemText( IDC_BACKUP_SYSLOGD,csBackup); GetDlgItemText( IDC_FILTERARRAY,csFilterArray); //if different from registry, save changes and prepare to ask for service restart (via timer) if ((reg_primary!=csPrimary)||(reg_secondary!=csBackup)||(reg_Port!=Port)||(reg_Port2!=Port2)||(reg_FilterArray!=csFilterArray)){ OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&csPrimary,PRIMARY_SYSLOGD_ENTRY); WriteRegKey(&csBackup,BACKUP_SYSLOGD_ENTRY); WriteRegKey((unsigned int*)&Port,PORT_ENTRY); WriteRegKey((unsigned int*)&Port2,PORT_BACKUP_ENTRY); WriteRegKey(&csFilterArray,EVENTIDFILTERARRAY); CloseRegistry(); reg_primary=csPrimary; reg_secondary=csBackup; reg_Port=Port; reg_Port2=Port2; reg_FilterArray=csFilterArray; KillTimer(daTimer); daTimer=SetTimer( 3, 2000, NULL); m_RestartServiceQuestionPlanned=true; } SetTimer( 2, 1000, NULL); } if (nIDEvent==3) { //Time to ask to restart service KillTimer(daTimer); m_RestartServiceQuestionPlanned=false; CheckRestartService(); } } //Check the status of the NTSyslog service on the selected computer BOOL CNTSyslogCtrlDlg::QueryServiceStatus() { CNTScmService myService; CNTServiceControlManager mySCM; SERVICE_STATUS myServiceStatus; CString csComputer; TCHAR InstallStatus[32]; if (!m_csComputer.IsEmpty()) // Set computer in \\computer_name format csComputer.Format( _T( "\\\\%s"), m_csComputer); else csComputer.Empty(); if (!mySCM.Open( csComputer, SC_MANAGER_ALL_ACCESS|GENERIC_READ)) { int apa=GetLastError(); if (apa==5) { AfxMessageBox( _T( "Permission denied to read service status. Please execute program as administrator."), MB_ICONSTOP); exit(0); } DisplayStatus( IDI_ERROR_ICON); SetMainDialogControls(false); return FALSE; } if (!mySCM.OpenService( NTSYSLOG_SERVICE_NAME, SERVICE_QUERY_STATUS, myService)){ //AfxMessageBox( _T( "Error OpenService"), MB_ICONSTOP); DisplayStatus( IDI_ERROR_ICON); mySCM.Close(); SetMainDialogControls(false); return FALSE; } if (!myService.QueryStatus( &myServiceStatus)) { AfxMessageBox( _T( "Error Query"), MB_ICONSTOP); DisplayStatus( IDI_ERROR_ICON); SetMainDialogControls(false); myService.Close(); mySCM.Close(); return FALSE; } //We're only here is status is good GetDlgItemText(IDC_INSTALL,&(InstallStatus[0]),32); if ((strcmp(InstallStatus,"Uninstall"))!=0) { SetDlgItemText( IDC_INSTALL, _T( "Uninstall")); } SetMainDialogControls(true); myService.Close(); mySCM.Close(); switch (myServiceStatus.dwCurrentState) { case SERVICE_START_PENDING: DisplayStatus( IDI_YELLOW_ICON, myServiceStatus.dwCurrentState); break; case SERVICE_RUNNING: DisplayStatus( IDI_GREEN_ICON); break; case SERVICE_STOP_PENDING: DisplayStatus( IDI_YELLOW_ICON, myServiceStatus.dwCurrentState); break; case SERVICE_STOPPED: DisplayStatus( IDI_RED_ICON); break; case SERVICE_CONTINUE_PENDING: DisplayStatus( IDI_YELLOW_ICON, myServiceStatus.dwCurrentState); break; case SERVICE_PAUSE_PENDING: DisplayStatus( IDI_YELLOW_ICON, myServiceStatus.dwCurrentState); break; case SERVICE_PAUSED: DisplayStatus( IDI_YELLOW_ICON, myServiceStatus.dwCurrentState); break; default: DisplayStatus( IDI_ERROR_ICON); break; } return TRUE; } BOOL CNTSyslogCtrlDlg::DisplayStatus(UINT nIconID, DWORD dwServiceState) { HICON hIcon; TCHAR InstallStatus[32]; if ((hIcon = AfxGetApp()->LoadIcon( nIconID)) == NULL) return FALSE; m_StatusIcon.SetIcon( hIcon); switch (nIconID) { case IDI_GREEN_ICON: // Service started SetDlgItemText( IDC_STATUS, _T( "Service is running.")); GetDlgItem( IDC_START)->EnableWindow( FALSE); GetDlgItem( IDC_STOP)->EnableWindow( TRUE); GetDlgItem( IDC_INSTALL)->EnableWindow( FALSE); break; case IDI_YELLOW_ICON: // Service pending switch (dwServiceState) { case SERVICE_START_PENDING: SetDlgItemText( IDC_STATUS, _T( "Service is starting.")); break; case SERVICE_STOP_PENDING: SetDlgItemText( IDC_STATUS, _T( "Service is stopping.")); break; case SERVICE_CONTINUE_PENDING: SetDlgItemText( IDC_STATUS, _T( "Service is leaving pause.")); break; case SERVICE_PAUSE_PENDING: SetDlgItemText( IDC_STATUS, _T( "Service is entering in pause.")); break; case SERVICE_PAUSED: SetDlgItemText( IDC_STATUS, _T( "Service is paused.")); break; default: SetDlgItemText( IDC_STATUS, _T( "Unknown state!")); break; } GetDlgItem( IDC_START)->EnableWindow( FALSE); GetDlgItem( IDC_STOP)->EnableWindow( FALSE); break; case IDI_RED_ICON: // Service stopped SetDlgItemText( IDC_STATUS, _T( "Service is stopped.")); GetDlgItem( IDC_START)->EnableWindow( TRUE); GetDlgItem( IDC_STOP)->EnableWindow( FALSE); GetDlgItem( IDC_INSTALL)->EnableWindow( TRUE); break; case IDI_ERROR_ICON: // Error default: GetDlgItemText(IDC_INSTALL,&(InstallStatus[0]),32); if ((strcmp(InstallStatus,"Install"))!=0) { SetDlgItemText( IDC_INSTALL, _T( "Install")); } SetDlgItemText( IDC_STATUS, _T( "Service is not installed.")); GetDlgItem( IDC_START)->EnableWindow( FALSE); GetDlgItem( IDC_STOP)->EnableWindow( FALSE); break; } return TRUE; } void CNTSyslogCtrlDlg::OnEventLog() { CConfigLogging cDlg; // Get pointers to the combo boxes. CComboBox *peType = (CComboBox *)GetDlgItem(IDC_EVENTLOG_SELECT); // If doesn't exist, stop rather than crashing. Should never happen. if(peType == NULL) { AfxMessageBox("Program error: Dialog now missing controls. This " "message should never appear.", MB_ICONSTOP); CDialog::OnCancel(); } // Get the selection. Depends on the dialog having the right items in it. int cur_index = peType->GetCurSel(); // Again, make sure we got values back. if(cur_index == CB_ERR) { AfxMessageBox("Program error: Dialog now returns errors. This " "message should never appear.", MB_ICONSTOP); CDialog::OnCancel(); } cDlg.SetupDialog(m_csaEventlogSelect.GetAt(cur_index), m_csComputer); if (cDlg.DoModal()!=IDCANCEL) CheckRestartService(); } void CNTSyslogCtrlDlg::SetComputerName() { CString csMessage; //erno csMessage.Format( _T( "Service status on computer <%s>..."), //erno (m_csComputer.IsEmpty() ? _T( "Local Machine") : m_csComputer)); csMessage.Format( _T( "Service status")); SetDlgItemText( IDC_COMPUTER, csMessage); } void CNTSyslogCtrlDlg::OnStartService() { // Add your control notification handler code here CNTScmService myService; CNTServiceControlManager mySCM; CString csComputer; CWaitCursor cWait; TCHAR szBuffer[255]; HKEY hKeyRemote,hKeySoftware; DWORD dwValue,dwSize,dwType; //Make sure any very recent changes are considered KillTimer(2); //Otherwise popup 'change settings' after initialization OnTimer(2); KillTimer(3); //dont set restart question flag m_RestartServiceQuestionPlanned=false; // Connect to the registry on HKLM if (RegConnectRegistry( (char*)((LPCTSTR)""), HKEY_LOCAL_MACHINE, &hKeyRemote) != ERROR_SUCCESS) { AfxMessageBox( _T( "Error while connecting to the registry!\n\nPlease retry."), MB_ICONSTOP); return; } // Create the SOFTWARE\SaberNet key or open it if it exists if (RegCreateKeyEx( hKeyRemote, NTSYSLOG_SOFTWARE_KEY, 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL, &hKeySoftware, &dwValue) != ERROR_SUCCESS) { AfxMessageBox( _T( "Error writing new parameters!\n\nCheck permissions to the registry(local machine\\software\\\ndatagram\\syslogagent)\n Please retry."), MB_ICONSTOP); RegCloseKey (hKeyRemote); return; } // Read the primary syslogd server //dwSize = szBuffer.GetLength(); dwSize = 255*sizeof( TCHAR); memset( szBuffer, 0, 255*sizeof( TCHAR)); if (RegQueryValueEx( hKeySoftware, PRIMARY_SYSLOGD_ENTRY, 0, &dwType, (LPBYTE) szBuffer, &dwSize) != ERROR_SUCCESS) { AfxMessageBox( _T( "Please enter primary IP address before starting service."), MB_ICONSTOP); RegCloseKey (hKeySoftware); RegCloseKey( hKeyRemote); return; } RegCloseKey (hKeySoftware); RegCloseKey( hKeyRemote); if ((strcmp(szBuffer,"")==0)||(strcmp(szBuffer,"0.0.0.0")==0)) { AfxMessageBox( _T( "No Syslog Server address has been entered!\n\nPlease enter address before starting service."), MB_ICONSTOP); return; } if (!m_csComputer.IsEmpty()) // Set computer in \\computer_name format csComputer.Format( _T( "\\\\%s"), m_csComputer); else csComputer.Empty(); if (!mySCM.Open( csComputer, SC_MANAGER_ALL_ACCESS|GENERIC_READ)) { AfxMessageBox( _T( "Unable to contact Service Control Manager!"), MB_ICONSTOP); return; } if (!mySCM.OpenService( NTSYSLOG_SERVICE_NAME, SERVICE_START, myService)) { mySCM.Close(); AfxMessageBox( _T( "Unable to send command to Service Control Manager!"), MB_ICONSTOP); return; } if (!myService.Start( 0, NULL)) { myService.Close(); mySCM.Close(); AfxMessageBox( _T( "Error while sending command to Service Control Manager!"), MB_ICONSTOP); return; } myService.Close(); mySCM.Close(); GetDlgItem( IDC_INSTALL)->EnableWindow( FALSE); QueryServiceStatus(); } void CNTSyslogCtrlDlg::OnStopService() { // Add your control notification handler code here CNTScmService myService; CNTServiceControlManager mySCM; CString csComputer; CWaitCursor cWait; if (!m_csComputer.IsEmpty()) // Set computer in \\computer_name format csComputer.Format( _T( "\\\\%s"), m_csComputer); else csComputer.Empty(); if (!mySCM.Open( csComputer, SC_MANAGER_ALL_ACCESS|GENERIC_READ)) { AfxMessageBox( _T( "Unable to contact Service Control Manager!"), MB_ICONSTOP); return; } if (!mySCM.OpenService( NTSYSLOG_SERVICE_NAME, SERVICE_STOP, myService)) { mySCM.Close(); AfxMessageBox( _T( "Unable to send command to Service Control Manager!"), MB_ICONSTOP); return; } if (!myService.Stop()) { myService.Close(); mySCM.Close(); AfxMessageBox( _T( "Error while sending command to Service Control Manager!"), MB_ICONSTOP); return; } myService.Close(); mySCM.Close(); QueryServiceStatus(); } void CNTSyslogCtrlDlg::OnBnClickedInstall(){ // Add your control notification handler code here CNTScmService myService; CNTServiceControlManager mySCM; CString csComputer; CWaitCursor cWait; TCHAR szModulePathname[260]; TCHAR InstallStatus[32]; szModulePathname[0]=_T('"'); LPCTSTR Dapointer=&szModulePathname[0]; DWORD dwLength=GetModuleFileName(NULL, &szModulePathname[1], _MAX_PATH); if( dwLength ) { while( dwLength && szModulePathname[ dwLength ] != _T('\\') ) { dwLength--; } if( dwLength ) szModulePathname[ dwLength + 1 ] = _T('\000'); } _tcscat_s(szModulePathname,SYSLOG_AGENT_NAME); _tcscat_s(szModulePathname,"\""); GetDlgItemText(IDC_INSTALL,&(InstallStatus[0]),32); if ((strcmp(InstallStatus,"Install"))==0) { CNTService myCNTService(Dapointer,"Syslog Agent","Syslog Agent",(DWORD)0xFF,"Forwards Event logs to Syslog Server"); myCNTService.Install(); initRegistry(NULL); OnInitDialog(); ReadMachineEventLogSettings(true); } else if ((strcmp(InstallStatus,"Uninstall"))==0) { m_csComputer.IsEmpty(); // if (!mySCM.Open( csComputer, SC_MANAGER_ALL_ACCESS|GENERIC_READ)) if (!mySCM.Open( csComputer, SC_MANAGER_ALL_ACCESS)) { DisplayStatus( IDI_ERROR_ICON); return ; } if (!mySCM.OpenService( NTSYSLOG_SERVICE_NAME, SERVICE_ALL_ACCESS, myService)) { DisplayStatus( IDI_ERROR_ICON); mySCM.Close(); return; } if (!myService.Delete()){ DisplayStatus( IDI_ERROR_ICON); AfxMessageBox( _T( "Failed to delete service!"), MB_ICONSTOP); myService.Close(); mySCM.Close(); return; } myService.Close(); mySCM.Close(); } else { AfxMessageBox( _T( "String compare failed!"), MB_ICONSTOP); } QueryServiceStatus(); } void CNTSyslogCtrlDlg::OnBnClickedHelp() //well, actually helpbutton.. { char temp[256]="",hlpfilepath[512]; // Get full pathname of the exe-files DWORD dwLength=GetModuleFileName(NULL, &temp[0], (sizeof(temp) / sizeof(temp[0]))); if( dwLength ) { while( dwLength && temp[ dwLength ] != _T('\\') ) { dwLength--; } if( dwLength ) temp[ dwLength + 1 ] = _T('\000'); } sprintf_s(hlpfilepath,"%s%s",temp,"Datagram SyslogAgent manual.pdf"); _spawnlp( _P_NOWAIT ,"hh.exe","hh.exe",hlpfilepath,NULL ); } void CNTSyslogCtrlDlg::OnBnClickedForwardEvents(){ bool theBool; //Set and store now value if (IsDlgButtonChecked(IDC_FORWARD_EVENTS)) theBool=true; else theBool=false; OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&theBool,FORWARDEVENTLOGS); CloseRegistry(); CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedForwardApplication(){ bool theBool; if (IsDlgButtonChecked(IDC_FORWARD_APPLICATION)) theBool=true; else theBool=false; OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&theBool,FORWARDAPPLICATIONLOGS); CloseRegistry(); //If any application logging configured, ask for restart of service if (m_ApplicationList.GetCount()>0) CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedUseping(){ bool aBool; OpenRegistry(NTSYSLOG_SYSLOG_KEY); if (IsDlgButtonChecked(IDC_USEPING)){ aBool=true; AfxMessageBox( _T( "Please note that this option only affects Event logging, not application\nlogging, as SyslogAgent does not control the application logs."),MB_OK); } else { aBool=false; } WriteRegKey(&aBool,USE_PING_ENTRY); CloseRegistry(); CheckRestartService(); } void CNTSyslogCtrlDlg::OnLbnSelchangeApplicationList(){ // Add your control notification handler code here } void CNTSyslogCtrlDlg::UpdateApplicationList(void){ //fill application log listBox CString keyName; m_ApplicationList.ResetContent(); OpenRegistry(NTSYSLOG_SYSLOG_KEY); GoToRegKey(APPLICATIONLOGS); while (GetNextKey(&keyName)) { m_ApplicationList.AddString(keyName); } CloseRegistry(); } void CNTSyslogCtrlDlg::OnBnClickedAddApplication(){ CConfAppl cDlg; //cDlg.SetCurrentComputer( m_csComputer); if (cDlg.DoModal() == IDCANCEL) return; UpdateApplicationList(); CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedRemoveapplication(){ int index; CString name; index=m_ApplicationList.GetCurSel(); m_ApplicationList.GetText(index,name); m_ApplicationList.DeleteString(index); if (name=="") { return; //nothing chosen } //Remove from registry OpenRegistry(NTSYSLOG_SYSLOG_KEY); GoToRegKey(APPLICATIONLOGS); DeleteKey(name); CloseRegistry(); CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedEditApplication() { int index; CString name; CConfAppl cDlg; //Ge info om vilken application som ska editeras index=m_ApplicationList.GetCurSel(); if (index==-1) { //Nothing selected return; } m_ApplicationList.GetText(index,name); cDlg.SetupDialog(name); //cDlg.SetCurrentComputer( m_csComputer); if (cDlg.DoModal() == IDCANCEL) return; UpdateApplicationList(); CheckRestartService(); } void CNTSyslogCtrlDlg::CheckRestartService(void){ CString text; //Service not stopped? GetDlgItemText(IDC_STATUS,text); if (text!="Service is running.") { return; } //Restart? if (AfxMessageBox( _T( "Service must be restarted for any new settings to take effect. Restart service now?"),MB_YESNO|MB_ICONQUESTION) == IDYES) { OnStopService(); GetDlgItemText(IDC_STATUS,text); while(text!="Service is stopped.") { QueryServiceStatus(); GetDlgItemText(IDC_STATUS,text); Sleep(300); } Sleep(200); OnStartService(); } } void CNTSyslogCtrlDlg::OnBnClickedCancel(){ // ehh, quit actually... CString csPrimary,csBackup,charPort,csFilterArray; int Port,Port2; GetDlgItemText( IDC_PRIMARY_SYSLOGD, csPrimary); if (csPrimary=="0.0.0.0") { if (AfxMessageBox( _T( "No Syslog Server address has been entered!\n\nNo entries will be sent. Quit anyway?"),MB_YESNO|MB_ICONQUESTION) == IDNO) { return; } } if (m_RestartServiceQuestionPlanned) { //user makes change, then exits quickly... KillTimer(daTimer); m_RestartServiceQuestionPlanned=false; CheckRestartService(); } else {//check if user has changed stuff //Read status GetDlgItemText(IDC_PORT,charPort); Port=atoi(charPort); GetDlgItemText(IDC_PORT2,charPort); Port2=atoi(charPort); GetDlgItemText( IDC_PRIMARY_SYSLOGD, csPrimary); GetDlgItemText( IDC_BACKUP_SYSLOGD,csBackup); GetDlgItemText( IDC_FILTERARRAY,csFilterArray); //if different from registry, save changes and prepare to ask for service restart (via timer) if ((reg_primary!=csPrimary)||(reg_secondary!=csBackup)||(reg_Port!=Port)||(reg_Port2!=Port2)||(reg_FilterArray!=csFilterArray)){ OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&csPrimary,PRIMARY_SYSLOGD_ENTRY); WriteRegKey(&csBackup,BACKUP_SYSLOGD_ENTRY); WriteRegKey((unsigned int*)&Port,PORT_ENTRY); WriteRegKey((unsigned int*)&Port2,PORT_BACKUP_ENTRY); WriteRegKey(&csFilterArray,EVENTIDFILTERARRAY); CloseRegistry(); reg_primary=csPrimary; reg_secondary=csBackup; reg_Port=Port; reg_Port2=Port2; reg_FilterArray=csFilterArray; CheckRestartService(); Sleep(1000); } } OnCancel(); } LRESULT CNTSyslogCtrlDlg::OnHelpCommand(WPARAM wParam, LRESULT lParam) { #ifdef SecLog return 0; //No helpfile available #endif OnBnClickedHelp(); return 0; } void CNTSyslogCtrlDlg::OnEnChangeFilterarray(){ // If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // Add your control notification handler code here } void CNTSyslogCtrlDlg::OnBnClickedUseMirror(){ bool theBool; //Set and store now value if (IsDlgButtonChecked(IDC_USE_MIRROR)) { theBool=true; GetDlgItem( IDC_BACKUP_SYSLOGD)->EnableWindow( TRUE); GetDlgItem( IDC_PORT2)->EnableWindow( TRUE); } else { theBool=false; GetDlgItem( IDC_BACKUP_SYSLOGD)->EnableWindow( FALSE); GetDlgItem( IDC_PORT2)->EnableWindow( FALSE); } OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&theBool,FORWARDTOMIRROR); CloseRegistry(); CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedRadioUdp(){ m_deliveryMode=0; m_usePing=0; OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&m_deliveryMode,TCP_DELIVERY); WriteRegKey(&m_usePing,USE_PING_ENTRY); CloseRegistry(); GetDlgItem( IDC_USE_MIRROR)->EnableWindow( TRUE); CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedRadioUdpPing(){ m_deliveryMode=0; m_usePing=1; OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&m_deliveryMode,TCP_DELIVERY); WriteRegKey(&m_usePing,USE_PING_ENTRY); CloseRegistry(); if (IsDlgButtonChecked(IDC_USE_MIRROR)) { AfxMessageBox( _T( "Mirror delivery is only available with standard UDP delivery. Deactivating setting."),MB_ICONINFORMATION); CheckDlgButton(IDC_USE_MIRROR, false); }; OnBnClickedUseMirror(); GetDlgItem( IDC_USE_MIRROR)->EnableWindow( FALSE); CheckRestartService(); } void CNTSyslogCtrlDlg::OnBnClickedRadioTcp(){ m_deliveryMode=1; m_usePing=0; OpenRegistry(NTSYSLOG_SYSLOG_KEY); WriteRegKey(&m_deliveryMode,TCP_DELIVERY); WriteRegKey(&m_usePing,USE_PING_ENTRY); CloseRegistry(); if (IsDlgButtonChecked(IDC_USE_MIRROR)) { AfxMessageBox( _T( "Mirror delivery is only available with standard UDP delivery. Deactivating setting."),MB_ICONINFORMATION); CheckDlgButton(IDC_USE_MIRROR, false); }; OnBnClickedUseMirror(); GetDlgItem( IDC_USE_MIRROR)->EnableWindow( FALSE); CheckRestartService(); } extern "C" { void DEBUGSERVICE(int indentLevel,char *a,...) { //A stub, really. The agent uses this, but the config program does not. } void DEBUGAPPLPARSE(int indentLevel,char *a,...) { //A stub, really. The agent uses this, but the config program does not. } }
gpl-3.0
spbond/language-game
QTGameEditor/GameEditor/mainwindow.cpp
21817
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFileDialog> #include <QString> #include <QGraphicsScene> #include <QPixmap> #include <QFileInfo> #include <QInputDialog> #include <QColorDialog> #include <QCheckBox> #include "FileManager.h" #include <QStringListModel> #include <QDebug> #include <QActionGroup> #include <QMessageBox> #include "dbmap.h" #include "activities.h" #include <map> #include <memory> using std::shared_ptr; #include "badges.h" Ui::MainWindow * MainWindow::ui = new Ui::MainWindow; DBMap * MainWindow::m_scenes = new DBMap(string("scenes")); Activities * MainWindow::m_pairActs = new Activities(QString("pairActs")); Activities * MainWindow::m_matchActs = new Activities(QString("matchActs")); MainDictionary * MainWindow::m_mainDict = new MainDictionary(); DictionarySets * MainWindow::m_dictSets = new DictionarySets(); Badges * MainWindow::m_badges = new Badges(); MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_mapStr("Add New Scene"), m_sceneStr("Add New Activity"), m_hotspotStr(m_mapStr) { ui->setupUi(this); m_BGM.setComboBox(ui->selectBGM); // Main Dictionary ui->wordErrorMsg->setStyleSheet(QString("QLabel { background-color : white; color : red; }")); ui->mainDictView->setModel(&m_mainDictModel); ui->mainDictView->setEditTriggers(QAbstractItemView::NoEditTriggers); // Edit Dictionary Set ui->mainDictView2->setModel(&m_mainDictModel); ui->dictSetView->setModel(&m_dictSetModel); ui->dictSetView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->dictSetName->setValidator(new QRegExpValidator( QRegExp("[ŁłA-Za-z0-9_]+"), this )); // Badges ui->badgesView->setModel(&m_badgesModel); ui->badgesView->setEditTriggers(QAbstractItemView::NoEditTriggers); //ui->badgeName->setValidator(new QRegExpValidator(QRegExp("[ -~]+"))); // no Łł because game app only takes string not wstring ui->screenName->setValidator(new QRegExpValidator( QRegExp("[A-Za-z0-9_]+"), this )); MyRect::m_soundApp = &m_soundApp; m_soundApp.start(QString(".\\SFML_SOUND")); ui->goToScene->insertItems(1, m_scenes->list()); ui->graphicsView->setEditorType(ScreenQGV::NONE); setupScreenQGVWidgets(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { QWidget::closeEvent(event); } void MainWindow::on_loadBGI_clicked() { QString selfilter = tr("All files (*.jpg *.jpeg *.png *bmp)"); QString filepath = QFileDialog::getOpenFileName( this, QString("Select Background Image"), QString(""), tr("All files (*.jpg *.jpeg *.png *bmp);;JPEG (*.jpg *.jpeg);;PNG (*.png);; BMP (*.bmp)" ), &selfilter ); if(filepath.isEmpty()) return; QString newFile = m_fileManager.copyFile(filepath, FileManager::IMG); ui->graphicsView->loadBGI(newFile); } void MainWindow::on_addBGM_clicked() { QString selfilter = tr("All files (*.ogg)"); QString filepath = QFileDialog::getOpenFileName( this, QString("Select Background Music"), QString(""), tr("All files (*.ogg)" ), &selfilter ); if(filepath.isEmpty()) return; QString newFile; if(ui->graphicsView->editorType() == ScreenQGV::MAP) { newFile = m_fileManager.copyFile(filepath, FileManager::MAPBGM); } else if(ui->graphicsView->editorType() == ScreenQGV::SCENE) { newFile = m_fileManager.copyFile(filepath, FileManager::SCNBGM); } else // Activity { newFile = m_fileManager.copyFile(filepath, FileManager::ACTBGM); } m_BGM.add(newFile, 50, 50); } void MainWindow::on_playBGM_clicked(bool checked) { if(checked) { ui->playBGM->setText(QString("Stop Music")); m_BGM.play(); } else { ui->playBGM->setText(QString("Play Music")); m_BGM.stop(); } } void MainWindow::on_delBGM_clicked() { if(ui->selectBGM->currentIndex() == 0) { return; } QString filepath = m_BGM.remove(ui->selectBGM->currentText()); m_fileManager.deleteFile(filepath); ui->selectBGM->removeItem(ui->selectBGM->currentIndex()); ui->selectBGM->setCurrentIndex(0); ui->vol->setEnabled(false); ui->pitch->setEnabled(false); } void MainWindow::on_selectBGM_activated(const QString &arg1) { if(ui->selectBGM->currentIndex() == 0) { ui->vol->setEnabled(false); ui->pitch->setEnabled(false); return; } ui->vol->setEnabled(true); ui->pitch->setEnabled(true); ui->vol->setSliderPosition(m_BGM.getVolume(arg1)); ui->pitch->setSliderPosition(m_BGM.getPitch(arg1)); } void MainWindow::on_vol_valueChanged(int value) { if(ui->selectBGM->currentIndex() == 0) return; m_BGM.setVolume(value, ui->selectBGM->currentText()); } void MainWindow::on_pitch_valueChanged(int value) { if(ui->selectBGM->currentIndex() == 0) return; m_BGM.setPitch(value, ui->selectBGM->currentText()); } void MainWindow::on_addImg_clicked() { QString selfilter = tr("All files (*.jpg *.jpeg *.png *bmp)"); QString filepath = QFileDialog::getOpenFileName( this, QString("Select Image"), QString(""), tr("All files (*.jpg *.jpeg *.png *bmp);;JPEG (*.jpg *.jpeg);;PNG (*.png);; BMP (*.bmp)" ), &selfilter ); if(filepath.isEmpty()) return; QString newFile = m_fileManager.copyFile(filepath, FileManager::IMG); ui->graphicsView->addImage(newFile, 0, 0, 50, 50); } void MainWindow::on_delBGI_clicked() { QString filepath = ui->graphicsView->getBGIFilepath(); ui->graphicsView->deleteBGI(); } void MainWindow::on_addText_clicked() { bool ok; QString text = QInputDialog::getText(this, tr("Enter text"), tr("Text:"), QLineEdit::Normal, QString(""), &ok); if(ok && !text.isEmpty()) ui->graphicsView->addText(text, 0, 0, 100, 50); } void MainWindow::on_del_clicked() { ui->graphicsView->deleteRect(); } void MainWindow::on_editText_clicked() { MyRect * r = MyRect::m_selectedRect; bool ok; QString text = QInputDialog::getText(this, tr("Enter Text"), tr("Text:"), QLineEdit::Normal, r->getText(), &ok); if(ok && !text.isEmpty()) r->setText(text); } void MainWindow::on_textColor_clicked() { MyRect * r = MyRect::m_selectedRect; QColor col = QColorDialog::getColor(r->getColor(), this, QString("Choose Text Background Color"), QColorDialog::ShowAlphaChannel); if(col.isValid()) r->setColor(col); } void MainWindow::on_imgLines_toggled(bool checked) { ui->graphicsView->toggleLines(checked, ScreenItemType::IMAGE); } void MainWindow::on_hotspotLines_toggled(bool checked) { ui->graphicsView->toggleLines(checked, ScreenItemType::HOTSPOT); } void MainWindow::on_TextLines_toggled(bool checked) { ui->graphicsView->toggleLines(checked, ScreenItemType::TEXT); } void MainWindow::on_addSnd_clicked() { MyRect * r = MyRect::m_selectedRect; QString selfilter = tr("All files (*.wav)"); QString filename = QFileDialog::getOpenFileName( this, QString("Select Sound"), QString(""), tr("All files (*.wav)" ), &selfilter ); if(filename.isEmpty()) return; QString newFile = m_fileManager.copyFile(filename, FileManager::OTHERSND); r->setSndFilepath(newFile); r->setVol(50); r->setPitch(50); ui->addSnd->setHidden(true); ui->delSnd->setHidden(false); ui->sndVolWidg->setHidden(false); ui->sndPitchWidg->setHidden(false); } void MainWindow::on_delSnd_clicked() { MyRect * r = MyRect::m_selectedRect; r->setHasSound(false); ui->addSnd->setHidden(false); ui->delSnd->setHidden(true); ui->sndVolWidg->setHidden(true); ui->sndPitchWidg->setHidden(true); m_fileManager.deleteFile(r->sndFilepath()); } void MainWindow::on_editHLCol_clicked() { MyRect * r = MyRect::m_selectedRect; QColor col = QColorDialog::getColor(r->getColor(), this, QString("Choose Text Background Color"), QColorDialog::ShowAlphaChannel); if(col.isValid()) r->setColor(col); } void MainWindow::on_sndVol_valueChanged(int value) { MyRect * r = MyRect::m_selectedRect; r->setVol(value); } void MainWindow::on_sndPitch_valueChanged(int value) { MyRect * r = MyRect::m_selectedRect; r->setPitch(value); } void MainWindow::on_hovLineEdit_textEdited(const QString &arg1) { MyRect * r = MyRect::m_selectedRect; r->setHoverText(arg1); } void MainWindow::on_order_valueChanged(int arg1) { ui->graphicsView->changeOrder(arg1); } void MainWindow::on_mD_engage_chkBox_toggled(bool checked) { MyRect * r = MyRect::m_selectedRect; r->setMouseDownEngage(checked); } void MainWindow::on_mD_select_chkBox_toggled(bool checked) { MyRect * r = MyRect::m_selectedRect; r->setMouseDownSelect(checked); } void MainWindow::on_mU_engage_chkBox_toggled(bool checked) { MyRect * r = MyRect::m_selectedRect; r->setMouseUpEngage(checked); } void MainWindow::on_mU_select_chkBox_toggled(bool checked) { MyRect * r = MyRect::m_selectedRect; r->setMouseUpSelect(checked); } void MainWindow::on_hov_engage_chkBox_toggled(bool checked) { MyRect * r = MyRect::m_selectedRect; r->setHoverEngage(checked); } void MainWindow::on_hov_select_chkBox_toggled(bool checked) { MyRect * r = MyRect::m_selectedRect; r->setHoverSelect(checked); } void MainWindow::on_widthRatio_valueChanged(int arg1) { ui->graphicsView->updateAspectRatio(); } void MainWindow::on_heightRatio_valueChanged(int arg1) { ui->graphicsView->updateAspectRatio(); } bool MainWindow::remindUserToSave() { if(ui->graphicsView->editorType() == ScreenQGV::NONE) return true; QMessageBox msgBox; msgBox.setText("This a reminder to save any changes."); msgBox.setInformativeText("Do you want to save your changes?"); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); int ret = msgBox.exec(); if(ret == QMessageBox::Cancel) return false; else { ui->playBGM->setText(QString("Play Music")); if(ret == QMessageBox::Save) on_saveEditor_clicked(); } return true; } void MainWindow::on_saveEditor_clicked() { if(ui->graphicsView->editorType() == ScreenQGV::SCENE) { if(ui->screenName->text().isEmpty()) { ui->screenErr->setText(QString("Name cannot be empty.")); return; } if(ui->graphicsView->isAdding()) { ui->graphicsView->setId(m_scenes->add(ui->screenName->text())); if(!ui->graphicsView->id()) { ui->screenErr->setText(QString("Name already exists.")); return; } ui->graphicsView->setisAdding(false); } else if(!m_scenes->rename(ui->graphicsView->id(), ui->screenName->text())) { ui->screenErr->setText(QString("Name already exists.")); return; } } m_fileManager.saveFiles(*(ui->graphicsView), m_BGM); } void MainWindow::on_goToScene_activated(const QString &arg1) { MyRect * r = MyRect::m_selectedRect; if(!ui->goToScene->currentIndex()) { r->setId(0); ui->badgeWidg->setHidden(true); return; } r->setId(m_scenes->id(arg1)); ui->badgeWidg->setHidden(false); } void MainWindow::on_addHotspot_clicked() { ui->graphicsView->addHotspot(0, 0, 50, 50); } void MainWindow::on_addBox_clicked() { ui->graphicsView->addBox(0, 0, 50, 50); } void MainWindow::on_boxLines_toggled(bool checked) { ui->graphicsView->toggleLines(checked, ScreenItemType::BOX); } void MainWindow::setupScreenQGVWidgets() { ui->scrollArea->setHidden(false); ui->screenErr->clear(); ScreenQGV::EditorType edType = ui->graphicsView->editorType(); ui->screenName->setReadOnly(false); ui->actPieceWidg->setHidden(true); if(edType == ScreenQGV::MAP || edType == ScreenQGV::SCENE) { if(edType == ScreenQGV::MAP) { ui->graphicsView->setEditorType(ScreenQGV::MAP); ui->editorType->setText("Map Editor"); ui->screenName->setText("WorldMap"); ui->screenName->setReadOnly(true); ui->goToScene->clear(); ui->goToScene->addItem(QString("Go to Scene")); ui->goToScene->insertItems(1, m_scenes->list()); ui->chooseRewardBadge->setHidden(true); ui->badgeLine->setHidden(true); } else // SCENE { ui->graphicsView->setEditorType(ScreenQGV::SCENE); ui->editorType->setText("Scene Editor"); ui->goToActivity->clear(); ui->goToActivity->addItem(QString("Go to Activity")); QStringList list = m_pairActs->listWithName(QString("Pairing - ")); list.append(m_matchActs->listWithName(QString("Matching - "))); ui->goToActivity->insertItems(1, list); ui->chooseRewardBadge->setHidden(false); ui->badgeLine->setHidden(false); ui->chooseRewardBadge->clear(); ui->chooseRewardBadge->addItem(QString("Choose a Reward Badge")); ui->chooseRewardBadge->insertItems(1, m_badges->list()); ui->chooseRewardBadge->setCurrentText(m_badges->badgeName(ui->graphicsView->rewardBadgeId())); } ui->choicesWidg->setHidden(true); ui->roundsWidg->setHidden(true); ui->selectDictSet->setHidden(true); ui->actLine->setHidden(true); ui->addText->setHidden(false); ui->TextLines->setHidden(false); ui->textLine->setHidden(false); ui->addImg->setHidden(false); ui->imgLines->setHidden(false); ui->imgLine->setHidden(false); ui->addHotspot->setHidden(false); ui->hotspotLines->setHidden(false); ui->hotspotLine->setHidden(false); ui->addBox->setHidden(false); ui->boxLines->setHidden(false); ui->boxLine->setHidden(false); ui->saveEditor->setHidden(false); ui->addScreen->setHidden(true); ui->editScreen->setHidden(true); } else if(edType == ScreenQGV::PAIRACT || edType == ScreenQGV::MATCHACT) { ui->choicesWidg->setHidden(false); ui->roundsWidg->setHidden(false); ui->selectDictSet->setHidden(false); ui->actLine->setHidden(false); ui->addText->setHidden(true); ui->TextLines->setHidden(true); ui->textLine->setHidden(true); ui->addImg->setHidden(true); ui->imgLines->setHidden(true); ui->imgLine->setHidden(true); ui->addHotspot->setHidden(true); ui->hotspotLines->setHidden(true); ui->hotspotLine->setHidden(true); ui->addBox->setHidden(true); ui->boxLines->setHidden(true); ui->boxLine->setHidden(true); ui->saveEditor->setHidden(true); ui->chooseRewardBadge->setHidden(true); ui->badgeLine->setHidden(true); ui->editorType->setText("Activity Editor"); ui->selectDictSet->clear(); ui->selectDictSet->addItem(QString("Choose a Dictionary")); ui->selectDictSet->insertItems(1, m_dictSets->dictSetsList()); ui->selectDictSet->setCurrentText(m_dictSets->dictSetName(ui->graphicsView->dictSetId())); ui->numChoices->setValue(ui->graphicsView->choices()); ui->numRounds->setValue(ui->graphicsView->rounds()); } else // NONE { ui->scrollArea->setHidden(true); } ui->stackedWidget->setCurrentWidget(ui->screenEditor); } void MainWindow::on_addScreen_clicked() { ui->screenErr->clear(); if(ui->dictSetName->text().isEmpty()) { ui->screenErr->setText(QString("The activity\nname cannot be empty.")); return; } if(!ui->selectDictSet->currentIndex()) { ui->screenErr->setText(QString("The activity\nmust have a dictionary set.")); return; } unsigned id; Activities::Activity act; act.name = ui->screenName->text(); act.dictSetId = ui->graphicsView->dictSetId(); if(ui->graphicsView->editorType() == ScreenQGV::PAIRACT) { id = m_pairActs->add(act); } else { id = m_matchActs->add(act); } if(!id) { ui->screenErr->setText(QString("That activity\nname already exists.")); return; } ui->graphicsView->setId(id); m_fileManager.saveFiles(*(ui->graphicsView), m_BGM); ui->stackedWidget->setCurrentWidget(ui->mainMenu); } void MainWindow::on_editScreen_clicked() { ui->screenErr->clear(); if(ui->dictSetName->text().isEmpty()) { ui->screenErr->setText(QString("The activity\nname cannot be empty.")); return; } if(!ui->selectDictSet->currentIndex()) { ui->screenErr->setText(QString("The activity\nmust have a dictionary set.")); return; } unsigned id; Activities::Activity act; act.name = ui->screenName->text(); act.dictSetId = ui->graphicsView->dictSetId(); if(ui->graphicsView->editorType() == ScreenQGV::PAIRACT) { if(!m_pairActs->edit(ui->graphicsView->id(), act)) { ui->screenErr->setText(QString("That activity\nname already exists.")); } } else { if(!m_matchActs->edit(ui->graphicsView->id(), act)) { ui->screenErr->setText(QString("That activity\nname already exists.")); } } m_fileManager.saveFiles(*(ui->graphicsView), m_BGM); ui->stackedWidget->setCurrentWidget(ui->mainMenu); } void MainWindow::on_numChoices_valueChanged(int arg1) { ui->graphicsView->setChoices(arg1); } void MainWindow::on_numRounds_valueChanged(int arg1) { ui->graphicsView->setRounds(arg1); } void MainWindow::on_selectDictSet_activated(const QString &arg1) { if(!ui->selectDictSet->currentIndex()) { ui->graphicsView->setDictSetId(0); return; } ui->graphicsView->setDictSetId(m_dictSets->dictSetId(arg1)); } void MainWindow::on_goToActivity_activated(const QString &arg1) { MyRect * r = MyRect::m_selectedRect; if(!ui->goToActivity->currentIndex()) { if(r->id()) ui->graphicsView->decrementActs(); r->setId(0); ui->actPieceWidg->setHidden(true); return; } QString actType = ui->goToActivity->currentText().section(QChar('-'), 0, 0); actType = actType.remove(QChar(' ')); QString str = ui->goToActivity->currentText().section(QChar('-'), 1, 1); ui->actPieceWidg->setHidden(false); if(!r->id()) { r->setActPieceFilepath(m_fileManager.errorImgFilepath()); ui->actPieceImg->setPixmap(QPixmap(r->actPieceFilepath()).scaled(50, 50, Qt::KeepAspectRatioByExpanding, Qt::FastTransformation)); ui->graphicsView->incrementActs(); } if(actType == QString("Pairing")) { r->setId(m_pairActs->id(str.remove(0, 1))); r->setGameType(GameType::PAIR); } else if(actType == QString("Matching")) { r->setId(m_matchActs->id(str.remove(0, 1))); r->setGameType(GameType::MATCHING); } } void MainWindow::on_selReqBadge_activated(const QString &arg1) { if(!ui->selReqBadge->currentIndex()) { MyRect::m_selectedRect->setCurrBadgeId(0); return; } MyRect::m_selectedRect->setCurrBadgeId(m_badges->id(arg1)); } void MainWindow::on_addBadgeToScn_clicked() { unsigned choice = m_badges->getSelection(); if(!choice) return; MyRect::m_selectedRect->addReqBadge(choice); QString currSelection = ui->selReqBadge->currentText(); ui->selReqBadge->clear(); ui->selReqBadge->addItem(QString("Select a Required Badge")); ui->selReqBadge->insertItems(1, MyRect::m_selectedRect->reqBadgeList()); ui->selReqBadge->setCurrentText(currSelection); } void MainWindow::on_delBadgeFromScn_clicked() { MyRect::m_selectedRect->removeBadge(); ui->selReqBadge->removeItem(ui->selReqBadge->findText(m_badges->badgeName(MyRect::m_selectedRect->currBadgeId()))); } void MainWindow::on_chooseRewardBadge_activated(const QString &arg1) { ui->graphicsView->setRewardBadgeId(m_badges->id(arg1)); } void MainWindow::on_setActPieceImg_clicked() { QString selfilter = tr("All files (*.jpg *.jpeg *.png *bmp)"); QString filepath = QFileDialog::getOpenFileName( this, QString("Select Image"), QString(""), tr("All files (*.jpg *.jpeg *.png *bmp);;JPEG (*.jpg *.jpeg);;PNG (*.png);; BMP (*.bmp)" ), &selfilter ); if(filepath.isEmpty()) return; QString newFile = m_fileManager.copyFile(filepath, FileManager::IMG); MyRect::m_selectedRect->setActPieceFilepath(newFile); ui->actPieceImg->setPixmap(QPixmap(MyRect::m_selectedRect->actPieceFilepath()).scaled(50, 50, Qt::KeepAspectRatioByExpanding, Qt::FastTransformation)); }
gpl-3.0
ryuuken00/Yui
twitch.js
1954
var request = require('request'); const channels = require('./logs/channels.json').channels; const config = require('./config.json'); const embed = require('./logs/embeds.json').twitch; const chalk = require('chalk'); const erroR = chalk.red.bold; const greetings = chalk.cyan.bold; const warning = chalk.yellow; var yui; var interval = setInterval(function() { for (var channel of channels) { let url = `https://api.twitch.tv/kraken/streams/${channel}?client_id=${config.twitchid}`; request({ url: url, json: true }, function(error, response, body) { if (body.stream == null) return; let createdAt = new Date(body.stream.created_at).getTime(); // Time that stream created as milliseconds. let now = new Date().getTime(); // Current time as milliseconds. if ((createdAt + 361000) > now) { setEmbedAndWrite(body); } }); } }, 360000); // 360000 (360 seconds) as 6 minutes function time() { date = new Date(); var lul; lul = `(${date.getDate()}-${date.getMonth()+1}-${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()})`; return lul; } function setEmbedAndWrite(body) { embed.title = body.stream.channel.status; embed.url = body.stream.channel.url; embed.timestamp = body.stream.created_at; embed.thumbnail.url = body.stream.channel.logo; embed.image.url = body.stream.preview.template.replace("{width}x{height}", "400x225"); embed.author.name = body.stream.channel.display_name; embed.author.url = body.stream.channel.url; embed.author.icon_url = body.stream.channel.logo; embed.fields[0].value = body.stream.game; embed.fields[1].value = body.stream.viewers; yui.guilds.get("117353309467181058").defaultChannel.send(`Hey! @here ${body.stream.channel.display_name} yayın açtı. :slight_smile:`, { embed }).then(message => message.delete(1920000)); } function setYui(bot) { yui = bot; } module.exports = { setYui };
gpl-3.0